Sunday, 6 October 2013

String in Java

You may have used String many time while learning core java and doing some java programms.

So some time you might thought how string works ?. What is string ?...etc
In this post i would try to explore about string.

What is string ?. String is just a class which stores array of characters. You can create an object of string by using new keyword ,as simple in java we use new keyword  to create an object of class,there is an another way to create  string like create string reference and assign a string value.
            i.e String str="core java"
However the string value ("core java") it stores in string pool. When compile sees str="core java" then it uses string pool to store assigned value.Please note that when you use new keyword , it does not use or refer string pool,instead it creates new object and stores value.

Some important points about string pool :
  • This is an area where JVM uses to store string literals. We call string literal when we just create reference of an string and assigns some string value as we did in last example by assigning "core java" string.
  • Suppose you have done . String s="java"; String s1="Core" . In such scenario JVM creates an object of "java" string in string pool,and in second line we are again creating an object s1 having "java" string value.In such scenario JVM does not create another object just it refers object of s.
 While learning some more important things you might why string is immutable . Mutable means once you created an object you can not change its state.I have explained in detail in why string is mutable



No comments:

Post a Comment