자바 ocjap 문제 해설 - 연산자 우선순위
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int x=1;
int y=0;
if(x++ > ++y){
System.out.print("Hello ");
}else{
System.out.print("Welcome ");
}
System.out.print("Log " + x + ":" + y);
}
}
What is the result?
A. Hello Log 1:0
B. Hello Log 2:1
C. Welcome Log 2:1
D. Welcome Log 1:0
정답: C
해설
x++ 는 나중에 더해지고
++y는 먼저 더해진다.
아래 출력을 보면 명확해진다.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int x=1;
int y=0;
System.out.print("x="+x++);
System.out.print("y="+ ++y);
if(x++ > ++y){
System.out.print("Hello ");
}else{
System.out.print("Welcome ");
}
System.out.print("Log " + x + ":" + y);
}
}
결과
x=1y=1Welcome Log 3:2
x는 나중에 더해져서 1이고 y는 먼저 더해져서 1이다.
그래서 if 절에서 if(1>1) 이기 때문에 false 이고 else 문으로 빠진다.
https://ideone.com/
여기서 자바 웹 컴파일 및 실행이 가능하다.