Strings in Java

Strings in Java

A String is a chain of characters. String Class is provided by Java and it implements strings as object of class String. In this lesson we will learn about Strings in Java.

Create strings in Java using any of the following constructors,

The following creates an empty string,

The following creates a string object. Initialized in the form of array of characters,

The following is another usage of Strings,

Let us see an example of strings,

The following is the output,

Java Strings

Let us see how to concatenate two strings,

String Concatenation in Java

To concat a string in Java, use the String concat() method,

The following is the output,

Java string concatenation
Let us now see why strings are mutable in Java,

Why Strings are Immutable?

Strings in Java cannot be changed, once created. Therefore, String objects are immutable. Remember that this does not apply to reference variables.

An example would make it easier to understand.

Now, referred to str2,

The following displays the text Example,

Now let us use the concat() method,

Printing str1, displays, Example Question, i.e. concatenation,

Printing str2, displays, Example,

Since concatenation did not refer to string str2, therefore the concatenation result is not visible.

Let us now see the methods in String class that allows you to manipulate strings.


String class methods allow easier manipulation of strings in Java. Below the methods are explained with suitable examples.

  • byte getBytes()
    Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
  • int indexOf(int ch)
    Returns the index within this string of the first occurrence of the specified character.
  • String intern()
    Returns a canonical representation for the string object.
  • String toLowerCase()
    Converts all of the characters in this String to lower case using the rules of the default locale.
  • String toUpperCase()
    Converts all of the characters in this String to upper case using the rules of the default locale.
  • String trim()
    Returns a copy of the string, with leading and trailing whitespace omitted.

Reference: Oracle Java String Class

In this lesson we learned how to work with Strings in Java.

Vectors in Java
String chartAt() method in Java
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create free tutorials for all.

No Comments

Post A Comment