반응형
- 연산자 종류
public class OperationPriority {
public static void main(String[] args) {
System.out.println("12를 5로 나누었을 때 나머지 : " + 12 % 3);
// 산술연산자 연산방향 : 왼쪽에서 오른쪽
int num = 9 * 4 / 3 % 5;
System.out.println("num=" + num);
// 대입연산자의 연산 방향 : 오른쪽에서 왼쪽
int a, b, c;
a=b=c=5;
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("c=" + c);
}
}
값
12를 5로 나누었을 때 나머지 : 0
num=2
a=5
b=5
c=5
- 단항 연산자
- 증감 연산자
public class IncDecOperationExample2 {
public static void main(String[] args) {
int x = 10;
int y = 10;
int result1 = ++x + 5; // 전위증가 16
int result2 = y++ + 5; // 후위증가 15
System.out.println(result1);
System.out.println(result2);
}
}
값
16
15
- 논리 부정 연산자: !
- boolean 타입에만 사용
- 제어문의 조건식에 사용된다
- 두 가지 변경상태(true/false)를 나타내는 토글 기능 구현
public class DenyLogicOperExam {
public static void main(String[] args) {
int value = 10;
if(!(value > 20)) {
System.out.println("value값은 20보다 크지 않다.");
}
// !(10 > 20)
// !(false)
// true
System.out.println(20 > 10); // 20은 10보다 크다. true
System.out.println(20>=10); // 20은 10보다 크거나 같다. true
System.out.println(20 < 10); // 20은 10보다 작다. false
System.out.println(20 <= 10); // 20은 10보다 작거나 같다. false
System.out.println(20 == 10); // 20은 10과 같다. false
System.out.println(20 != 10); // 20은 10과 다르다. true
}
- 이항 연산자
⁙ 간단한 예외처리
public class ExceptionHandlingExam {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
try {
int result = num1 / num2;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다");
System.out.println(e.getMessage());
}
}
}
문제가 생길수 있는 코드를 try 블럭에 넣고 catch문에 예외 코드를 넣는다.
반응형
댓글