String, for constant strings.
StringBuffer, for strings that can change.
Why use String? Because they are constants, Strings are cheaper than StringBuffers and they can be shared.
StringBuffer dest = new StringBuffer(len); StringBuffer dest = new StringBuffer(); String dest = new String("Destination");
toString();
All classes inherit toString() from the Object class and many classes override this method to provide an implementation that is meaningful to that class. Implement it in your classes too!
valueOf()
Static member of String that can be used to convert variables of different types to Strings.
The Java compiler uses the String and StringBuffer classes behind the scenes to handle literal strings and concatenation.
"Hello World!"
You can use literal strings anywhere you would use a String object.
System.out.println("I add that you look lovely today."); int len = "Goodbye Cruel World".length(); String s = "Hola Mundo";
The above construct is equivalent to, but more efficient than, this one, which ends up creating two Strings instead of one:
String s = new String("Hola Mundo");
String cat = "cat"; System.out.println("con" + cat + "enation");
The above example compiles to:
String cat = "cat"; System.out.println(new StringBuffer().append("con").append(cat).append("enation"));
You can also use the + operator to append values to a String that are not themselves Strings:
System.out.println("Java's Number " + 1);
![]() | Caution |
---|---|
![]() Java Strings are First-class Objects, unlike C or C++ strings which are simply null-terminated arrays of 8-bit characters. |
Copyright © 1998-2009 Dilvan Moreira