String pool and & keyword

When you use String literals then it references to String pool.

String s1="abc;
String s2="abc;
String s3=new String("abc");

if(s1==s2){
    System.out.println("Equal");// equal becase pointing to the String pool 
}else{
    System.out.println("Not Equal");
}

if(s1==s3){
   System.out.println("Equal");
}else{
  System.out.println("Not Equal");// it is not equal because s1 is pointig to the String pool and s3 pointing to the heap memory
}

Author: Susheel kumar

Leave a Reply

Your email address will not be published. Required fields are marked *