-
210929 / 대입 연산자, 부호 연산자, 산술 연산자, 증가&감소 연산자, 관계 연산자, 논리 연산자, 조건 연산자개발자 수업/Java 2021. 9. 29. 23:55
1. 연산자는 무엇인가
1) 연산자 (Operator) : 항을 이용하여 연산하는 기호 (+, -, *, /)
2) 피연산자 (Operand) = 항 : 연산자의 작업 대상(변수, 상수, 리터럴, 수식)
2. 대입 연산자 (assignment operator)
1) 변수에 다른 변수나 값을 대입하는 연산자
2) 이항연산자 중 우선 순위가 가장 낮은 연산자
3) 왼쪽 변수 = 오른쪽 변수(또는 값, 식)
3. 부호 연산자
1) 단항 연산자
2) 변수의 부호를 유지하거나(+), 바꿈(-)
4. 산술 연산자
1) 사칙 연산자
+
-
*
/ 앞에 있는 항에서 뒤에 있는 항을 나누어 몫을 구함
% 앞에 있는 항에서 뒤에 있는 항을 나누어 나머지를 구함package kr.co.ezenac.operator; public class OperatorTest { public static void main(String[] args) { int v1 = 5; int v2 = 2; int result = v1 + v2; System.out.println("더하기 결과 : " + result); result = v1 - v2; System.out.println("빼기 결과 : " + result); result = v1 * v2; System.out.println("곱하기 결과 : " + result); result = v1 / v2; System.out.println("나누기 결과 : " + result); result = v1 % v2; System.out.println("나머지 결과 : " + result); try { result = v1 / 0; // 산술 연산 예외가 발생 } catch(Exception e) { System.out.println("예외 발생 : " + e.toString()); } } }
2) 복합 대입 연산자
대입 연산자와 다른 연산자가 함께 쓰임
+=
-=
*=
/=
%=package kr.co.ezenac.operator; public class AssignOperTest { public static void main(String[] args) { int result = 0; result += 10; // result = result + 10; System.out.println("result : " + result); result -= 5; // result = result - 5; System.out.println("result : " + result); result *= 5; // result = result * 5; System.out.println("result : " + result); result /= 5; // result = result / 5; System.out.println("result : " + result); result %= 5; // result = result % 5; System.out.println("result : " + result); } }
5. 증가, 감소 연산자
1) 단항 연산자
2) 변수의 값을 1 더하거나 1 뺄 때 사용
3) 연산자가 항의 앞에 있는가, 뒤에 있는가에 따라 연산 시점과 결과가 달라짐
4) 문장(statement)의 끝(;)을 기준으로 연산 시점을 생각해야 함
5) ++ : 항의 값에 1을 더함 ex) val = ++num; -> 먼저 num값이 1 증가 후 val 변수에 대입
val = num++; -> val 변수에 기존 num 값을 대입한 후 num값 1 증가package kr.co.ezenac.operator; public class InCreDreTest { public static void main(String[] args) { int x = 10; int y = 10; System.out.println("-----------------------------"); System.out.println("x = " + (x++)); // 후위증가연산자 10 System.out.println("x = " + x); // 11 System.out.println("y = " + (++y)); // 전위증가연산자 11 System.out.println("y = " + y); // 11 System.out.println("----------------------------"); } }
-- : 항의 값에 1을 뺌 ex) val = --num; -> 먼저 num값이 1 감소 후 val 변수에 대입
val = num--; -> val 변수에 기존 num 값을 대입한 후 num값 1 감소
6. 관계 연산자
1) 이항 연산자 (비교 연산자라고도 함)
2) 연산의 결과가 true(참), false(거짓)으로 반환 됨
3) 조건문, 반복문의 조건식으로 많이 사용 됨
4) >
<
>=
<=
==package kr.co.ezenac.operator; // ==, != public class StringEqualsTest { public static void main(String[] args) { /* * 리터럴인 경우는 같은 값이 있는지 메모리(heap) 공간 먼저 체크하고나서, * 같은 값이 있다면 같은 주소를 공유하게 되고 * 없다면 새로운 곳에 인스턴스를 생성해 줌 */ String str1 = "서울특별시"; // String str2 = "자바"; String str2 = "서울특별시"; /* * 참조형 타입에서 ==은 '주소 비교'를 하고 있음 * 같은 리터럴의 경우는 같은 번지를 공유함 */ boolean result = (str1 == str2); System.out.println("str1 == str2 : " + result); // true // new 연산자 오면 무조건 새로운 인스턴스 생성 String str3 = new String("서울특별시"); result = (str1 == str3); System.out.println("str1 == str3 : " + result); // false /* * String 클래스의 equals()는 주소와 상관없이 '값'이 같다면 무조건 true 리턴함 */ result = str1.equals(str2); System.out.println("str1.equals(str2) : " + result); // true result = str1.equals(str3); System.out.println("str1.equals(str3) : " + result); // true } }
!=
7. 논리 연산자
1) 관계 연산자와 혼합하여 많이 사용 됨
2) 연산의 결과가 true(참), false(거짓)으로 반환 됨
3) && (논리곱) : 두 항이 모두 참인 경우에만 결과 값이 참, 그 외는 거짓
|| (논리합) : 두 항 중 하나의 항만 참이면 결과 값은 참, 두 항이 모두 거짓인 경우에만 결과 값이 거짓package kr.co.ezenac.operator; public class LogicalOperTest { public static void main(String[] args) { boolean result = false; int i = 10; result = (i > 5); System.out.println("(i > 5) : " + result); result = (i >= 9) && (i < -8); System.out.println("(i >=9) && (i < -8) : " + result); result = (i >= 9) || (i < -8); System.out.println("(i >= 9) || (i < -8) : " + result); char ch = 'b'; //ch 변수값이 알파벳 소문자인지 확인하는 식 result = (ch >= 'a') && (ch <= 'z'); System.out.println("(ch >= 'a') && (ch <= 'z') : " + result); //ch에 저장되어진 값이 알파벳인지 확인하는 조건식 result = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); System.out.println("(ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') : " + result); } }
! (부정) : 단항 연산자임
참인 경우는 거짓으로, 거짓인 경우는 참으로package kr.co.ezenac.operator; /* * ! 논리부정연산자 == not 연산자 -> 반대값을 취하는 연산자 */ public class DenyTest { public static void main(String[] args) { boolean power = false; System.out.println("power의 값 : " + power); power = !power; System.out.println("power의 값 : " + power); power = !power; System.out.println("power의 값 : " + power); if(!power) { System.out.println("if문 실행됨!"); } if(power) { System.out.println("if문 실행됨"); } } }
4) short circuit evaluation (단락 회로 평가)
- 논리곱(&&)은 두 항의 결과가 모두 true일 때만 결과가 true => 앞의 항의 결과가 false이면 뒤 항의 결과를 평가하지 않음
- 논리합(||)은 두 항의 결과가 모두 false일 때만 결과가 false => 앞의 항의 결과가 true이면 뒤 항의 결과를 평가하지 않음
8. 조건 연산자
1) 삼항 연산자
2) 조건식 ? 결과1 : 결과2 -> 조건식이 참이면 결과1, 거짓이면 결과2가 선택됨
3) 조건식의 결과의 경우에 따라 다른 결과가 수행됨
4) if(조건문)을 간단히 표현할 때 사용할 수 있음package kr.co.ezenac.operator; import java.util.Scanner; public class ThreeOperTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("점수를 입력하세요 : "); int score = scan.nextInt(); // (조건식) ? 1 : 2 char grade = (score >= 90) ? 'A' : 'B'; System.out.println("당신의 등급은 : " + grade + " 입니다."); // 삼항 연산자 중첩 grade = (score >= 90) ? 'A' : ((score >= 80) ? 'B' : 'C'); System.out.println("당신의 등급은 : " + grade + " 입니다."); scan.close(); } }
9. 이항 연산자의 특징
1) 연산을 실행하기 전에 피연산자의 타입을 일치시키는 작업을 함
- 디폴트 타입인 int 보다 바이트 수가 작은 타입은 int로 변환시킴
- byte, char, short -> int
예) byte + short -> int + int -> int
char + int -> int + int -> int
- 정수가 실수와 연산을 하게 되면, 표현 범위가 넓은 타입으로 형변환 됨
예) int + float -> float + float -> float
double + float -> double + double -> doublepackage kr.co.ezenac.operator; public class DefaultTypeTest { public static void main(String[] args) { byte b1 = 127; byte b2 = 1; //byte b3 = b1 + b2; // byte + byte => int + int => int int i1 = b1 + b2; // 해결방법 1 : int형으로 받아주면 됨 (자동 캐스팅) byte b3 = (byte)(b1 + b2); // 해결방법 2 : 강제 캐스팅 System.out.println("i1 = " + i1 + ", b3 = " + b3); // i1 = 128, b3 = -128 // ------------------------------------------------------------------- char ch = 'A'; // A는 아스키코드 값으로 65 int i2 = ch + b3; // 65 + (-128) System.out.println("i2 = " + i2 ); // i2 = -63 // ------------------------------------------------------------------- float f1 = 15.5F; //int i3 = b1 + f1; // float + float => float float f2 = b1 + f1; System.out.println("f2 = " + f2); // f2 = 142.5 // ------------------------------------------------------------------- double d1 = 10.5; //float f3 = f1 + d1; // float + double => double double d2 = f1 + d1; System.out.println("d2 = " + d2); // d2 = 26.0 } }
10. 비트 연산자
1) &, |, ^
2) 피연산자를 비트단위로 연산함
3) AND (&) 연산자 : 피연산자 중 둘 다 1이면 1임
OR (|) 연산자 : 피연산자 중 어느 한 쪽이 1이면 1임
XOR (^) 연산자 : 피연산자가 서로 다를 때 1임
11. 쉬프트 연산자 (<<, >>)'개발자 수업 > Java' 카테고리의 다른 글
6. Review / 7.객체지향프로그램 (0) 2021.10.04 5. 반복문 (while문, do~while문, for문) (0) 2021.10.01 210930 / if문, if else문, if else if문, switch case문, Math.random() (0) 2021.10.01 210929 / 진수, 변수, 부동 소수점 방식, 문자형, 논리형, 상수, 리터럴, 형변환 (0) 2021.09.29 210928 / 다운로드, 프로그래밍, 자바, 변수 (0) 2021.09.28