String Handling in Java - Complete Guide
As you know, whenever you take input or output from the user in Java, you always get String type data. In Java, String is a predefined class. The JVM creates new memory for String all the time - let's understand how JVM manages memory.
What is String in Java?
- String is a group of characters or sequence of characters.
- String is a predefined class in Java which exists in
java.langpackage. - String is a final class in Java - it can never be inherited.
- String class implements
Serializable, Comparable, CharSequenceinterfaces etc. - String objects are immutable - once created, they can never be changed.
- String object is always represented by double quotes.
- You can create String objects in two ways:
- Using Literals Concept
- Using new Keyword
Using Literals Concept
You can create String literals with double quotes:
String name = "Deep Singh";
In case of literals, one reference variable and one object is created.
When you use String literals, JVM first checks in String Pool (Constant Pool). If that object exists, it returns the same address to the reference variable.
Example:
String first = "Deep";
String last = "Singh";
String lname = "Singh"; // Points to same object as last, no new object created
Using new Keyword
You can create String instance with new keyword:
String name = new String("Ashok Singh");
In case of new keyword, one reference variable and two objects are created - one inside String Pool (Constant Pool) and another inside Heap Area.
By default, it points to Heap Area address.
Example:
String name = new String("Ashok Singh");
String Objects are Immutable - Example
String name = "Deep";
name.concat("Singh");
System.out.println(name);
Why? Because String is immutable. concat() creates a new object "Deep Singh" in pool, but reference variable name still points to old object "Deep". To get new value, you must assign: name = name.concat("Singh");
Conclusion
String Pool saves memory by reusing literals. Use literals (String s = "Deep") for memory efficiency. Use new String() only when you explicitly need heap object. Remember String immutability - any modification creates new object.
Next: StringBuffer vs StringBuilder, String Methods, String Comparison (== vs equals)
2 comments:
Very nice sir but am dout in Literals
Can you explan it....
Very nice sir but am dout in Literals
Can you explan it....
Post a Comment