3강의 예제를 모아둔 것이다.

일부는 다른 글에서 설명하면서 사용할 것이고 일부는 넘어갈 거라서 만약 코드 적기가 귀찮다면 복사 붙여넣기해서 사용하자.

ctrl + F 한 후 class이름을 검색하면 쉽게 찾을 수 있다.

public class OperatorEx01 {
	public static void main(String[] args) {

		int i = 5;
		i++; // i=i+1;
		System.out.println(i);

		i = 5;
		++i;
		System.out.println(i);

	}

}
6
6

 

 

public class OperatorEx02 {
	public static void main(String[] args) {
		int i = 5, j = 0;
		j = i++;
		System.out.println("j=i++; 실행 후, i=" + i + ", j=" + j);
		i = 5; 
		j = 0;
		j = ++i;
		System.out.println("j=++i; 실행 후, i=" + i + ", j=" + j);
	}
}
j=i++; 실행 후, i=6, j=5
j=++i; 실행 후, i=6, j=6

 

 

public class OperatorEx03 {
	public static void main(String[] args) {
		int i=5, j=5;
		System.out.println(i++);
		System.out.println(++j);
		System.out.println("i = " + i + ", j = " + j);		
		int x = 5;		
		x = x++ - ++x;
		System.out.println(x);		
		byte b = -128;
		b = (byte)-b;
		System.out.println(-b);
	}
}
5
6
i = 6, j = 6
-2
128

 

 

public class OperatorEx04 {
	public static void main(String[] args) {
		int i = -10;
		i = +i;
		System.out.println(i);

		i = -10;
		i = -i;
		System.out.println(i);
	}
}
-10
10

 

 

public class OperatorEx05 {
	public static void main(String[] args) {
		int a = 10;
		int b = 4;
        
		System.out.printf("%d + %d = %d%n", a, b, a + b);
		System.out.printf("%d - %d = %d%n", a, b, a - b);
		System.out.printf("%d * %d = %d%n", a, b, a * b);
		System.out.printf("%d / %d = %d%n", a, b, a / b);
		System.out.printf("%d / %f = %f%n", a, (float) b, a / (float) b);
	}
}
10 + 4 = 14
10 - 4 = 6
10 * 4 = 40
10 / 4 = 2
10 / 4.000000 = 2.500000
66.66666666666667
66.67
66.66
66.66200

 

 

public class Exercise3_06 {
	public static void main(String[] args) {
		byte a = 10;
		byte b = 20;
		byte c = a + b;
		System.out.println(c);
	}
}
30

 

 

public class Exercise3_07 {
	public static void main(String[] args) {
		byte a = 10;
		byte b = 20;
		byte c = (byte) (a + b);
		System.out.println(c);
	}
}
44

 

 

public class OperatorEx08 {
	public static void main(String[] args) {
		int a = 1_000_000;	// 1,000,000 1백만
		int b = 2_000_000;  // 2,000,000 2백만
		
//		int c = a * b; // 2 * 10^12
		long c = a* b;	// a* b = 2,000,000,000,000 ?
		System.out.println(c);
	}

}
-1454759936

 

public class OperatorEx09 {
	public static void main(String[] args) {
		long a = 1_000_000 * 1_000_000;
		long b = 1_000_000 * 1_000_000L;
		
		System.out.println("a="+a);
		System.out.println("b="+b);
	}

}
a=-727379968
b=1000000000000

 

 

public class OperatorEx10 {
	public static void main(String[] args) {
		int a = 1000_000;

		int result1 = a * a / a;
		int result2 = a / a * a;
		
		System.out.printf("%d * %d / %d = %d%n", a, a, a, result1);
		System.out.printf("%d / %d * %d = %d%n", a, a, a, result2);

	}
}
1000000 * 1000000 / 1000000 = -727
1000000 / 1000000 * 1000000 = 1000000

 

 

public class OperatorEx11 {
	public static void main(String[] args) {
		char a = 'a';
		char d = 'd';
		char zero = '0';
		char two = '2';
		
		System.out.printf("'%c' - '%c' = %d%n", d, a, d - a);
		System.out.printf("'%c' - '%c' = %d%n", two, zero, two - zero);
		System.out.printf("'%c' = %d%n", a, (int)a);
		System.out.printf("'%c' = %d%n", d, (int)d);
		System.out.printf("'%c' = %d%n", zero, (int)zero);
		System.out.printf("'%c' = %d%n", two, (int)two);
		
//		char c1 = 'A';
//		char c2 = c1 + 1; // 변수와 리터럴의 연산이라 안됨 final로 리터럴로바꾸면 ㄱ나ㅡㅇ
//		상수 포함
		char c2 = 'a' + 1; // 리터럴 간의 연산
		
		char c3 = 0xAC00;
		System.out.println(c2);
		System.out.println(c3);
		
		int sec = 60 * 60 * 24; // 
		System.out.println(sec);
	}

}
'd' - 'a' = 3
'2' - '0' = 2
'a' = 97
'd' = 100
'0' = 48
'2' = 50
b
가
86400

 

 

public class OperatorEx12 {
	public static void main(String[] args) {
		
		char c1 = 'a';	// c1에는 문자 'a'의 코드값인 97이 저장된다.
		char c2 = c1;	// c1에 저장되어 있는 값이 c2에 저장된다.
		char c3 = ' ';	// c3를 공백으로 초기화 한다.
		
		int i = c1 + 1;	// 'a'+1 > 97+1 > 98
		
		c3 = (char)(c1 + 1);	// c1 + 1의 형태가 int 이므로 char로 변환
		c2++;
		c2++;
		
		System.out.println("i=" + i);
		System.out.println("c2=" + c2);
		System.out.println("c3=" + c3);
	}

}
i=98
c2=c
c3=b

 

 

public class OperatorEx13 {
	public static void main(String[] args) {
		char c1 = 'a';
		
//		char c2 = c1 + 1; // 컴파일 에러
		char c2 = 'a' + 1;	//리터럴간의 연산이므로 에러 X
		
		System.out.println(c1);
		System.out.println(c2);
	}

}
a
b

 

 

public class OperatorEx14 {
	public static void main(String[] args) {
		char c = 'a';
		for (int i = 0; i < 26; i++) {
			// 블럭{} 안의 문장을 26번 반복한다.]
			System.out.print(c++);
		} // 'a;부터 26개의 문자를 출력한다.

		System.out.println(); // 줄바꿈을한다

		c = 'A';
		for (int i = 0; i < 26; i++) { // 블럭 {} 안의 문장을 26번 반복한다.
			System.out.print(c++);	   //'A'부터 26개의 문자를 출력한다.
		}

		System.out.println();

		c = '0';
		for (int i = 0; i < 10; i++)	// 블럭{} 안의 문장을 10번 반복한다.
			System.out.println(c++);	// '0'부터 10개의 문자를 출력한다.
		System.out.println();

		// 줄바꿈을한다
	}
}
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0
1
2
3
4
5
6
7
8
9

 

 

import java.util.Scanner;

public class OperatorEx15 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		char lowerCase = 'x';
		char upperCase = (char)(lowerCase - 32);
		System.out.println(upperCase);
		}
 }
X

 

 

public class OperatorEx16 {
	public static void main(String[] args) {
		float pi = 3.141592f;
		float shortPi = (int)(pi * 1000) / 1000f;
		System.out.println(shortPi);
	}

}
3.141

 

 

public class OperatorEx17 {
	public static void main(String[] args) {
		double pi = 3.141592;
		double shortPi = (int)(pi * 1000 + 0.5) / 1000.0;

		System.out.println(shortPi);
	}

}
3.142

 

 

public class OperatorEx18 {
	public static void main(String[] args) {
		double pi = 3.141592;
		double shortPi = Math.round(pi * 1000) / 1000.0;
		System.out.println(shortPi);
	}

}
3.142

 

 

public class OperatorEx19 {
	public static void main(String[] args) {
		int x = 10;
		int y = 8;
		
		System.out.printf("%d을 %d로 나누면, %n", x, y);
		System.out.printf("몫은 %d이고, 나머지는 %d입니다.%n", x / y, x % y);
        	}

}
10을 8로 나누면, 
몫은 1이고, 나머지는 2입니다.

 

 

public class OperatorEx20 {
	public static void main(String[] args) {
		System.out.println(-10%8);
		System.out.println(10%-8);	
		System.out.println(-10%-8);		
	}

}
-2
2
-2

 

 

public class OperatorEx21 {
	public static void main(String[] args) {
		System.out.printf("10 == 10.0f \t %b%n", 10==10.0f);
		System.out.printf("'0' == 0 \t %b%n", '0' == 0);	
		System.out.printf("'A' == 65 \t %b%n", 'A' == 65);
		System.out.printf("'A' > 'B' \t %b%n", 'A' > 'B');	 
		System.out.printf("'A'+1 != 'B' \t %b%n", 'A'+1 != 'B');	
	}
}
10 == 10.0f 	 true
'0' == 0 	 false
'A' == 65 	 true
'A' > 'B' 	 false
'A'+1 != 'B' 	 false

 

 

public class OperatorEX22 {
	public static void main(String[] args) {
		float f = 0.1f;
		double d = 0.1;
		double d2 = (double) f;

		System.out.printf("10.0==10.0f	%b%n ", 10.0 == 10.0f);
		System.out.printf("0.1==0.1f	%b%n ", 0.1 == 0.1f);
		System.out.printf("f=%19.17f%n ", f);
		System.out.printf("d =%19.17f%n ", d);
		System.out.printf("d2=%19.17f%n ", d2);
		System.out.printf("d==f %b%n ", d == f);
		System.out.printf("d==d2 %b%n ", d == d2);
		System.out.printf("d2==f %b%n ", d2 == f);
		System.out.printf("(float)d==f %b%n ", (float) d == f);
	}

}
0.1==0.1f	false
 f=0.10000000149011612
 d =0.10000000000000000
 d2=0.10000000149011612
 d==f false
 d==d2 false
 d2==f true
 (float)d==f true

 

 

public class OperatorEx23 {
	public static void main(String[] args) {
		String str1 = "abc";
		String str2 = new String("abc");

		System.out.printf("\"abc\"==\"abc\" ? %b%n", "abc"=="abc");
		System.out.printf(" str1==\"abc\" ? %b%n", str1=="abc");
		System.out.printf("str1.equals(\"abc\") ? %b%n", str1.equals("abc"));
		System.out.printf("str2.equals(\"abc\") ? %b%n", str2.equals("abc"));
		System.out.printf("str2.equalsIgnotreCase(\"abc\") ? %b%n", str2.equalsIgnoreCase("abc"));
	}

}
"abc"=="abc" ? true
 str1=="abc" ? true
 str1=="abc" ? false
str1.equals("abc") ? true
str2.equals("abc") ? true
str2.equalsIgnotreCase("abc") ? true

 

 

public class OperatorEx24 {
	public static void main(String[] args) {
		int x = 0;
		char ch = ' ';
		
		x = 15;
		System.out.printf("x=%2d, 10 < x && x < 20 = %b%n", x, 10 < x && x < 20);
		
		x = 6;
		System.out.printf("x=%2d , x%%2==0 || x%%3==0 && x%%6!=0 = %b%n",x, x%2==0 || x%3==0&&x%6!=0);
		System.out.printf("x=%2d , (x%%2==0 || x%%3==0) && x%%6!=0 = %b%n",x, (x%2==0 || x%3==0)&&x%6!=0);
		
		ch='1';
		System.out.printf("ch='%c', '0' <= ch && ch <= '9' =%b%n", ch, '0' <= ch && ch <='9');
		
		ch='a';
		System.out.printf("ch='%c', 'a' <= ch && ch <= 'z' =%b%n", ch, 'a' <= ch && ch <='z');
		
		ch='A';
		System.out.printf("ch='%c', 'A' <= ch && ch <= 'Z' =%b%n", ch, 'A' <= ch && ch <='Z');
		

		ch='q';
		System.out.printf("ch='%c', 'q' <= ch && ch <= 'Q' =%b%n", ch, 'q' <= ch && ch <='Q');
	}

}
x=15, 10 < x && x < 20 = true
x= 6 , x%2==0 || x%3==0 && x%6!=0 = true
x= 6 , (x%2==0 || x%3==0) && x%6!=0 = false
ch='1', '0' <= ch && ch <= '9' =true
ch='a', 'a' <= ch && ch <= 'z' =true
ch='A', 'A' <= ch && ch <= 'Z' =true
ch='q', 'q' <= ch && ch <= 'Q' =false

 

 

import java.util.Scanner;

public class OperatorEx25 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		char ch = ' ';
		for (int i = 1; i <= 10; i--) {

			System.out.printf("문자를 하나 입력하세요.>");

			String input = scanner.nextLine();
			ch = input.charAt(0);

			if ('0' <= ch && ch <= '9') {
				System.out.printf("입력하신 문자는 숫자입니다.%n");
			}
			if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'z')) {
				System.out.printf("입력하신 문자는 영문자입니다.%n");
			}	
		} // main
		scanner.close();}
문자를 하나 입력하세요.>a
입력하신 문자는 영문자입니다.
문자를 하나 입력하세요.>1
입력하신 문자는 숫자입니다.
문자를 하나 입력하세요.>

 

 

public class OperatorEx26 {
	public static void main(String[] args) {
		int a = 5;
		int b = 0;

		System.out.printf("a=%d, b=%d%n", a, b);
		System.out.printf("a!=0 || ++b!=0 = %b%n", a != 0 || ++b != 0);
		System.out.printf("a=%d, b=%d%n", a, b);
		System.out.printf("a==0 && ++b!=0 = %b%n", a == 0 && ++b != 0);
		System.out.printf("a=%d, b=%d%n", a, b);
	}
}
a=5, b=0
a!=0 || ++b!=0 = true
a=5, b=0
a==0 && ++b!=0 = false
a=5, b=0

 

 

public class OperatorEx27 {
	public static void main(String[] args) {
		boolean b = true;
		char ch = 'c';

		System.out.printf("b=%b%n", b);
		System.out.printf("!b=%b%n", !b);
		System.out.printf("!!b=%b%n", !!b);
		System.out.printf("!!!b=%b%n", !!!b);
		System.out.println();

		System.out.printf("ch=%c%n", ch);
		System.out.printf("ch < 'a' || ch > 'z'=%b%n", ch < 'a' || ch > 'z');

		System.out.printf("!('a'<=ch && ch<='z'=%b%n", !('a' <= ch && ch <= 'z'));

		System.out.printf("'a'<=ch && ch<='z' =%b%n", 'a' <= ch && ch <= 'z');
		} // main의 끝
}
b=true
!b=false
!!b=true
!!!b=false

ch=c
ch < 'a' || ch > 'z'=false
!('a'<=ch && ch<='z'=false
'a'<=ch && ch<='z' =true
4
7
3
-2
24
1
11111111111111111111111111111010
11111111111111111111111111111101
1111111111111111111111111111101
2147483645
5
5

 

 

public class OperatorEx28 {
	public static void main(String[] args) {
		int x = 0xAB, y = 0xF;

		System.out.printf("x = %#X  \t\t%s%n", x, toBinaryString(x));
		System.out.printf("y = %#X  \t\t%s%n", y, toBinaryString(y));
		System.out.printf("%#X | %#X = %#X \t%s%n", x, y, x | y, toBinaryString(x | y));
		System.out.printf("%#X & %#X = %#X \t%s%n", x, y, x & y, toBinaryString(x & y));
		System.out.printf("%#X ^ %#X = %#X \t%s%n", x, y, x ^ y, toBinaryString(x ^ y));
		System.out.printf("%#X ^ %#X ^ %#X = %#X \t%s%n", x, y, y, x ^ y, toBinaryString(x ^ y ^ y));

	} // main의 끝

	static String toBinaryString(int x) { // 10진 정수를 2진수로 변환하는 메서드
		String zero = "00000000000000000000000000000000";
		String tmp = zero + Integer.toBinaryString(x);
		return tmp.substring(tmp.length() - 32);
	}
}
x = 0XAB  		00000000000000000000000010101011
y = 0XF  		00000000000000000000000000001111
0XAB | 0XF = 0XAF 	00000000000000000000000010101111
0XAB & 0XF = 0XB 	00000000000000000000000000001011
0XAB ^ 0XF = 0XA4 	00000000000000000000000010100100
0XAB ^ 0XF ^ 0XF = 0XA4 	00000000000000000000000010101011

 

 

public class OperatorEx29 {
	public static void main(String[] args) {
		byte p = 10;
		byte n = -10;

		System.out.printf(" p =%d |t%s%n", p, toBinaryString(p));
		System.out.printf("~p =%d |t%s%n", ~p, toBinaryString(~p));
		System.out.printf("~p+1 =%d |t%s%n", ~p+1, toBinaryString(~p+1));
		System.out.printf("~~p =%d |t%s%n", ~~p, toBinaryString(~~p));
		System.out.println();
		System.out.printf(" n =%d%n", n);
		System.out.printf("~(n-1)=%d%n", ~(n-1));
	} // main의 끝

	static String toBinaryString(int x) { // 10진 정수를 2진수로 변환하는 메서드
		String zero = "00000000000000000000000000000000";
		String tmp = zero + Integer.toBinaryString(x);
		return tmp.substring(tmp.length() - 32);
	}
}
 p =10 |t00000000000000000000000000001010
~p =-11 |t11111111111111111111111111110101
~p+1 =-10 |t11111111111111111111111111110110
~~p =10 |t00000000000000000000000000001010

 n =-10
~(n-1)=10

 

 

public class OperatorEx30 {
	// 10진 정수를 2진수로 변환하는 메서드
	static String toBinaryString(int x) { 
		String zero = "00000000000000000000000000000000";
		String tmp = zero + Integer.toBinaryString(x);
		return tmp.substring(tmp.length() - 32);
	}
	public static void main(String[] args) {
		
		int dec = 8;
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1));
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2));
		System.out.println();
		
		dec = -8;
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1));
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2));
		System.out.println();
		
		dec = 8;
		System.out.printf("%d >> %2d = %4d |t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
		System.out.printf("%d >> %2d = %4d |t%s%n", dec, 32, dec >> 32, toBinaryString(dec >> 32));
		
	} // main의 끝
}
8 >> 0 =    8 |t00000000000000000000000000001000
8 >> 1 =    4 |t00000000000000000000000000000100
8 >> 2 =    2 |t00000000000000000000000000000010
8 << 0 =    8 |t00000000000000000000000000001000
8 << 1 =   16 |t00000000000000000000000000010000
8 << 2 =   32 |t00000000000000000000000000100000

-8 >> 0 =   -8 |t11111111111111111111111111111000
-8 >> 1 =   -4 |t11111111111111111111111111111100
-8 >> 2 =   -2 |t11111111111111111111111111111110
-8 << 0 =   -8 |t11111111111111111111111111111000
-8 << 1 =  -16 |t11111111111111111111111111110000
-8 << 2 =  -32 |t11111111111111111111111111100000

8 >>  0 =    8 |t00000000000000000000000000001000
8 >> 32 =    8 |t00000000000000000000000000001000

 

 

public class OperatorEx31 {
	public static void main(String[] args) {
		int dec =1234;
		int hex = 0xABCD;
		int mask = 0xF;
		
		System.out.printf("hex=%X%n", hex);
		System.out.printf("%X%n", hex & mask);
		
		hex = hex >> 4;
		System.out.printf("%X%n", hex & mask);
		
		hex = hex >> 4;
		System.out.printf("%X%n", hex & mask);
		
		hex = hex >> 4;
		System.out.printf("%X%n", hex & mask);
	}

}
hex=ABCD
D
C
B
A

 

 

public class OperatorEx32 {
	public static void main(String[] args) {
		int x, y, z;
		int absX, absY, absZ;
		char signX, signY, signZ;
		
		x = 10;
		y = -5;
		z = 0;
		
		absX = x >= 0 ? x : -x; // x의 값이 음수이면, 양수로 만든다.
		absY = y >= 0 ? y : -y;
		absZ = z >= 0 ? z : -z;
		
		signX = x > 0 ? '+' : (x==0 ? ' ' : '-'); //조건 연산자를 중첩
		signY = y > 0 ? '+' : (y==0 ? ' ' : '-');
		signZ = z > 0 ? '+' : (z==0 ? ' ' : '-'); 
		
		System.out.printf("x=%c%d%n", signX, absX);
		System.out.printf("y=%c%d%n", signY, absY);
		System.out.printf("z=%c%d%n", signZ, absZ);
		
	}

}
x=+10
y=-5
z= 0

 

자동 형 변환

서로 다른 타입 간의 대입이나 연산을 할 때, 형 변환으로 타입을 일치시키는 것이 원칙이다.

하지만, 경우에 따라 편의상의 이유로 형 변환을 생략할 수 있다.

그렇다고 해서 형 변환이 이루어지지 않는 것은 아니고, 컴파일러가 생략된 형 변환을 자동적으로 추가한다.

float f = 1234 // 형변환의 생략. float f = (float)1234;와 같음.

 

그러나 변수가 저장할 수 있는 값의 범위보다 더 큰 값을 저장하려는 경우에 형변환을 생략하면 에러가 발생한다.

byte b = 1000; //에러. byte의 범위(-128~127)를 넘는 값을 저장.

 

 

그러나 명시적 형변환을 해 주었을 경우는 에러가 안 난다.

char ch = (char)1000;

 

또한 연산과정에서도 형 변환이 자동적으로 이루어진다.

 

자동형 변환의 규칙

기존의 값을 최대한 보존할 수 있는 타입으로 자동 형변환한다.
1 byte 2 byte 4 byte 8 byte 4 byte 8 byte
byte short int long float double
    char      

 

char와 short은 둘 다 2 byte의 크기로 크기가 같지만, 범위가 달라서 둘 중 어느 쪽으로 바꿔도 손실이 발생할 수 있으므로 형 변환이 수행될 수 없다.

1. boolean을 제외한 나머지 7개의 기본형은 서로 형변환이 가능하다.
2. 기본형과 참조형은 서로 형변환할 수 없다.
3. 서로 다른 타입의 변수간의 연산은 형변환을 하는 것이 원칙이지만,
   값의 범위가 작은 타입에서 큰 타입으로의 형변환은 생략할 수 있다.

연습문제는 코드 초보 스터디(http://cafe.naver.com/javachobostudy.cafe)에서 PDF 파일로 제공

 

정수형 - byte, short, int, long

정수형에는 모두 4개의 자료형이 있으며, 각 자료형이 저장할 수 있는 값의 범위가 서로 다르다.

byte(자료형) < short < int < long
1(메모리)   2   4   8

기본 자료형(default data type)은 int이다.

 

정수형의 표현 형식과 범위

타입(type) 저장 가능한 범위 크기
bit            byte
byte -128~127(-2⁷~2⁷-1) 8 1
short -32,768~32,767(-2¹⁵~2¹⁵-1) 16 2
int -2,147,483,648~2,147,483,647(-2³¹~2³¹-1. 약 +-20억) 32 4
long -9,223,372,036,854,775,808~9,223,372,036,854,775,807(-2⁶³~2⁶³-1) 64 8

정수형은 연산을 할 때 4byte보다 작은 자료형의 값을 계산할 때는 4byte로 변환하기 때문에 int형으로 저장하는 경우가 많다.

주의할 점은 부호가 있는 정수의 경우 최솟값에서 -1을 하면 최댓값이 되고 최댓값에서 1을 더하면 최솟값이 된다.

 

실수형 - float, double

타입 저장 가능한 값의 범위(양수) 정밀도 크기
float 1.4X10⁻⁴⁵~3.4X10³⁸ 7자리 32 4
double 4.9X10⁻³¹⁴~1.8X10³⁰⁸ 15자리 64 8

이것은 양의 범위만을 적이며 -를 붙이면 음의 범위가 된다. 

 float의 경우 0에서 경우 0에서 +-1.4X10⁻⁴⁵까지 double의 경우 0에서 +-4.9X10⁻³¹⁴까지 값을 표현할 수 없다.

 

실수형에서 최댓값을 넘어선다면 값이 무한대가 되고, 최솟값 이하가 되면 0이 된다.

 

실수의 저장 형식은 세 부분으로 나뉘어서 저장되는데, 부호(Sign), 지수(Exponent), 가수(Mantissa), 모두 세 부분으로 이루어져 있다.

float : 1 + 8 + 23 = 32 (4 byte)
S(1) E (8) M (23)
double : 1 + 11 + 52 = 64 (8 byte)
S(1) E (8) M (23)

이와 같은 표현 형식은 IEEE 754(Institute of Electrical and Electronics Engineers)라는 표준을 따른 것이다.

기호 의미 설명
S 부호(Sign bit) 0이면 양수, 1이면 음수
E 지수(Exponent) 부호가 있는 정수, 지수의 범위는
-127~128(float),-1023~1024(double)
M 가수(Mantissa) 실제값을 저장하는 부분,
10진수로 7자리(float), 15자리 (double)의 정밀도로 저장 가능

부호 (Sign bit)

S는 부호 비트를 의미하며 1 bit이다.

 

지수(Exponent)

E는 지수를 저장하는 부분으로 float의 경우, 8bit의 저장 공강을 갖는다.

-127과 128은 숫자 아님(NaN Not a Number)과 양의 무한대(POSITIVE_INFINITY), 음의 무한대(NEGATIVE-INFINITY)와 같이 특별한 값의 표현을 위해 있으므로 실재 사용한 지수의 범위는 -126~127이다.

 

가수(Mantissa)

'M'은 실제 값인 가수를 저장하는 부분이다.

 

부동소수점에는 오차가 존재한다. 무한소수 같은 경우도 물론이고 계산할 때도 오차가 조금씩 발생한다.

'JAVA 02강 변수(Variable) > 기본형' 카테고리의 다른 글

기본형(primitive type)  (0) 2021.07.11

논리형 - boolean

boolean power = true;

boolean checkes = False; //에러 대소문자가 구분됨 true 또는 false만 가능

boolean은 true와 false 중 하나를 저장할 수 있으며 기본값(default)은 false이다.

논리 구현에 주로 사용된다.

 

문자형 - char

문자형 char역시 한 가지 자료형밖에 없다.

char ch = 'A'; //문자 'A'를 char타입의 변수 ch에 저장

위의 문장은 변수에 '문자'가 저장되는 것 같지만 실재로는 문자의 유니코드 65가 저장되는 것이다.

'A' = 65

'a' = 97

'0' = 48

 

배열의 자료형과 기본값

자료형 기본값
boolean false
char '\u0000'
byte, short, int 0
long 0L
float 0.0f
double 0.0d 또는 0.0
참조형변수 null

 

 

 

인코딩과 디코딩(encoding & decoding)

인코딩은 'A'를 유니코드 65로 변환해서 저장하는 것을 말하고 65를 다시 'A'로 변환하는 것을 디코딩이라고 한다.

암호화를 인코딩, 해석을 디코딩이라고 보면 된다. 만약 웹브라우저의 인코딩 설정이 웹페이지의 인코딩과 다른 경우 글자가 알아볼 수 없게 깨져서 나온다.

https://www.convertstring.com/ko/EncodeDecode/Base64Decode

 

Base64로 디코딩 - 온라인 Base64로 디코더

당신의 Base64로 여기에 텍스트를 디코딩 복사 파일로 디코딩 Base64로 다운로드 :

www.convertstring.com

 

아스키(ASCII)

ASCII는 'American Standard Code for Information Interchange'의 약어로 정보교환을 위한 미국의 표준 코드란 뜻이다.

아스키코드는 255가지이므로 한글을 표현하기에는 부족해서 한글을 표시하기 위해서는 확장 아스키(Extended ASCII)를 사용한다 한글 윈도에서 작성된 문서는 기본적으로 'CP949(확장 완성형)'로 인코딩 되어 저장된다.

2의 보수법은 해당 숫자 양수에 해당하는 2진수와 음수에 해당하는 2진수를 더하면 크기가 초과돼서 사라지고 나머지는 0이 되는 수이다. 

# 2진수 부호있는10진수
1 000 0
2 001 1
3 010 2
4 011 3
5 100 -4
6 101 -3
7 110 -2
8 111 -1

보면 양수1과 음수 -1의 2진수로의 표현은 각각 001과 111인데 이것을 더하면

(1) 000이 되고 (1)은 자릿수를 초과하는 값으로써 버려진다.

좀 더 간단하게 쓰면 2의 보수는 양수의 0인 자리에 1을 넣고 1인 자리에 0을 넣은 값에서 +1하면된다.

 

3을 2진수로 011이라는 사실만 알 때 

-3은 100+001=101이란 사실을 알 수 있다.

 

반대로 -2가 2진수로 110이라는 사실을 알 때

양수 -2는 001+001=010이라는 사실을 알 수 있다.

'JAVA 02강 변수(Variable) > 진법' 카테고리의 다른 글

실수의 진법변환  (0) 2021.07.11
정수의 진법 변환  (0) 2021.07.11
8진법과 16진법(octal base hexadecimal)  (0) 2021.07.11
비트(bit)와 바이트(byte)  (0) 2021.07.11
10진법과 2진법(decimal, binary)  (0) 2021.07.11

2진수를 10진수로 변환하는 방법

각 자릿수에 0.5ⁿ을 곱하고 더해준다.

 

0.101(2진수)의 경우

0./1/0/1

0.5X1+0.5 ²X0+0.5 ³X1 = 0.5+0+0.125

0.625(10진수)

 

10진수를 2진수로 변환하는 방법

0.5 0.625 나머지
0.5 0.125 1
0.5 0.125 0
    1
    0.101

0.625(10진수)는 0.101(2진수)이다.

 

 

10진수를 n진수로 나누려면 해당 진수로 나누고 나머지 값을 앞에 적는 것을 더 이상 나눌 수 없을 때까지 반복한 다음 마지막 몫과 나머지를 아래부터 위로 순서대로 적으면 된다.

 

 

2 46 나머지
2 23 0
2 11 1
2 5 1
  2 1
  1 0

46(10진수) > 101110(2진수)

이런식으로 변환이 가능하다.

 

 

8진수는 2진수 3자리를. 16진수는 2진수 4자리를 각각 한자리로 표현할 수 있기 때문에 자릿수가 짧아져서 알아보기 쉬워지고 서로 간의 변환 방법 또한 매우 간단하다.

 

2진수를 25를 8진수로 바꾸려면 2진수를 3자리 단위로 나눈 뒤 그 3자리마다의 2진수값을 구해서 적으면 된다.

01101 > 001/101 > 1/5 > 15

 

001은 2진수로 2²X0+2X0+1X1 = 1

101은 2진수로 2²X1+2X0+1X1 = 5

16진수의 경우 2진수를 4자리 단위로 나눈 뒤 그 4자리마다 2 진수 값을 구해서 적으면 된다.

'JAVA 02강 변수(Variable) > 진법' 카테고리의 다른 글

음수의 2진 표현 - 2의 보수법  (0) 2021.07.11
실수의 진법변환  (0) 2021.07.11
정수의 진법 변환  (0) 2021.07.11
비트(bit)와 바이트(byte)  (0) 2021.07.11
10진법과 2진법(decimal, binary)  (0) 2021.07.11

+ Recent posts