Java String immutable in nature


            String Objects are designed to be immutable object, Since string are created in memory based on their hashcode value it cannot be changed on its same memory location, If you try to change the string value JVM will create a new memory for it and your reference will be pointed to it.


Try this code to verify it.

package com.candidjava;

public class SampleString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String s1=new String("Candid");
		
		System.out.println("hashcode of candid:  "+s1.hashCode());  // step 1 
		
		s1=s1.concat("java");  // new object will be created
		
		System.out.println("hashcode of candidjava:  "+s1.hashCode());  // step 2
		
	}

}
Output:
hashcode of candid:  2011111119
hashcode of candidjava:  582404465





Related Post

Comments


©candidjava.com