Strings are value objects. Value objects should always be immutable. If youwant a different value (different String), you need a different object.
String is Immutable String is the most used immutable class in Java. If new Java developers had to deal with a mutable String they may get very frustrated and overwhelmed by the complexity of the object model and give up on Java not long after starting.
String s = "nothing special";
s.toUppercase();
s.toUppercase();
On the other hand, you could write it like this:
String s = "nothing special";
s = s.toUppercase();
s = s.toUppercase();
SAFETY
If step A of a process receives a String and checks it, youdon't want some programmer to modify it before it reaches step B where it's assumed to have been OKed by A.
If they were mutable, imagine doing
getClass().getName().someModifyingOperation();
Good luck finding that class again, Mr. Classloader
Let me first tell you what is StringBuilder. StringBuilder is a class analogous to StringBuffer added in JDK 1.5. This class is designed to use in place where StringBuffer is used by single thread(like in most of the cases). According to documentation, StringBuilder should work faster than StringBuffer. So " thread unsafe, fast".I was reading one of the posts of orkut Java community asking "what is this capacity in StringBuffer and even we can add two strings from String class why to go for StringBuffer". Valid question !
GC need to work little more in case of String, but thats fair. As a java wellwisher let me try to do some publicity of Java API :D. And here it goes:No don't use String class for concatenation operation, always use StringBuffer/StringBuilder and let me tell you why ?
This is a simple Java code for string addition in String and StringBuffer:
class StringTest {
public static void main(String[] args)
{
String s = "just a string";
s = s + "add me too";
System.out.println(s);
/*
StringBuffer s = new StringBuffer("just a string") ;
//StringBuilder s = new StringBuilder("just a string");
s = s.append("add me too");System.out.println(s);
*/
}
}
now have a look on the bytecode of this program
>> javac StringTest.java
>> javap -c StringTest
Just see line no. 11. Interesting, the plus sign we used for addition is not as innocent as it looks. String itself use StringBuffer(StringBuilder) to add two strings and hence taking much more time than normal append operation done by StringBuffer.
Let me give you more evidence, run verbose option and check the time
>> javac -verbose StringTest.java
and check the other one, that is, with StringBuffer one.You can clearly figure out the time difference and make a try with StringBuilder, time should reduce furthermore.
No comments:
Post a Comment