자바(Java)에서 연산자는 프로그래밍에서 데이터를 처리하고 조작하는 핵심적인 도구 중 하나이다. 자바에서 사용되는 다양한 연산자에 대해 알아보자.
🔍 산술 연산자(Arithmetic Operators)
덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/)
int a = 5;
int b = 2;
int sum = a + b; // 덧셈
int difference = a - b; // 뺄셈
int product = a * b; // 곱셈
int quotient = a / b; // 나눗셈
int remainder = a % b; // a를 b로 나눈 나머지
🔍 대입 연산자(Assignment Operators)
int x = 10;
int y = 5;
x += y; // x = x + y;
x -= y; // x = x - y;
x *= y; // x = x * y;
x /= y; // x = x / y;
x %= y; // x = x % y;
🔍 증감 연산자 (Increment and Decrement Operators)
int i = 5;
i++; // 후위 증가: i = i + 1;
++i; // 전위 증가: i = i + 1;
int j = 10;
j--; // 후위 감소: j = j - 1;
--j; // 전위 감소: j = j - 1;
🔍 비교 연산자(Comparison Operators)
int p = 7;
int q = 7;
boolean isEqual = (p == q); // 등호: true if p equals q
boolean isNotEqual = (p != q); // 부등호: true if p is not equal to q
boolean isGreaterThan = (p > q); // 크다: true if p is greater than q
boolean isLessThan = (p < q); // 작다: true if p is less than q
boolean isGreaterOrEqual = (p >= q); // 크거나 같다: true if p is greater than or equal to q
boolean isLessOrEqual = (p <= q); // 작거나 같다: true if p is less than or equal to q
🔍 논리 연산자(Logical Operators)
boolean a = true;
boolean b = false;
boolean andResult = (a && b); // 논리 AND: true if both a and b are true
boolean orResult = (a || b); // 논리 OR: true if either a or b is true
boolean notResult = !a; // 논리 NOT: true if a is false
🔍 비트 연산자(Bitwise Operators)
int m = 5; // 이진수 표현: 0101
int n = 3; // 이진수 표현: 0011
int andResult = m & n; // 비트 AND: 0001 (1)
int orResult = m | n; // 비트 OR: 0111 (7)
int xorResult = m ^ n; // 비트 XOR: 0110 (6)
int complementResult = ~m; // 비트 NOT: 11111010111111111111111111111010 (-6)
int leftShiftResult = m << 1; // 비트 왼쪽 시프트: 1010 (10)
int rightShiftResult = m >> 1; // 비트 오른쪽 시프트: 0010 (2)
🔍 조건(삼항) 연산자(Conditional Operator)
int p = 10;
int q = 5;
int max = (p > q) ? p : q; // 만일 p가 q보다 크면 max에는 p가 들어가고, 그렇지 않으면 q가 들어간다.
💡 결론
자바의 다양한 연산자를 이용하여 효율적이고 다양한 연산을 수행할 수 있다. 이러한 연산자들은 자바 프로그래밍에서 중요한 역할을 하며, 적재적소에 활용하여 보다 효과적인 코드를 작성할 수 있다.
'JAVA > Theory' 카테고리의 다른 글
| 자바(Java)의 접근 제어자 (1) | 2023.12.17 |
|---|---|
| 배열 리스트(Array List) (0) | 2023.12.17 |
| 자바(Java)의 변수와 자료형 (0) | 2023.12.14 |
| [디자인패턴] MVC (0) | 2023.12.12 |
| 자바(Java)의 예외 처리(Exception Handling) (0) | 2023.12.10 |
댓글