영어로 읽는 코딩

22_[자바] string +

String operator + and +=

There’s one special usage of an operator in Java: The + and += operators can be used to concatenate strings, as you’ve already seen. It seems a natural use of these operators even though it doesn’t fit with the traditional way that they are used.

This capability seemed like a good idea in C++, so operator overloading was added to C++ to allow the C++ programmer to add meanings to almost any operator. Unfortunately, operator overloading combined with some of the other restrictions in C++ turns out to be a fairly complicated feature for programmers to design into their classes. Although operator overloading would have been much simpler to implement in Java than it was in C++ (as has been demonstrated in the C# language, which does have straightforward operator overloading), this feature was still considered too complex, so Java programmers cannot implement their own overloaded operators like C++ and C# programmers can.

The use of the String operators has some interesting behavior. If an expression begins with a String, then all operands that follow must be Strings (remember that the compiler automatically turns a double-quoted sequence of characters into a String):

//: operators/StringOperators.java
import static net.mindview.util.Print.*;
public class StringOperators {
public static void main(String[] args) {
    int x = 0, y = 1, z = 2;
	String s = "x, y, z ";
	print(s + x + y + z);
	print(x + " " + s); // Converts x to a String
	80 Thinking in Java Bruce Eckel
	s += "(summed) = "; // Concatenation operator
	print(s + (x + y + z));
	print("" + x); // Shorthand for Integer.toString()
}
} /* Output:
x, y, z 012
0 x, y, z
x, y, z (summed) = 3
0
*///:~

 

Note that the output from the first print statement is ‘012’ instead of just ‘3’, which is what you’d get if it was summing the integers. This is because the Java compiler converts x, y, and z into their String representations and concatenates those strings, instead of adding them together first. The second print statement converts the leading variable into a String, so the string conversion does not depend on what comes first. Finally, you see the use of the += operator to append a string to s, and the use of parentheses to control the order of evaluation of the expression so that the ints are actually summed before they are displayed.

Notice the last example in main( ): you will sometimes see an empty String followed by a + and a primitive as a way to perform the conversion without calling the more cumbersome explicit method (Integer.toString( ), in this case).

 

[Thinking in Java 80]

 

댓글

댓글 본문
작성자
비밀번호
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기