Overview


String is a special class built into the Java language defined in the java.lang package.

The String class represents character strings. String literals in Java programs, such as “abc”, are implemented as instances of this class.

For example:

   1:  String str = "This is a string_example";

On the right hand side a String object is created represented by the string literal. Its object reference is assigned to the str variable.

Strings are immutable; that is, they cannot be modified once created. Whenever it looks as if a String object was modified, a new String was actually created and the old one was thrown away.

   1:     public void testNewString(){
   2:          String a = "aaaaa";
   3:          String b = a;
   4:          //now b and a reference the same string object
   5:          System.out.println(b == a);
   6:          //output:true
   7:           a = a.substring(2);
   8:           //a now reference new object 
   9:           System.out.println(b == a);
  10:           System.out.println(b);
  11:           System.out.println(a);
  12:           //output:false
  13:           //       aaaaa
  14:           //       aaa
  15:      }