STRING POOL IN JAVA

STRING POOL IN JAVA

http://hacktangle.com/string-pool-in-java/
subash  June 21st,2017

String pool is a pool of strings where created Strings are stored and before creating new String object ,object compiler checks if same string literal is already defined .

As the title says , String pool is pool of Strings .String is special class in java and is immutable . The meaning of String immutable is that we can not change defined String object or simply it is unchangeable .

We can assign string value in two ways .Putting value in double quote directly or using new operator .When a new string value is assigned , compiler checks if it is already in the string pool or not .If it already exists there , it returns the same reference already existed in String pool without creating new String object and if it doesn’t find in String pool , it creates new object , puts in String pool and returns the reference .

Let’s see an example .

String a="hacktangle";

String b="hacktangle";

String c=new String("hacktangle");

Here, all three variables a , b, c have same value hacktangle . We have assigned value for b same as value of a . So , during compilation , compiler checks in the String pool if any object with same value exists or not . It obviously finds a . So , for b , it returns reference of a without creating new object . This saves a little memory .

When it goes to our third way , we are forcing to create new object c to heap and checks whether it exists or not in String pool .It creates new object and returns the reference .

We can check this by using == operator . Let’s check if objects for these are same or not .

System.out.println("a==b:"+a==b);

System.out.println("a==c:"+a==c);

This prints ,

a==b:true

a==c:false

This means , a and b are referencing same object and c is different object than a or b . String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String.

Sometimes in java interview, you will be asked question about String pool. For example, how many string is created  statement below ;

String string = new String("Hacktangle");

In above statement, either 1 or 2 string will be created. If there is already a string literal “Hacktangle” in the pool, then only one string “string” will be created in the pool. If there is no string literal “Hacktangle” in the pool, then it will be first created in the pool and then in the heap space, so total 2 string objects will be created.

扫描二维码关注公众号,回复: 2968557 查看本文章

猜你喜欢

转载自blog.csdn.net/ultrapro/article/details/73550245