Strings in Java
To create string there are two ways
1. String s3= new String("hello");
String s4= new String ("hello");
2. String s1= "hello";
String s2="hello";
which method is better ? second method


1. String s3= new String("hello");
String s4= new String ("hello");
2. String s1= "hello";
String s2="hello";
which method is better ? second method
Because the content is same s1 and s2 refer to the same object where as s3 and s4 do not refer to the same object. The 'new' key word creates new objects for s3 and s4 which is expensive.


StringBuffer and StringBuilder
StringBuffer
is used to store character strings that will be changed (String
objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence. it is synchronized .
StringBuilder
was added in Java 5. It is identical in all respects to StringBuffer
except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.
Comments
Post a Comment