[Java]연산자

Devlog·2024년 2월 14일

Java

목록 보기
5/41

연산자(operator): 연산의 종류를 결정짓는 기호
피연산자(operand): 연산식에서 연산되는 데이터(값)
- 연산자종류
산술 - (+, -, *, /, %, ···)
증감 - (++, --, ···)
논리 - (&&, ||, ···)
대입 - (=, +=,-=, ···)

1) 단항 연산자

: 피연산자가 단 하나뿐인 연산자
: 부호 연산자(+,-), 증감 연산자(++,--), 논리 부정 연산자(!)가 있음

1-1) 부호 연산자(+,-)

: 양수 및 음수를 표시함

public class SignOperatorExample {

	public static void main(String[] args) {
		
		int x = -100;
		int result1 = +x;
		int result2 = -x;
		System.out.println("result1= " + result1);
		System.out.println("result2= " + result2);
		
		byte b = 100;
		//byte result3 = -b; → byte타입 값을 부호 연산하면 int타입 값으로 바뀌므로 컴파일 에러 발생
		int result3 = -b;
		System.out.println("result3= " + result3);
	}

}

출력

result1= -100
result2= 100
result3= -100

1-2) 증감 연산자(++,--)

: 변수의 값을 1증가(++)시키거나 1감소(--)시키는 연산자
++피연산자 - 다른 연산을 수행하기 전에 피연산자의 값을 1 증가시킴
--피연산자 - 다른 연산을 수행하기 전에 피연산자의 값을 1 감소시킴
피연산자++ - 다른 연산을 수행한 후에 피연산자의 값을 1 증가시킴
피연산자-- - 다른 연산을 수행한 후에 피연산자의 값을 1 감소시킴

public class IncreaseDecreaseOperatorExample {

	public static void main(String[] args) {
		
		int x = 10;
		int y = 10;
		
		int z;
		
		System.out.println("---------------------");
		x++; //10 -> 11
		++x; //12
		System.out.println("x=" + x);
		
		System.out.println("---------------------");
		y--; //10 -> 9
		--y; //8
		System.out.println("y=" + y);
		
		System.out.println("---------------------");
		z = x++; //12 -> 13
		System.out.println("z="+z); //12
		System.out.println("x="+x); //13
		
		System.out.println("---------------------");
		z = ++x; //14 
		System.out.println("z="+z); //14
		System.out.println("x="+x); //14
		
		System.out.println("---------------------");
		z = ++x + y++; //23=(15+8)->9
		System.out.println("z="+z); //23
		System.out.println("x="+x); //15
		System.out.println("y="+y); //9
	}

}
---------------------
x=12
---------------------
y=8
---------------------
z=12
x=13
---------------------
z=14
x=14
---------------------
z=23
x=15
y=9

✓ ++i와 i=i+1의 연산속도 차이는 없다

1-3) 논리 부정 연산자(!)

: true → false로 false → true로 변경
: 조건문과 제어문에서 조건식의 값을 부정하도록 해서 실행 흐름을 제어할 때 주로 사용
: 토글기능(두 가지 상태를 번갈아가면 변경)을 구현할 때도 사용

public class DenyLogicOperatorExample {

	public static void main(String[] args) {
		
		boolean play = true;
		System.out.println(play);
		
		play = !play;
		System.out.println(play);
		
		play = !play;
		System.out.println(play);
	}

}
true
false
true

2) 이항 연산자

: 피연산자가 2개인 연산자
: 산술 연산자(+, -, *, /, %),
문자열 결합 연산자(+),
비교 연산자(<, <=, >, >=, ==, !=),
논리 연산자(&&, ||, &, |, ^, !),
대입 연산자(+=, -=, *=, /=, %=) 등이 있음

2-1) 산술 연산자(+,-,*,/,%)

//산술 연산자
public class ArithmeticOperatorExample {

	public static void main(String[] args) {
		
		int v1 = 5;
		int v2 = 2;
		
		int result1 = v1+v2;
		System.out.println("result1="+result1);
		
		int result2 = v1-v2;
		System.out.println("result2="+result2);
		
		int result3 = v1*v2;
		System.out.println("result3="+result3);
		
		int result4 = v1/v2;
		System.out.println("result4="+result4);
		
		int result5 = v1%v2;
		System.out.println("result5="+result5);
		
		double result6 = (double) v1/v2; //v1 or v2 둘중 하나를 double타입으로 강제 타입 변환해야함
		System.out.println("result6="+result6);

	}

}
result1=7
result2=3
result3=10
result4=2
result5=1
result6=2.5
//char타입의 산술 연산
public class CharOperationExample {

	public static void main(String[] args) {
		char c1 = 'A' + 1; //'A'는 65라는 유니코드를 가지므로 'A'+1=66이됨
		char c2 = 'A';
		//char c3 = c2 + 1; //변수 c2와 1을 더하면 c2는 int타입으로 변환되고 1과 연산이 되기 때문에 연산결과는 int타입이 됨
		char c3 = (char)(c2+1);
		System.out.println("c1="+c1);
		System.out.println("c2="+c2);
		System.out.println("c3="+c3);
	}

}
c1=B
c2=A
c3=B

2-2) 문자열 결합 연산자(+)

: 문자열을 서로 결합하는 연산자

public class StringConcatExample {

	public static void main(String[] args) {
		
		String str1 = "JDK" + 6.0;
		String str2 = str1 + " 특징";
		System.out.println(str2);
		
		String str3 = "JDK" + 3 + 3.0;
		String str4 = 3 + 3.0 + "JDK";
		System.out.println(str3);
		System.out.println(str4);
	}

}
JDK6.0 특징
JDK33.0
6.0JDK

2-3) 비교 연산자(<,<=,>,>=,==,!=)

: 피연산자의 대소 또는 동등을 비교해서 true/false를 산출함

//비교연산자1
public class CompareOperatorExample1 {

	public static void main(String[] args) {
		
		int num1 = 10;
		int num2 = 10;
		boolean result1 = (num1 == num2);
		boolean result2 = (num1 != num2);
		boolean result3 = (num1 <= num2);
		System.out.println("result1=" + result1);
		System.out.println("result2=" + result2);
		System.out.println("result3=" + result3);
		
		char char1 = 'A';
		char char2 = 'B';
		boolean result4 = (char1 < char2);
		System.out.println("result4=" + result4);
	}

}
result1=true
result2=false
result3=true
result4=true
public class CompareOperatorExample2 {

	public static void main(String[] args) {
		int v2 = 1;
		double v3 = 1.0;
		System.out.println(v2 == v3); //변수 v2가 double타입으로 변환돼서 비교됨
		
		double v4 = 0.1;
		float v5 = 0.1f;
		System.out.println(v4 == v5); //실수의 저장 방식인 부동 소수점 방식이 0.1을 정확히 표현할 수 없기 때문에 false
		System.out.println((float)v4 == v5); //피연산자를 모두 float타입으로 변환해서 비교하거나 정수 타입으로 변환해서 비교해야함
	}

}
true
false
true

✓ String 변수 비교할 때에는 equals()메소드를 사용함

2-4) 논리 연산자(&&, ||, &, |, ^, !)

&& vs &
- &&는 앞의 피연산자가 false라면 뒤의 피연산자를 평가하지 않고 바로 false라는 산출 결과를 냄
- &는 두 피연산자 모두를 평가해서 산출 결과를 냄
∴ &보다는 &&가 더 표율적으로 동작함

|| vs |
- ||는 앞의 피연산자가 true라면 뒤의 피연산자를 평가하지 않고 바로 true라는 산출 결과를 냄
- |는 두 피연산자 모두를 평가해서 산출 결과를 냄
∴ |보다는 ||가 더 효율적으로 동작함

public class LogicalOperatorExample {

	public static void main(String[] args) {
		
		int charCode = 'A';
		
		if((charCode >= 65) & (charCode <= 90)) {
			System.out.println("대문자군요");
		}
		
		if((charCode >= 97) && (charCode <= 122)) {
			System.out.println("소문자군요");
		}
		
		if(!(charCode < 48) && !(charCode > 57)) {
			System.out.println("0~9 숫자군요");
		}
		
		int value = 6;
		
		if((value%2==0) | (value%3==0)) {
			System.out.println("2 또는 3의 배수군요");
		}
		if((value%2==0) || (value%3==0)) {
			System.out.println("2 또는 3의 배수군요");
		}
	}

}
대문자군요
2 또는 3의 배수군요
2 또는 3의 배수군요

2-5) 대입 연산자(=, +=, -=, *=, /=, %=)

: 오른쪽 피연산자의 값을 왼쪽 피연산자인 변수에 저장함
단순 대입 연산자 → = (모든 연산자들 중 가장 낮은 연산 순위)
복합 대입 연산자
+=, -=, *=, /=, %=, &=, &=, |=, ^=

public class AssignmentOperatorExample {

	public static void main(String[] args) {
		
		int result = 0;
		result += 10;
		System.out.println("result=" + result);
		result -= 5;
		System.out.println("result=" + result);
		result *= 3;
		System.out.println("result=" + result);
		result /= 5;
		System.out.println("result=" + result);
		result %= 3;
		System.out.println("result=" + result);
	}

}
result=10
result=5
result=15
result=3
result=0

3) 삼항 연산자(= 조건연산식)
: 3개의 피연산자를 필요로 하느 ㄴ연산자
: ? 앞의 조건식에 따라 콜론(:) 앞뒤의 피연산자가 선택된다고 해서 조건 연산식이라고 부르기도 함

조건식(피연산자1) ? 값 또는 연산식(피연산자2) : 값 또는 연산식(피연산자3)
true가 나오면 피연산자2, false가 나오면 피연산자3

public class ConditionalOperationExample {

	public static void main(String[] args) {
		int score = 85;
		char grade = (score > 90) ? 'A' : ((score > 80) ? 'B' : 'C');
		System.out.println(score + "점은" + grade + "등급입니다.");
	}

}
85점은B등급입니다.

0개의 댓글