Java String Class

STRINGS IN JAVA

Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation.

Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.

JAVA.LANG.STRING CLASS CREATION

A simple String can be created using a string literal enclosed inside double quotes as shown;

String str1 = “My name is bob”;

Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.

If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon.

In the above code all the String references str1, str2 and str3 denote the same String object, initialized with the character string: “My name is bob”. But the Strings str4 and str5 denote new String objects.

Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (“”), using the string concatenation operator (+).