Monday, 26 June 2017
What is String class
1) String is part of java.lang package.
2) String is a group of characters. "Hello"
Important Point1:
3) String is immutable. Non changeable.
If we create any string object, we can't modify it's value. But if we try to make any changes, new string will be created with new changes.
Ex: String str = new String("Hello"); //Object1: "Hello"
str.concat(" World!");//Object2: "Hello World!" no reference variable. eligible for garbage collection.
System.out.println(str);//Print object1
StringBuffer is another class from java.lang package. Mutable: We can perform any change in the existing object.
4) StringBuffer stringBuffer = new StringBuffer("Hello");//Object1
stringBuffer.append(" World!");//Object1 stringBuffer reference variable pointing to "Hello World!"
System.out.println(stringBuffer);//Print object1 "Hello World!"
Important Point2:
5) String str1=new String("Hello");
String str2=new String("Hello");
System.out.println(str1 == str2); //False Reference comparison
System.out.println(str1.equals(str2))//True Content comparison;
6) StringBuffer str1=new StringBuffer("Hello");
StringBuffer str2=new StringBuffer("Hello");
System.out.println(str1 == str2); //False Reference comparison
System.out.println(str1.equals(str2))//False Reference comparison;
Important Point3:
Two ways to create string:
String str1=new String("Hello"); //Two Objects will be created. one in HEAP and one in String common pool
String str2="Hello"; //one object will be created in SCP
JVM will check with the required content object is already there in SCP or not. if it's missing then only it makes entry in scp.
GC is not allowed to access SCP. All entries will be removed only when JVM shutdown.
SCP resides in method area.
Important Point4:
String str1=new String("Hello");
String str2=new String("Hello");
String str3="Hello";
String str4="Hello";
Only one entry in SCP.
Two objects in heap.
String str = new String("Spring");//Heap: Object(Spring) SCP: Spring
str.concat("Summer");//Heap: Object(Spring),Object(Spring Summer) SCP: Spring,Summer
String str2 = str.concat("Winter");//Heap: str->Object(Spring),Object(Spring Summer),str2->Object(Spring Winter) SCP: Spring,Summer,Winter
str = str.concat(" Fall");//Heap: Object(Spring),str->Object(Spring Fall),Object(Spring Summer),str2->Object(Spring Winter) SCP: Spring,Summer,Winter,Fall
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment