String pool example






Using immutability of Strings in Java, the JVM can optimize the amount of memory allocated for them by storing only one copy of each literal String in the pool. This process is called interning.
When we create a String variable and assign a value to it, the JVM searches the pool for a String of equal value.

 This  example    explain  you   how   String pool   works   in   Java memory .  To save
 memory.





package Java8;


/**  @author MUkesh Jha  **/
public class Stringpool {

      public static void  stringPool() {
     
         
        String   s1 ="abc";
       
        String   s2 ="abc"  ;
         
        String  s3= new  String ("abc");
       
        String   s4=new   String ("abc");
       
        String   s5=new   String("abc").intern();
       
        String  b= "def";
        String  b2= new String ("def");
             
               
  //        ######  String  Pool Examples #################          
       
          System.out.println( "s1 = =S3" + s1==s3);
         
          System.out.println( "s1==s5" + s1==s5);
            
          System.out.println( "s1.equals(s3) ="+   s1.equals(s3));

          System.out.println( "s4==s2 ==>" +  s4==s2);
          System.out.println( "s2.equals(s4)=" + s2.equals(s4));

          System.out.println( "s5 ->" +s5);
         
              System.out.println( "s1.equals(s5)=" + s1.equals(s5));
              
              System.out.println( " b2 ->" +b2);

      }
public static void main(String[] args) {
// TODO Auto-generated method stub
   
stringPool() ;

}

}












String pool example    String pool   example Reviewed by Mukesh Jha on 1:30 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.