String in Depth
String in Depth
3 concept
1st
Difference b/w
Heap SCP
In this case two objects will be created one is in the
heap
s1-->manshu manshu
other one is in SCP(String constant pool) and
String s2 = "manshu";
Heap SCP
but
Heap
String s1= new String ("manshu");
String s2 = new String ("manshu"); SCP
String s3 = new String ("manshu"); s1-->manshu
String s4 = new String ("manshu"); s2-->manshu
s3-->manshu manshu
String s5 = new String ("manshu");
s4-->manshu
s5-->manshu
Goals conclusion
shivam
s2--> shivam
String s4 = "shivam";
s3
s4
2nd
== vs equal()
in String class
String s1 = new String("manshu");
String s2 = new String("manshu");
Heap
String s3 = new String("shivam");
SCP
String s4 = "manshu";
s1-->manshu s4->
manshu
String s5 = "manshu"; s2-->manshu
s3 --> shivam
s5->
s6-> shivam
String s6 = "shivam"
no
s1 == s2 ? because both are in heap and
refering to different object Heap
SCP
s1-->manshu s4->
s5-> manshu
s2-->manshu
no
because s1 is in heap pointing to
s1 == s4 ? different than that of s4 which is
Heap
SCP
s5-> manshu
s2-->manshu
s3 --> shivam
s6-> shivam
s1.equal(s4) yes
because both content are same
String s4 = "manshu";
String s5 = "manshu";
Heap
yes
SCP
3rd
Immutability
String can not change
same like
Because of runtime
operation if an object is required to create
compulsory that object should be placed on
the heap but not SCP.
String s=new String("manshu");
s.concat(" shivam");
System.out.println(s);//manshu
Heap
SCP
s-->manshu manshu
String s= "manshu";
s.concat(" shivam");
System.out.println(s);//manshu
Heap SCP
s -> manshu
(no reference) manshu shivam
shivam
String s1 = new String ("manshu")
String s2 = s1.toUpperCase();
String s3= s1.toLowerCase();
System.out.println(s1 == s2);
System.out.println( s1 ==s3);
SCP
s1 --> manshu
(no reference)
manshu
s2 -->MANSHU
SCP
s1 --> manshu
s3-->
manshu
s2 -->MANSHU
String s2 = s1.toUpperCase();
String s4 = s2.toLowerCase();
;
System.out.println( s1==s4); //false why ?
solution
Heap
SCP
s1 --> manshu
(no reference)
manshu
s2 -->MANSHU
SCP
s1 --> manshu
manshu
s2 -->MANSHU
s4 --> manshu