- Home
- Objectives

- XyzWs Study Guides
- Study Guides
- Study Notes
- Resources

- Mock Exams
SCJP Study Guide:
Fundamentals
Printer-friendly version |
Mail this to a friend
String Concatenation
The binary + operator performs string concatenation when one or both operands are of type String. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression ) that is the concatenation of the two operand strings.
If an operand of string concatenation is null, an empty string is substituted that is the string "null"(four ASCII characters n, u, l, l).
Otherwise, any non-string argument is converted to its string representation by invoking the toString() method of the referenced object with no arguments.
If toString() returns null, an empty string is substituted.
The result of the string concatenation operator is a string that consists of the characters of the left operand followed by the characters of the right operand. The string concatenation operator never returns a null value.
For example:
class Program {
public static void main(String[] args) {
String s1 = "Hello, ";
String s2 = "XyzWS.com";
String s3 = null;
System.out.println(s1 + s2); //Output "Hello, XyzWS.com"
System.out.println(s1 + s3); //Output "Hello, null"
}
}
A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:
- If T is boolean, then use new Boolean(x).
- If T is char, then use new Character(x).
- If T is byte, short, or int, then use new Integer(x).
- If T is long, then use new Long(x).
- If T is float, then use new Float(x).
- If T is double, then use new Double(x).
This reference value is then converted to type String by string conversion.