일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- flatten
- MySQL
- 딥러닝
- JavaScript
- 생활코딩 머신러닝야학
- Java
- Python
- 생활코딩
- 머신러닝(딥러닝)
- Database
- CNN
- 판다스
- 데이터베이스
- 개발자
- 파이썬
- 머신러닝
- reshape
- pandas
- tensorflow
- LeNet
- 머신러닝야학
- 이것이 자바다
- 데이터베이서
- 야학
- 카카오클라우드스쿨2기
- 데이터베이스 개론
- 연산자
- 생활코딩 데이터베이스
- Today
- Total
IT's 우
이것이 자바다, java_3장. 연산자 본문
-부호 연산자
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);
short s =100;
//short result3= -s; //컴파일 에러, short 타입 값을 부호 연산하면 int 타입 값으로 바뀐다.
int result4 = -s;
System.out.println("result4= " + result4);
}
}
- 증감 연산자(++, --)
public class IncreaseDecreaseOperatorExample {
public static void main(String[] args) {
int x =10;
int y = 10;
int z;
System.out.println("---------------");
x++; //x=11
++x; //x=12
System.out.println("x= " + x);
System.out.println("---------------");
y--; //y=9
--y; //y=8
System.out.println("y= " + y);
System.out.println("---------------");
z=x++; // z=12, x=13
System.out.println("z= " + z);
System.out.println("x= "+ x);
System.out.println("---------------");
z=++x; // z=14, x=14
System.out.println("z= " + z);
System.out.println("x= "+ x);
System.out.println("---------------");
z= ++x + y++; // z=23, x=15, y=9
System.out.println("z= " + z);
System.out.println("x= "+ x);
System.out.println("y= " + y);
}
}
- 논리 부정 연산자(!)
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);
}
}
- 비트 반전 연산자(~)
비트 반전 연산자의 결과를 이용하면 부호가 반대인 정수를 구할 수도 있다.
물론 간단하게 부호 연산자인 -를 이용해도 되겠지만,
비트 반전 연산자의 산출값에 1을 더하면 부호가 반대인 정수를 얻을 수 있다.
10을 비트 반전하면 -11을 얻는데, 여기에 1을 더하면 -10을 얻는다.
public class BitReverseOperatorExample {
public static String toBinaryString(int value) {
// 정수값을 총 32비트의 이진 문자열로 리턴하는 메소드
String str = Integer.toBinaryString(value);
while(str.length() < 32) {
str = "0" + str;
}
return str;
}
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(v5) + " (십진수: " + v5 + ")");
System.out.println(toBinaryString(v6) + " (십진수: " + v6 + ")");
}
}
- 산술 연산자
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; //int타입으로 실수 타입의 결과를 얻고싶다면 피연산자 중 최소한 하나는 실수 타입이어야 한다.
System.out.println("result6= " + result6);
}
}
- char 타입 연산
public class CharOperationExample {
public static void main(String[] args) {
char c1 = 'A' + 1;
//리터럴 문자 'A'에 1을 더하면 문자 A는 65라는 유니코드를 가지므로 66이 된다. 따라서 66인 유니코드는 문자 B이므로 c1에는 문자 B가 저장된다.
char c2 = 'A';
//char c3 = c2 +1; //컴파일 에러
//변수 c2에 1을 더하면 c2는 int 타입으로 변환되고 1과 연산이 되기 때문에 산출 타입은 int 타입이 된다. 따라서 char 타입 변수 c3에 대입을 할 수 없어 컴파일 에러가 발생한다.
System.out.println("c1 : " + c1);
System.out.println("c2 : " + c2);
//System.out.println("c3 : " + c3);
}
}
- 오버플로우
public class OverFlowExample {
public static void main(String[] args) {
int x =1000000;
int y =1000000;
int z = x * y;
System.out.println(z);
}
}
위 코드는 컴파일 에러는 발생하지 않지만, 변수 z에는 올바른 값이 저장되 않는다. 1000000*1000000은 10^6*10^6=10^12이 되어 int 타입에 저장될 수 있는 값의 범위를 초과하게 되므로 쓰레기값인 -727379968을 얻게 된다. 상기 예제가 올바른 값을 얻기 위해서는 변수 x와 y 중 최소 하나라도 long 타입이 되어야 하고, 변수 z가 long 타입이어야 한다.
- 오버플로우 해결
public class OverflowExample2 {
public static void main(String[] args) {
long x=1000000;
long y=1000000;
long z= x*y;
System.out.println(z);
}
}
-산술 연산 전에 오버플로우를 감지
public class CheckOverflowExample {
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)) {
System.out.println("A");//어디서 오류인지 확인하기 위해
throw new ArithmeticException("오버플로우 발생");//예외 발생 코드
}
}else {//right<0일 경우
if(left<(Integer.MAX_VALUE - right)) {
System.out.println("B");//어디서 오류인지 확인하기 위해
throw new ArithmeticException("오버플로우 발생");//예외 발생 코드
}
}
return left + right;
}
}
정확한 계산해야 할 때는 부동소수점(실수) 타입을 사용하지 않는 것이 좋다.
- 정확하게 계산할 떄에는 부동소수점 타입을 사용하지 않는다.
public class AccuracyExample {
public static void main(String[] args) {
int apple =1;
double pieceUnit = 0.1;
int number =7;
double result = apple - number*pieceUnit;
System.out.println("사과 한개에서 ");
System.out.println("0.7 조각을 빼면, ");
System.out.println(result + " 조각이 남는다.");
}
}
이진 포맷의 가수를 사용하는 부동소수점 타입(float, double)은 0.1을 정확히 표현할 수 없어 근사치로 처리하기 때문이다. 정확한 계산이 필요하다면 정수 연산으로 변경해서 계산해야 한다.
public class AccuracyExample2 {
public static void main(String[] args) {
int apple =1;
int totalPieces = apple * 10;
int number =7;
int temp =totalPieces -number;
double result = temp/10.0;
System.out.println("사과 한 개에서 ");
System.out.println("0.7 조각을 빼면, ");
System.out.println(result + " 조각이 남는다.");
}
}
- 문자열 연결 연산자
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);
}
}
-비교 연산자
public interface CompareOperatorExample {
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);
}
}
double v4 = 0.1;
float v5 = 0.1f;
System.out.println(v4 == v5);
//false
이진 포맷의 가수를 사용하는 모든 부동소수점 타입은 0.1을 정확히 표현할 수가 없어서 0.1f는 0.1의 근사값으로 표현되어 0.10000000149011612와 같은 값이 되기 때문에 0.1보다 큰 값이 되어 버린다. 해결책은 피연산자를 모두 float 타입으로 강제 타입 변환한 후에 비교 연산을 하든지, 정수로 변환해서 비교하면 된다.
- 논리 연산자(&&, ||, &, |, ^, !)
&, |는 두 피연산자 모두를 평가해서 산출 결과를 낸다.
&&, ||는 앞의 피연산자만 평가하고 뒤의 피연산자를 평가하지 않고 바로 산출 결과를 낸다. 더 효울적이다.
- 비트 연산자(&, |, ^, ~, <<, >>, >>>)
>비트 논리 연산자(&, |, ^)
비트 연산자는 피연산자를 int 타입으로 자동 타입 변환한 후 연산을 수행한다. 그렇기 떄문에 byte, short, char 타입을 비트 논리 연산하면 그 결과는 int 타입이 된다. 그래서 다음은 컴파일 에러가 난다.
> 비트 이동 연산자(<<. >>, >>>)
비트 이동(shift) 연산자는 정수 데이터의 비트를 좌측 또는 우측으로 밀어서 이동시키는 연산을 수행한다.
a << b : 정수 a의 각 비트를 b만큼 왼쪽으로 이동(빈자리는 0으로 채워진다.)
a >> b : 정수 a의 각 비트를 b만큼 오른쪽으로 이동(빈자리는 정수 a의 최상위 부호 비트(MSB)와 같은 값으로 채워진다.)
a >>> b : 정수 a의 각 비트를 b만큼 오른쪽으로 이동(빈자리는 0으로 채워진다.)
- 대입 연산자
출처: 이것이 자바다 신용권 지음
'Java > 이것이 자바다' 카테고리의 다른 글
[Macbook Air M1] Java, Eclipse 설치 (0) | 2022.04.24 |
---|---|
이것이 자바다[Java]_String 타입의 문자열 비교 (0) | 2021.01.16 |
이것이 자바다[Java]_3장 Nan, Infinity 연산, ArithmeticException(예외) (0) | 2021.01.16 |