자바가 제공하는 다양한 연산자를 학습하세요.
boolean
을 제외한 기본형에서 사용 가능int
보다 작은 타입이면 int
로 변환int
는 소수점 이하를 버리니 결과값 변화에 주의+
더하기-
빼기*
곱하기/
나누기 몫ArithmeticException
에러Infinity
%
나누기 나머지NaN
산술 연산자 이용 반올림
public static void main(String[] args) {
double pi = 3.141592;
double shortPi1 = (int) (pi * 100 + 0.5) / 100.0;
double shortPi2 = Math.round(pi * 100) / 100.0;
System.out.println(shortPi1); //3.14
System.out.println(shortPi2); //3.14
}
비트 연산자 | 결과 |
---|---|
& | AND. 두 비트가 모두 1일 때만 결과 값 1 |
| | OR. 두 비트 중 하나만 1이어도 결과 값 1 |
^ | XOR. 두 비트가 같은 값이면 결과 값 1 |
~ | 비트 반전 |
x << n | x의 각 비트가 왼쪽으로 n비트 이동. 빈자리는 0. (기존 값에 2n만큼 곱하는 것) |
x >> n | x의 각 비트가 오른쪽으로 n비트 이동. 빈자리는 부호비트 유지 (기존 값에 2n만큼 나누는 것) |
x >>> n | x의 각 비트가 오른쪽으로 n비트 이동. 빈자리는 0. |
중간 값 구하기: 백기선 님 스터디 영상 中
int start = 2_000_000_000;
int end = 2_100_000_000;
int mid = (start + end)/2;
//위처럼 중간 값을 구하는 방식은 괄호 안 계산에서 오버플로우가 날 수 있기 때문에 안전하지 않다.
//쉬운 해결법
int mid = start + (end - start) / 2;
//멋 한번 내고 싶을 때
int mid = (start + end) >>> 1;
비트 연산자 잘 안 쓰니까 심심할까봐
문제풀이: 백기선 님 스터디 영상 中
int형 배열이 있다.
해당 배열에 들어있는 숫자들은 오직 한 숫자를 제외하고는 모두 두 번씩 들어있다.
오직 한 번만 등장하는 숫자를 찾는 코드를 작성하라.
여러 방법이 있겠지만 비트연산자 사용 모습
public class Hello{
public static void main(String[] args){
Hello hello = new Hello();
int result = hello.solution(new int[] {5,5,4,4,3,3,2,2,1});
System.out.println(result);
}
// TODO XOR
// 비트가 서로 다르면 1, 같으면 0
/*
5 ^ 0 = 5
5 ^ 5 = 0
비트
101 101
000 101
--- ---
101 000
5 ^ 1 ^ 5 => (5 ^ 5) ^ 1 = 0 ^ 1 = 1
*/
private int solution(int[] numbers){
int result = 0;
for(int number : numbers){
reslut ^= number;
}
return result;
}
}
ture
false
중 하나관계 연산자 | 결과 |
---|---|
> | 좌변 값이 크면 true , 아니면 false |
< | 좌변 값이 작으면 true , 아니면 false |
>= | 좌변 값이 크거나 같으면 true , 아니면 false |
<= | 좌변 값이 작거나 같으면 true , 아니면 false |
== | 두 값이 같으면 true , 아니면 false |
!= | 두 값이 다르면 true , 아미녀 false |
==
!=
는 참조형의 경우 객체의 주소값을 비교boolean
만 허용논리 연산자 | 결과 |
---|---|
&& | 두 피연산자가 모두 true 일때만 결과값 true |
|| | 두 피연산자 중 하나라도 true 라면 결과값 ture |
! | true 면 false , false 면 true 리턴 |
&&
, ||
연산 중 두 항을 모두 시행하지 않더라도 결과 값을 알 수 있을 때, 나머지 항을 실행하지 않는다&
, |
의 두 피연산자가 boolean
인 경우 논리 연산자 처럼 사용될 수 있는데, 이떄는 단락 회로 평가가 일어나지 않는다true
나 false
리턴null
평가 시 항상 false
리턴캐스트 연산자와 함께 사용되는 모습
Animal cat = new Cat();
if(cat instanceof Cat){ //cat의 인스턴스 자료형이 Cat이라면
Cat cat = (Cat) cat;
}
복합 대입 연산자
op= | = |
---|---|
i += 1; | i = i + 1; |
i -= 1; | i = i - 1; |
i *= 1; | i = i * 1; |
i /= 1; | i = i / 1; |
i %= 1; | i = i % 1; |
i <<= 1; | i = i << 1; |
i >>= 1; | i = i >> 1; |
i &= 1; | i = i & 1; |
i ^= 1; | i = i ^ 1; |
i |= 1; | i = i | 1; |
i *= 10 + j; | i = i * (10 + j); |
출저: 자바의 정석
(Parameters) -> { Body }
Thread thread = new Thread( () -> {
System.out.println("람다 표현식 사용")
});
람다 표현식?
조건식 ? 식1 : 식2
true
면 식1
, false
면 식2
를 리턴//삼항 연산자
void fun1() {
return Condition1 ? value1
: Condition2 ? value2
: value3
}
//if문
void fun2() {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else {
return value3
}
}
연산자 우선순위 표
Precedence | Operator | Type | Associativity |
---|---|---|---|
15 | () [] · | Parentheses Array subscript Member selection | Left to Right |
14 | ++ -- | Unary post-increment Unary post-decrement | Right to left |
13 | ++ -- + - ! ~ ( type ) | Unary pre-increment Unary pre-decrement Unary plus Unary minus Unary logical negation Unary bitwise complement Unary type cast | Right to left |
12 | * / % | Multiplication Division Modulus | Left to right |
11 | + - | Addition Subtraction | Left to right |
10 | << >> >>> | Bitwise left shift Bitwise right shift with sign extension Bitwise right shift with zero extension | Left to right |
9 | < <= > >= instanceof | Relational less than Relational less than or equal Relational greater than Relational greater than or equal Type comparison (objects only) | Left to right |
8 | == != | Relational is equal to Relational is not equal to | Left to right |
7 | & | Bitwise AND | Left to right |
6 | ^ | Bitwise exclusive OR | Left to right |
5 | | | Bitwise inclusive OR | Left to right |
4 | && | Logical AND | Left to right |
3 | || | Logical OR | Left to right |
2 | ? : | Ternary conditional | Right to left |
1 | = += -= *= /= %= | Assignment Addition assignment Subtraction assignment Multiplication assignment Division assignment Modulus assignment | Right to left |
Larger number means higher precedence.
출저: bilkent: Java Operator Precedence Table
기존 스위치문 (switch statement)
switch (day) {
case MONDAY:
case TUESDAY:
System.out.println("A 하는 날");
break;
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
System.out.println("B 하는 날");
break;
case SATURDAY:
System.out.println("C 하는 날");
break;
case SUNDAY:
System.out.println("쉬는 날");
break;
}
java 12 스위치문(switch statement)과 표현식(switch expression)
//스위치문
String toDo;
switch (day) {
case MONDAY, TUESDAY -> toDo = "A";
case WEDNESDAY, THURSDAY, FRIDAY -> toDo = "B";
case SATURDAY -> toDo = "C";
case SUNDAY -> toDo = "D";
}
//스위치 표현식
String toDo = switch (day) {
case MONDAY, TUESDAY -> "A";
case WEDNESDAY, THURSDAY, FRIDAY -> "B";
case SATURDAY -> "C";
case SUNDAY -> "D";
};
int result = switch (num) {
case "one":
break 1;
case "two":
break 2;
};
case
에 여러 값 설정 가능case L ->
사용 가능case L ->
오른쪽에 있는 코드만 실행되며 break
생략default
필요)break <value>
사용 가능java 13 스위치 표현식
int result = switch (num) {
case "one": yield 1;
case "two": yield 2;
default: yield 0;};
break <value>
가 yield <value>
로 변경