728x90
연산자
//연산자 : 연산을 수행하는 기호
//피연산자 : 연산자의 연산 수행 대상
//모든 연산자는 연산결과를 반환 ↔ 연산 결과를 반환하지 않으면 연산자가 아니다
//연산자의 종류
//산술 연산자 + - * / %
//비교 연산자 > < >= <= == !=
//논리 연산자 && || !
//대입 연산자 =
//기타 (type) ? : instanceof 형변환 연산자, 삼항연산자, instanceof연산자
연산자의 우선순위
//1. 단항 연산자 ++ -- + - ~ ! (type)
//2. 산술 연산자 * / %, + -
//3. 비교 연산자 < > <= >= instanceof, == !=
//4. 논리 연산자 &, ^, |, &&, ||, ?
//5. 삼항 연산자 ?:
//6. 대입 연산자
//1 ~ 6 순서임
//※단항 연산자, 대입연산자는 결합 규칙이 ←임
//ex) x = y = 1
// y = 1이 먼저 대입되고, x = 1이 대입
증감연산자
//증가연산자(++) 피연산자의 값을 1 증가
//감소연산자(--) 피연산자의 값을 1 감소
//전위형 값이 참조되기 전에 증가 j = ++i;
//j = ++i; => ++i; j=i; //증가 후에 참조하여 대입
//후위형 값이 참조된 후에 증가 j = i++;
//j = i++; => j=i; i++; //참조하여 대입 후 증가
//단, 증감 연산자가 독립적으로 사용된 경우, 전위형과 후위형의 차이가 없음
int i = 3, j = 0;
j = i++;
System.out.println("후위형 증가연산자, i = " + i + " j = " + j);
i = 3; j = 0;
j = ++i;
System.out.println("전위형 증가연산자, i = " + i + " j = " + j);
//부호 연산자
int num = -10;
num = +num;
System.out.println(num);
num = -10;
num = -num;
System.out.println(num);
형변환
//형변환? 변수 또는 상수의 타입을 다른 타입으로 변환
//(타입)피연산자
double d = 85.4;
int integer = (int)d;
double cd = integer;
System.out.println(d);
System.out.println(cd);
//자동형변환
//컴파일러가 자동으로 형변환
float f = 1234;
//== float f = (float)1234;
//int i = 3.14f;
//큰 -> 작은 => 값 손실 발생
int i = (int)3.14f;
//기존 값을 최대한 보존할 수 있는 타입으로 자동 형변환됨
byte b1 = 100;
byte b2 = (byte)100; //리터럴
int i1 = 100;
//byte b3 = i; i가 변수이고 i의 값을 모르기 때문에 컴파일러가 알 수 없다-> 에러
byte b3 = (byte)i; //수동형변환
//byte b4 = 1000; byte타입의 범위를 벗어난 값 대입임으로 에러
byte b4 = (byte)1000; //값 손실이 발생하여 b4에는 -24의 값이 저장
산술 변환
//같은 형끼리만 계산이 가능함
//산술 변환 : 연산 전 피연산자의 타입을 일치 시키는 것
//두 가지 규칙은 반드시 암기할 것
//규칙 1. 두 피연산자의 타입을 같게 일치시킴(보다 큰 타입으로 일치, 값 손실을 최소화하기 위해서)
//long + int => long + long ==> long
//float + int => float + float ==> float
//double + float => double + double ==> double
//규칙 2. 피연산자의 타입이 int보다 작은 타입이면 int로 변환
//byte + short => int + int => int
//char + short => int + int => int
char a = '2', b = '0';
System.out.println(a-b); //문자에서 숫자로 형변환할 때 -'0'을 하는 이유
System.out.println();
int x = 1000000;
int y = 2000000;
long z = x * y; //오버플로우가 발생함
long z1 = (long)x * y; //오버플로우가 발생하지 않으려면 x나 y를 형 변환해줘야함
System.out.println(z);
System.out.println(z1);
반올림
//반올림 Math.rount()
//실수를 소수 첫째자리에서 반올림한 정수를 반환
long result1 = Math.round(3.14);
System.out.println(result1);
long result2 = Math.round(3.54);
System.out.println(result2); //반올림 된 결과
System.out.println();
double pi = 3.141592;
//double shortPi = Math.round(pi*1000)/1000.0;
//System.out.println(shortPi);
//계산과정
System.out.println(pi);
System.out.println(pi*1000);
System.out.println(Math.round(pi*1000));
System.out.println(Math.round(pi*1000)/1000); //int/int => int
System.out.println(Math.round(pi*1000)/1000.0); //int/double => double
System.out.println((double)Math.round(pi*1000)/1000);
//10^n을 곱한 후 10^n.0으로 나누면 원하는 자리에서 반올림가능
//결과를 3.141로 나타내려면?
System.out.println(pi*1000);
System.out.println((int)(pi*1000)); //값 손실을 내서
System.out.println((int)(pi*1000)/1000.0);
System.out.println();
//나머지 연산자 %
//나누는 피연산자는 0이 아닌 정수만 허용되며, 부호는 무시됨
System.out.println(3%2);
System.out.println(3%-2);
System.out.println(-3%2);
System.out.println(-3%-2);
비교연산자
//비교연산자 >, <, >=, <=, ==, !=
//=>, =<, =! 이렇게 사용하는 것만 조심
//문자열의 비교
//문자열 비교에는 == 대신 equals() 메소드를 사용해야함
//==도 결과가 나오긴 하나 올바른 결과가 나오지 않을 때가 있음
String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2); //true
System.out.println(str1.equals(str2)); //true
String string1 = new String("abc");
String string2 = new String("abc");
System.out.println(string1==string2); //false
System.out.println(string1.equals(string2)); //true
논리연산자
//조건식을 연결할 때 사용하는 연산자
//ex1) x는 10보다 크고 20보다 작다
// x > 10 && x <20 == 10 < x && x <20
//단, 10 < x < 20 이런식의 표현은 허용하지 않음
//ex2) i는 2의 배수 또는 3의 배수
//i%2==0 || i%3 ==0
//ex3) i는 2의배수 또는 3의 배수이지만 6의배수는 아니다.
//(i%2==0 || i%3==0) && i%6 !=0
//※&&가 ||보다 우선순위가 높다
//ex4) 문자 ch는 숫자('0'~'9')이다
//'0' <= ch && ch <= '9'
//ex5) 문자 ch는 대문자 또는 소문자
//('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')
//논리 부정 연산자 !
boolean b = true;
System.out.println(!!b);
System.out.println(!b);
//ex1) 문자 ch가 소문자가 아니다
// ch < 'a' || ch > 'z'
// == !('a' <= ch && ch <= 'z')
나머지 연산자
//조건 연산자(3항 연산자) ? :
//조건식의 결과에 따라 연산 결과가 다름
// 조건식 ? 식1 : 식 2
// 조건식이 참이면 식1, 거짓이면 식2
//(x > y)? x : y;
//=> if(x > y){result x} else{result y};
//대입 연산자
//오른쪽 피연자를 왼쪽 피연산자에 저장후 저장된 값을 반환
//모든 연산자는 결과값을 반환
int x = 3;
System.out.println(x);
//x = 3
//x lvalue(저장공간, 변수, 배열), 3 rvalue(값)
//복합 대입 연산자
//대입 연산자와 다른 연자를 하나로 축약
//i += j => i = i + j
//...
//주의할 점
//i *= x + j; => i = i * (x + j);
728x90
'organize > 자바' 카테고리의 다른 글
자바 처음부터 다시 시작하기 5 (0) | 2024.04.15 |
---|---|
자바 처음부터 다시 시작하기 4 (0) | 2024.04.14 |
자바 처음부터 다시 시작하기 2 (0) | 2024.04.10 |
자바 처음부터 다시 시작하기 1 (0) | 2024.04.10 |
Java Chapter 2 타입과 연산자 (0) | 2023.12.03 |