- 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
- s1
- s2
- Five String Objects/literals
- “iByte”
- “Code’s”
- “iByteCode’s”
- “theopentutorials.com”
- “iByteCode’s theopentutorials.com”