Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The Java compiler uses theString
andStringBuffer
classes behind the scenes to handle literal strings and concatenation.
In Java, you specify literal strings between double quotes:You can use literal strings anywhere you would use a"Hello World!"String
object. For example,System.out.println
accepts aString
argument, so you could use a literal string in place of aString
there.You can also useSystem.out.println("Might I add that you look lovely today.");String
methods directly from a literal string.Because the compiler automatically creates a newint len = "Goodbye Cruel World".length();String
object for every literal string it encounters, you can use a literal string to initialize aString
.The above construct is equivalent to, but more efficient than, this one, which ends up creating twoString s = "Hola Mundo";String
s instead of one:The compiler creates the first string when it encounters the literal string "Hola Mundo!", and the second one when it encountersString s = new String("Hola Mundo");new String
.
In Java, you can use+
to concatenateString
s together:This is a little deceptive because, as you know,String cat = "cat"; System.out.println("con" + cat + "enation");String
s can't be changed. However, behind the scenes the compiler usesStringBuffer
s to implement concatenation. The above example compiles to:You can also use theString cat = "cat"; System.out.println(new StringBuffer().append("con"). append(cat).append("enation").toString());+
operator to append values to aString
that are not themselvesString
s:The compiler converts the non-System.out.println("Java's Number " + 1);String
value (the integer1
in the example) to aString
object before performing the concatenation operation.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |