&&는 좌항과 우항의 값이 모두 참(true)일 때 참이 된다. And라고 읽는다. 다음 예제를 보자. 결과는 1이다. and의 좌우항이 모두 true인 것은 첫 번째 조건문 밖에 없기 때문이다.
package org.opentutorials.javatutorials.conditionaloperator;
public class AndDemo {
public static void main(String[] args) {
if (true && true) {
System.out.println(1);
}
if (true && false) {
System.out.println(2);
}
if (false && true) {
System.out.println(3);
}
if (false && false) {
System.out.println(4);
}
}
}
논리 연산자를 이용한 사례를 살펴보자. 다음 예제는 논리 연산자를 이용해서 이전 예제를 개선한 것이다.
package org.opentutorials.javatutorials.conditionaloperator;
public class LoginDemo3 {
public static void main(String[] args) {
String id = args[0];
String password = args[1];
if (id.equals("egoing") && password.equals("111111")) {
System.out.println("right");
} else {
System.out.println("wrong");
}
}
}
중첩된 if 문을 하나로 줄였다. 덕분에 코드의 복잡성도 낮아졌다. 위의 코드에서 &&는 아래와 같은 의미가 된다.
"id의 값이 egoing이고 password의 값이 111111이면 참이다"
즉 and 연산자의 좌항과 우항이 모두 참일 때 전체가 참이 되는 것이다.