JAVA/이것이 자바다
이것이 자바다 | 3강_연산자
한 면만 쓴 종이
2022. 1. 13. 17:55
연산자
- 대부분의 연산자: 왼쪽에서 오른쪽
- 단항 연산자, 부호 연산자, 대입 연산자: 오른쪽에서 왼쪽
연산자 우선순위
- 단항>이항>삼항 연산자
- 산술>비교>논리>대입 연산자
-short타입 값을 부호 연산하면 int타입으로 됨
short s = 100;
short result = -s; //컴파일 에러
-올바르게 고친 코드
short s = 100;
int result = -s;
증감 연산자
package chap03;
public class chap03_1 {
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);
short s = 100;
//short result3 = -s; //컴파일 에러
int result3 = -s;
System.out.println("result3=" + result3);
}
}
논리 부정 연산자
package chap03;
public class chap03_2 {
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);
}
}
비트 반전 연산자
byte v1 = 10;
byte v2 = ~v1; //컴파일 에러
int v2 = ~v1; //-11 (정상작동)
byte v1 = 10;
int v2 = ~v1 + 1; //-10
Integer.toBinaryString()
- 정수값을 총 32비트의 이진 문자열로 리턴하는 메소드
- 앞의 비트가 모두 0이면 0은 생략되고 나머지 문자열만 리턴 ->
- 32개의 문자열을 얻기 위해서는 아래의 메소드 필요
public static String toBinaryString(int value) { String str = Integer.toBinaryString(value); while(str.length() < 32) { str = "0" + str; } return str; }
비트 반전 연산자
package chap03;
public class chap03_3 {
public static void main(String[] args) {
int v1 = 10;
int v2 = ~v1;
int v3 = ~v1 + 1;
System.out.println(toBinaryString(v1) + "(십진수:" + v1 + ")");
System.out.println(toBinaryString(v2) + "(십진수: " + v2 + ")");
System.out.println(toBinaryString(v3) + "(십진수: " + v3 + ")");
System.out.println();
int v4 = -10;
int v5 = ~v4;
int v6 = ~v4 + 1;
System.out.println(toBinaryString(v4) + " (십진수: " + v4 + ")");
System.out.println(toBinaryString(v4) + " (십진수: " + v5 + ")");
System.out.println(toBinaryString(v4) + " (십진수: " + v6 + ")");
}
public static String toBinaryString(int value) {
String str = Integer.toBinaryString(value);
while(str.length() < 32) {
str = "0" + str;
}
return str;
}
}
산술 연산자
- 피연산자가 모두 정수타입, int타입보다 크기가 작은 타입 -> int타입으로 변환 후, 연산 => 산출 타입은 int
- 피연산자가 모두 정수 타입, long타입 존재 -> long타입으로 변환 후, 연산 => 산출타입은 long
- 피연산자 중 실수타입(float, double)이 존재 -> 크기가 큰 실수 타입으로 변환 후 연산 => 산출 타입은 실수 타입
char 타입 연산
package chap03;
public class chap03_4 {
public static void main(String[] args) {
char c1 = 'A' + 1;
char c2 = 'A';
//char c3 = c2 + 1; //컴파일 에러(int타입을 char타입 변수에 대입할 수 없기 때문)
char c3 = (char) (c2 + 1); //강제 타입 변환
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c3: " + c3);
}
}
산술 연산 전에 오버플로우 탐지
package chap03;
public class chap03_5 {
public static void main (String[] args) {
try {
int result = safeAdd(2000000000, 2000000000);
System.out.println(result);
} catch(ArithmeticException e) { //예외처리
System.out.println("오버플로우가 발생하여 정확하게 계산할 수 없음");
}
}
public static int safeAdd(int left, int right) {
if((right>0)) {
if(left>(Integer.MAX_VALUE - right))
throw new ArithmeticException("오버플로우 발생");
}
return left + right;
}
}
NaN Infinity 연산
5 / 0.0 // Infinity
5 % 0.0 // NaN
"NaN"을 체크하고 연산 수행
// "NaN" 문자열의 문제점
package chap03;
public class chap03_6 {
public static void main(String[] args) {
String userInput = "NaN";
double val = Double.valueOf(userInput); //Double.valueOf 메소드에 의해 double타입 NaN으로 변환
double currentBalance = 10000.0;
currentBalance = 10000.0;
currentBalance += val;
System.out.println(currentBalance);
}
}
*Double.isNaN() 메소드 이용 -> val의 값이 NaN인지 검사, ==연산자 이용하면 안 됨 (NaN은 != 연산자를 제외한 모든 연산자 사용할 경우false 리턴함)
문자열 연결 연산자
//문자열 연결 연산자
package chap03;
public class chap03_7 {
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);
}
}
0.1 과 0.1f
0.1 == 0.1f -> false
false인 이유 : 이진 포맷의 가수를 사용하는 모든 부동소수점 타입은 0.1을 정확히 표현할 수 없어서 0.1f 는 0.1의 근사값으로 표현되기 때문
문자열 비교
package chap03;
public class chap03_8 {
public static void main(String args[]) {
String strVar1 = "신민철";
String strVar2 = "신민철";
String strVar3 = new String("신민철");
System.out.println(strVar1 == strVar2);
System.out.println(strVar1 == strVar3);
System.out.println();
System.out.println(strVar1.equals(strVar2));
System.out.println(strVar1.equals(strVar3));
}
}
삼항 연산자
package chap03;
public class chap03_9 {
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등급입니다.
}
}