영어로 읽는 코딩

15_[자바] 연산자 우선순위와 String +

Precedence

Operator precedence defines how an expression evaluates when several operators are present. Java has specific rules that determine the order of evaluation. The easiest one to remember is that multiplication and division happen before addition and subtraction. Programmers often forget the other precedence rules, so you should use parentheses to make the order of evaluation explicit. For example, look at statements (1) and (2):

 

//: operators/Precedence.java
public class Precedence {
    public static void main(String[] args) {
		int x = 1, y = 2, z = 3;
		int a = x + y - 2/2 + z; // (1)
		int b = x + (y - 2)/(2 + z); // (2)
		System.out.println("a = " + a + " b = " + b);
	}
} /* Output:
a = 5 b = 1
*///:~

 

These statements look roughly the same, but from the output you can see that they have very different meanings which depend on the use of parentheses.

 

Notice that the System.out.println( ) statement involves the ‘+’ operator. In this context, ‘+’ means “string concatenation” and, if necessary, “string conversion.” When the compiler sees a String followed by a ‘+’ followed by a non-String, it attempts to convert the non-String into a String. As you can see from the output, it successfully converts from int into String for a and b.

 

[Thinking in Java, 64]

댓글

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