String objects are immutable

20 January 2012 By Nithya Vasudevan 2,070 views 3 Comments
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • Once a String object is created, its contents cannot be altered.
  • If you need to change a string, it always creates a new one that contains the modifications and makes the reference variable refer to the new object.
package com.ibytecode.strings.basics;
public class ImmutableStringObjects {
	public static void main(String[] args) {
		String s1 = "iByte"; //Statement 1
		String s2 = s1; //Statement 2
		s2 = s1.concat("Code's"); //Statement 3
		s2 = s2 + " theopentutorials.com"; //Statement 4
		System.out.println("s1 = " + s1);
		System.out.println("s2 = " + s2);
	}
}

s1 = iByte
s2 = iByteCode’s theopentutorials.com

How many String objects and reference variables are created?

  • Two Reference Variables
    1. s1
    2. s2
  • Five String Objects/literals
    1. “iByte”
    2. “Code’s”
    3. “iByteCode’s”
    4. “theopentutorials.com”
    5. “iByteCode’s theopentutorials.com”



  • mohammad irfan

    i just want to updated thigs in java and new one………………

    Thanku.

  • sudhakar p

    keep it up.good job……

  • sudhakar p

    thanks a lot