String str = new String("abc");
Creates two object on in the pool and other in heap
an it refers to the heap object
String str1 = "abc";
Creates single object tin the pool
Problem -1
String str = new String("abc");
String str1 = "abc";
String str2 ="abc";
String str3 = new String("abc").intern();
System.out.println(str==str1);
System.out.println(str.equals(str1));
System.out.println(str1==str2);
System.out.println(str1==str3);
Output-
false
true
true
true
we can use the String in Switch case after Java-7
Problem -2
String test = "i want to-test my function";
System.out.println(test.length());
System.out.println(test.charAt(5));
//System.out.println(test.charAt(100)); //Error out of index
System.out.println(test.substring(3, 9)); //9 is excluded
Output
25
t
ant to
Problem -3
StringBuilder sb = new StringBuilder("ada");
//System.out.println(s==sb); // Compiler Error incompatible type
System.out.println(s.equals(sb)); //false
System.out.println(sb.equals(s)); //false
Problem -4
ArrayList<String> al = new ArrayList<String>();
al.add("a");
al.add("b");
Collections.sort(al);
System.out.println(al);
ArrayList<StringBuilder> alb = new ArrayList<StringBuilder>();
alb.add(new StringBuilder("a") );
alb.add(new StringBuilder("b"));
//Collections.sort(alb); //compiler Error
System.out.println(alb);
StringBuilder and StringBuffer does not implements comparable
String
|
StringBuffer
|
StringBuilder
| |
Storage Area
|
Constant String Pool
|
Heap
|
Heap
|
Modifiable
|
No (immutable)
|
Yes( mutable )
|
Yes( mutable )
|
Thread Safe
|
Yes
Every immutable object in Java is thread safe.
|
Yes
All method synchronized.
|
No
|
Performance
|
Fast
|
Very slow
All method synchronized.
|
Fast
|
Comments
Post a Comment