2. What is String in Java?
● String is a sequence of characters
● java.lang.String class is used to create string object.
● How to create String object?
● By string literal
● String s="rakesh";
● By new keyword
● String s=new String("rakesh");
3. String literal vs new keyword
● String C="Java";
● String D="Java"; //will not create new instance
● Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't
exist in the pool, a new string instance is created and placed in the pool.
● In the above example only one object will be created. Firstly JVM will not find any string object with the value "Java" in string constant pool, so it will create a new object. After that it will
find the string with the value "Java" in the pool, it will not create new object but will return the reference to the same instance.
● Why java uses concept of string literal?
● To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
4. String literal vs new keyword
● When you create String object using new() operator, it always create a new object in heap memory.
● String A=new String("Java");
● String B=new String("Java");
6. String literal vs String object approaches
In this case, two objects (A & B) would be created.One would be the same string literal as above and would be
placed in String Constant Pool.Second object would be created and placed in the normal (non pool memory)
and A would refer to it.The second object would act as a normal object in a heap.