자바에서의 연산자 이해 및 활용

1. 산술 연산자

두 개의 피연산자를 사용하여 계산을 수행합니다.

  • 기본 연산: +, -, *, /, %
  • 단항 연산: ++, --

증가/감소 연산자는 변수 앞 또는 뒤에 위치할 수 있습니다.


public class ArithmeticExample {
    public static void main(String[] args) {
        int x = 5;
        int y = 3;

        System.out.println(x + y); // 합계
        System.out.println(x - y); // 차이

        double z = 10.0;
        int w = 4;

        System.out.println(z / w); // 실수 나눗셈 결과

        int counter = 1;
        System.out.println(++counter); // 사전 증가 후 출력
        System.out.println(counter--); // 출력 후 사후 감소
    }
}

2. 대입 연산자

오른쪽 값을 왼쪽 변수에 저장합니다.

  • = (단순 대입)
  • +=, -=, *=, /=, %= (결과 대입)

public class AssignmentExample {
    public static void main(String[] args) {
        int total = 10;

        total += 5; // total = total + 5
        System.out.println(total);

        total %= 3; // total = total % 3
        System.out.println(total);
    }
}

3. 비교 연산자

두 값 사이의 관계를 평가하여 boolean 결과를 반환합니다.

  • >, <, >=, <=, ==, !=

public class ComparisonExample {
    public static void main(String[] args) {
        int first = 10;
        int second = 20;

        System.out.println(first == second); // false
        System.out.println(first > second);  // false
        System.out.println(first <= second); // true
    }
}

4. 논리 연산자

boolean 값을 조합하거나 반전시킵니다.

  • && (그리고)
  • || (또는)
  • ! (아님)

public class LogicExample {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;

        System.out.println(a && b); // false
        System.out.println(a || b); // true
        System.out.println(!a); // false
    }
}

5. 비트 연산자

정수와 문자 데이터를 이진 형태로 처리합니다.

  • ~ (비트 반전)
  • & (AND), | (OR), ^ (XOR)
  • << (좌측 시프트), >> (우측 시프트)

public class BitwiseExample {
    public static void main(String[] args) {
        int num = 8;

        System.out.println(num << 1); // 16
        System.out.println(num >> 1); // 4

        int mask = 1;
        System.out.println(mask & num); // 0
    }
}

6. 삼항 연산자

true/false에 따라 다른 값을 선택합니다.


public class TernaryExample {
    public static void main(String[] args) {
        int score = 95;

        String result = (score >= 90) ? "우수" : "보통";
        System.out.println(result); // 우수
    }
}

7. 자동 타입 변환

산술 연산 중 더 큰 범위의 데이터 타입으로 자동 형변환이 일어납니다.

  • byte/short/int/long → float/double
  • String과의 결합은 항상 문자열 연결으로 처리됩니다.

public class TypeConversionExample {
    public static void main(String[] args) {
        int small = 5;
        double big = 10.5;

        double result = small + big;
        System.out.println(result); // 15.5

        String message = "점수: " + small;
        System.out.println(message); // 점수: 5
    }
}

태그: java operators type_conversion

5월 31일 11:29에 게시됨