11 논리 연산자
OR ( || )
||(or)는 좌우항 중에 하나라도 true라면 전체가 true가 되는 논리 연산자다. 다음 예를 보자. 결과는 1,2,3이 출력된다. 마지막 조건문의 or는 좌항과 우항이 모두 false이기 때문에 false가 된다.
package org.opentutorials.javatutorials.conditionaloperator; public class OrDemo { 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); } } }
다음 예제는 id 값으로 egoing, k8805, sorialgi 중의 하나를 사용하고 비밀번호는 111111을 입력하면 right 외의 경우에는 wrong를 출력하는 예다.
package org.opentutorials.javatutorials.conditionaloperator; public class LoginDemo4 { public static void main(String[] args) { String id = args[0]; String password = args[1]; if ((id.equals("egoing") || id.equals("k8805") || id.equals("sorialgi")) && password.equals("111111")) { System.out.println("right"); } else { System.out.println("wrong"); } } }
위의 예제에서는 or와 and를 혼합해서 사용하는 방법을 보여준다. id 값을 테스트하는 구간을 괄호()로 묶었다. 사용자가 id의 값으로 egoing 비밀번호를 111111을 입력했다면 연산의 순서는 아래와 같이 된다.
- (id=="egoing" or id=="k8805" or id=="sorialgi") : true가 된다.
- password=='111111' : true가 된다.
- true(1항) and true(2항) : true가 된다.
사칙 연산을 할 때 괄호부터 계산하는 것과 같은 원리다.