String objects are immutable

  • 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”



Leave a Comment