Java Reference
In-Depth Information
String Concatenation Operator (+)
The + operator is overloaded. An operator is said to be overloaded if it is used to perform more than one function. So
far, you have seen its use as an arithmetic addition operator to add two numbers. It can also be used to concatenate
two strings. Two strings, such as "abc" and "xyz" , can be concatenated using the + operator as "abc" + "xyz" to
produce new string "abcxyz" . The following is another example of a string concatenation:
String str1 = "Hello,";
String str2 = " Alekhya";
String str3 = str1 + str2; // Assigns "Hello, Alekhya" to str3
The string concatenation operator is also used to concatenate a primitive and a reference data type value to a
string. I will discuss only concatenation of string and primitive data types in this section. When either operand of the
+ operator is a string, it performs string concatenation. When both operands of + are numeric, it performs number
addition. Consider the following snippet of code:
int num = 26;
String str1 = "Alphabets";
String str2 = num + str1; // Assigns "26Alphabets" to str2
When the expression num + str1 is executed, the + operator acts as a string concatenation operator because
its right-hand operand, str1 , is a String . Before num and str1 are concatenated, num is replaced by its string
representation, which is "26" . Now, the expression becomes "26" + str1 , which results in "26Alphabets" .
Table 4-2 lists the string representation of the values of the primitive data types.
Table 4-2. String Representations of the Values of Primitive Data Types
Data Type
Value
String Representation
int, short,
byte, long
1678
"1678"
0
"0"
char
'A'
"A"
'\u0041'
(Unicode escape sequence)
"A"
boolean
true
"true"
false
"false"
float
2.5
"2.5"
0.0F
"0.0"
-0.0F
"-0.0"
Float.POSITIVE_INFINITY
"Infinity"
Float.NEGATIVE_INFINITY
"-Infinity"
Float.NaN
"NaN"
( continued )
 
Search WWH ::




Custom Search