public class Ex12 { //곱셈 연삲 후 int값을 초과해서 오버플로우 발생. public static void main(String[] args){ int a = 1000000 * 1000000 / 1000000; // 곱셈 연산 후 int값을 초과해버려서 오버플로우가 일어남. //int a = 1000000 * (1000000 / 1000000); int b = 1000000 / 1000000 * 1000000; System.out.println(a); System.out.println(b); } }
[JAVA] ch03-11. int * int = 오버플로우
·
JAVA/예제
public class Ex11 {//int*int=오버플로우 long타입으로 바꿔주면 해결. int형은 2의 32승-1 결국, 맨앞 숫자2, 0 9개까지 가능 public static void main(String[] args){ //long a = 1000000 * 1000000; //오버플로우 발생 int*int long a = (long)1000000 * 1000000; // long타입으로 바꿔주면 해결 long b = 1000000 * 1000000L; System.out.println(a); System.out.println(b); } }
[JAVA] ch03-10. int에서 long 오버플로우
·
JAVA/예제
public class Ex10 { //a*b의 결과는 int값으로 계산되어 long으로 넘어가는 도중 int 계산에서 //오버플로우가 일어난 상태에서 long 변수로 들어감. public static void main(String[] args){ int a = 1000000; //1,000,000 int b = 2000000; //2,000,000 long c = a * b; // 2,000,000,000,000 [값의 변질이 일어남] System.out.println(c); //-1454759936 } }
[JAVA] ch03-09. byte 오버플로우
·
JAVA/예제
public class Ex09 { //byte는 0부터 127까지 128을 빼면 300-1287= 172-128 = 44 결국 오버플로우로 인한 결과 public static void main(String[] args){ byte a = 10; byte b = 30; byte c = (byte)(a*b); // value loss. System.out.println(c); // 44 } }
[JAVA] ch03-08. 덧셈
·
JAVA/예제
public class Ex08 {//덧셈. public static void main(String[] args){ byte a = 10; byte b = 20; byte c = (byte)(a+b); //byte c = a+b; // result type is int. System.out.println(c); } }
[JAVA] ch03-07. 논리 연산자
·
JAVA/예제
public class Ex07 {//논리연산자 public static void main(String[] args){ boolean power = false; //논리연산자는 boolean에서만 가능 System.out.println(power); power = !power; System.out.println(power); power = !power; System.out.println(power); } }
[JAVA] ch03-06. 형변환
·
JAVA/예제
public class Ex06 { // 형변환, int미만의 타입은 byte, char, short는 int로 바뀐다. public static void main(String[] args){ byte a = 10; //byte result = -a; // result type is int. byte result = (byte)-a; // int미만의 타입은 byte, char, short는 int로 바뀐다. System.out.println(a+","+result); long b = 10; //int 타입 이상의 타입은 그대로 long result2 = -b; System.out.println(b+","+result2); //*int + float -> float + float -> float } }
[JAVA] ch03-05. 비트전환
·
JAVA/예제
public class Ex05 {//비트전환 public static void main(String[] args){ long b = 10; //bitwise operator is only for integer type(정수형에서만 가능) System.out.println(b); System.out.println(~b); System.out.println(~b + 1); //~ 0을 1로 1을 0으로 비트전환 음수를 표현하기 위한 방법 중 1 } }
[JAVA] ch03-04. 부호 연산자
·
JAVA/예제
public class Ex04 { //부호 연산자 public static void main(String[] args){ int i = -10; i = +i; System.out.println("i=" + i); i = -10; i = -i; System.out.println("i=" + i); } }