형변환(Type Casting)

형변환이란 한 데이터 타입의 값을 다른 데이터 타입으로 변환하는 과정이다.

목차

  1. 기본타입 허용 범위 크기
  2. 자동형변환(묵시적형변환)
  3. 자동형변환 예외
  4. 자동형변환 예시
  5. 강제형변환(명시적형변환)
  6. 강제형변환 예시

1. 기본타입 허용 범위 크기

  • byte < short < int < long < float < double

2. 자동형변환(묵시적형변환)

작은 데이터 타입에서 큰 데이터 타입으로의 변환이 발생할 때
Java가 자동으로 처리하는 것을 자동형변환이라고하고 데이터 손실이 없다.

큰 허용 범위타입 = 작은 허용 범위타입
byte b = 10
int num = b;

예시) byte -> int

  • byte가 더해지는 과정에서 int로 자동형변환

byte b1 = 10;
byte b2 = 10;
int result = b1 + b2;
System.out.println(result); // 20

예시) int -> long

  • int가 더해지는 과정에서 long으로 자동형변환
    int i1 = 10;
    int i2 = 10;
    long result = i1 + i2;
    System.out.println(result); // 20

예시) long -> float, double


long l1 = 5000000000L;
float f1 = l1;
double d1 = l1;

System.out.println(f1); // 5.0E9
System.out.println(d1); // 5.0E9

예시) float -> double


float f1 = 1.5F;
double d1 = 1.52;
double doubleResult1 = f1 + d1;
System.out.println(doubleResult1); // 3.02

3. 자동형변환 예외(byte->char)

  • byte에서 char로 자동형변환을 시도하면 각각 허용범위가 다르기 때문에 Type mismatch 에러가 나온다.

  • byte : -128 ~ 127 / char : 0 ~ 65533


byte b1 = 10;
byte b2 = 10;
char result = b1 + b2; 
// Type mismatch: cannot convert from int to char

4. 자동형변환 예시


char charValue = '가';
int intValue = charValue;
System.out.println(intValue); // 유니코드로 출력 44032


int intValue1 = 11;
long longValue1 = intValue1;
System.out.println(longValue1); // 11


long longValue2 = 100;
float floatValue2 = longValue2;
System.out.println(floatValue2); // 100.0

float floatValue3 = 100.5F;
double doubleValue3 = floatValue3;
System.out.println(doubleValue3); // 100.5


float f2 = 2.2f;
float f3 = 2.2f;
double doubleResult2 = f2 + f3;

System.out.println(doubleResult2); // 4.400000095367432

5. 강제형변환(명시적 형변환)

큰 데이터 타입에서 작은 데이터 타입으로 변환할 때는 명시적으로 형변환을 해야한다.
이 경우 데이터 손실이 발생할 수 있다.

  • 작은 허용범위 타입 = (작은 허용범위 타입) 큰허용범위타입

5-1. int타입은 byte타입보다 더 큰 허용범위를 가지고 있어 명시적형변환이 필요하다.


int intValue = 10;
byte byteValue = (byte) intValue;
System.out.println(byteValue); // 10

5-2. 정수값으로 char타입에서 문자를 출력하기 위해 변환한다.


int intValue1 = 65;
char charValue1 = (char) intValue1;
System.out.println(charValue1);

5-3. 실수(float, double)은 정수타입(byte, short, int, long)으로 자동형변환 되지 않는다.

소수점 부분은 버려지고 정수부분만 저장된다.


double doubleValue2 = 3.14;
int intValue2 = (int) doubleValue2;
System.out.println(intValue2);

6. 강제형변환 예시

int intValue = 44032;
char charValue = (char) intValue;
System.out.println(charValue); // 가


long longValue = 500;
intValue = (int) longValue;
System.out.println(intValue); // 500


double doubleValue = 3.14;
intValue = (int) doubleValue;
System.out.println(intValue); // 3
반응형

#변수의 타입

자바 변수의 타입에는 기본형(Primitive Type), 참조형(Reference Type)이 있다.

기본형은 정수타입, 실수타입, 논리타입으로 분류된다.

 

 

기본형에는 총 8개의 타입이 있다.

- 정수타입 : byte, char, short, int, long

- 실수타입 : float, double

- 논리타입 : boolean

 

참조형에는 총 4개가 있다.

- 배열(Array)

- 열거형(Enum)

- 클래스(Class)

- 인터페이스(Interface)

 

 

 

정수(Integer)란?

정수란 소수나 분수가 없는 수의 집합으로, 양의 정수(자연수), 음의 정수, 0이 있다.

정수는 수학에서 가장 기본적인 수의 개념 중 하나로, 우리가 일상에서 숫자를 셀 때 사용하는 양의 정수(예: 1, 2, 3...)와 온도 등에서 사용하는 음의 정수(예: -1, -2, -3...)로 나뉜다.

 

 

byte 타입

- 메모리 사용 크기 : 1byte(8bit)

- 저장값 범위 :  -27 ~ (27 - 1) / -128 ~ 127

- 저장값 범위 계산 방법 :  -2(n-1) ~ 2(n-1)-1, n은 비트

 

 

byte 타입 실습 예제

 

line 12 주석을 해제하면 변수의 범위를 넘어갔기 때문에 Type missmatch 오류가 발생한다.

 

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
31
32
package j241002;
 
public class J101_PrimitiveType_Byte {
 
    public static void main(String[] args) {
        
        byte by1 = -128;
        byte by2 = -100;
        byte by3 = 0;
        byte by4 = 100;
        byte by5 = 127;
        //byte var6 = 128;
        
        System.out.println(by1);
        System.out.println(by2);
        System.out.println(by3);
        System.out.println(by4);
        System.out.println(by5);
        //System.out.println(by6);
        
        /*
          
          Description    Resource    Path    Location    Type
         Type mismatch: cannot convert from int to byte    ---.java    /---/---/--- line 12    Java Problem
          
         */
        
 
    }
 
}
 
cs

 

 

 

 

 

char 타입

- 메모리 사용 크기 : 2byte(16bit)

- 저장값 범위 : 0 ~ 216 - 1 / 0 ~ 65535

 

 

 

 

char 타입 예제

 

char는 '( Singe Qoutation Mark, 홑따옴표)를 사용하여 문자를 저장하고 n진수로 변환된 값도 저장가능하다.

Character는 사전적인 의미로 문자, 기호를 뜻하는데 왜 정수타입인가 이상함을 느낄 수 있다.

 

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
package j241002;
 
public class J101_PrimitiveType_Char {
 
    public static void main(String[] args) {
        
            
        char c11 = 'A'// 문자
        char c22 = 65// 10진수
        char c33 = '\u0041'// 16진수
        char c44 = '가';
        char c55 = 44032;
        char c66 = '\uac00';
        
        System.out.println(c11);
        System.out.println(c22);
        System.out.println(c33);
        System.out.println(c44);
        System.out.println(c55);
        System.out.println(c66);
                
        
    }
}
 
 
cs

 

 

문자(character) 컴퓨터 내부에서는 숫자(정수)로 인코딩되어 처리되기 때문이라고 볼 수 있다.

작은 따옴표로 감싼 형태를 문자 리터럴이라고 하고 유니코드로 변환되어 저장이 된다.

각 문자, 기호에 대응되는 고유한 정수값이 있기때문에 문자도 숫자처럼 저장되고 연산될 수 있다. 

예를 들어 'A' + 1을 수행하면 66이 되어 문자 'B'로 변환된다.

※ 유니코드에 대해서는 추후 작성.

 

 

 

 

int 타입

- 메모리 사용 크기 : 4byte(32bit)

- 저장값 범위 :  -231 ~ (231 - 1) / -2,147,483,648 ~ 2,147,483,647(약20억)

- 저장값 범위 계산 

 

210 = 1024 ≒ 103

 

231

= 210 x 210 x 210 x 2

= 1024 x 1024 x 1024 x 2

≒ 2 x 109

 

 

 

int 타입 예제

10진수 뿐만 아니라 2, 8, 16진수 저장도 가능하다.

개발자에 의해 직접 입력된 값을 리터럴(literal)이라고 하며 리터럴 중 정수로 인식되는 경우는 다음과 같다.


- 2진수(Binary) : Ob, 0B로 시작 / 0과 1로 구성 
- 8진수(Octal) : 0부터 시작, 0~7로 구성
- 10진수(Decimal) : 0~9 로 구성 
- 16진수(Hexadecimal) : 0x, 0X로 시작 0~9로 구성되며 그 이상부터는  A(10),B(11),C(12),D(13),E(14),F(15) 

※ 16진수는 웹에 색상(ex. #000000), 메모리주소(ex. 0x7fff) 등에 사용

※ 진법 변환에 관해서는 추후 작성.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package j241002;
 
public class J101_PrimitiveType_Int {
 
    public static void main(String[] args) {
        
        int var1 = 0b1001// 2진수
        int var2 = 0206// 8진수
        int var3 = 111// 10진수
        int var4 = 0xAF// 16진수
        
        System.out.println("2진수 : " + var1);
        System.out.println("8진수 : " + var2);
        System.out.println("10진수 : " + var3);
        System.out.println("16진수 : " + var4);
                
    }
 
}
 
cs
 

 

\

long 타입

- 메모리 사용 크기 : 8byte(64bit)

- 저장값 범위 :  -263 ~ (263 - 1) / -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807

 

 

 

long 타입 예제

int의 범위를 초과할 경우 long을 사용

정수 리터럴 뒤 l, L을 추가(대문자 권장)

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package j241002;
 
public class J101_PrimitiveType_Long {
 
    public static void main(String[] args) {
        
        //long var1 = 12345678912;
        long var2 = 12345678912L;
        
        //System.out.println(var1);
        System.out.println(var2);
        
            
 
    }
 
}
 
cs

 

 

 

 

 

float 타입

- 메모리 사용 크기 : 4byte(32bit)

- 저장값 범위 :  (1.4 x 10^-45) ~ (3.4 x 10^38)

- 정밀도 : 소수점 이하 약 7자리(6~9)

 

 

double 타입

- 메모리 사용 크기 : 8byte(64bit)

- 저장값 범위 :  (4.9 x 10^-324) ~ (1.8 x 10^308)

- 정밀도 : 소수점 이하 약 15자리(15~18)

※ float 보다 약 2배정도 정밀도가 높아서 double

 

float, double 정밀도 예제

 

 

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
package j241002;
 
public class J101_RealNumber_FloatDouble {
 
    public static void main(String[] args) {
 
 
        // 실수값 저장 
        //float var1 = 3.14; // type mismatch
        float var2 = 3.14f;
        double var3 = 3.14// float 보다 약 2배정도 정밀도가 높아서 double 
        
        // 정밀도 테스트 
        float var4 = 0.1234567890123456789f;
        double var5 = 0.1234567890123456789;
        
        
        //System.out.println(var1);
        System.out.println(var2);
        System.out.println(var3);
        System.out.println(var4);
        System.out.println(var5);
        
        
 
    }
 
}
 
cs

 

 

boolean 타입

- True, False를 저장하는 논리형 변수

- 참, 거짓에 따라 조건문, 제어문의 흐름을 변경한다.

- 불리언, 불린 등으로 불린다

 

 

boolean 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package j241002;
 
public class J101_PrimitiveType_Boolean {
 
    public static void main(String[] args) {
        
        boolean flag = false;
        boolean isRun = true;
        
        System.out.println(flag);
        System.out.println(isRun);
        
    }
 
}
 
cs
반응형

'JAVA' 카테고리의 다른 글

[JAVA][09] Scanner 클래스  (0) 2024.11.17
[JAVA][07] 형변환(Type Casting)  (0) 2024.10.22
[JAVA][05] 변수값 바꾸기1  (0) 2024.10.09
[JAVA][04] 변수(Variable)란?  (1) 2024.10.03
[JAVA][03] Hello World  (0) 2024.10.03

int x = 1, int y = 2 일때 두 변수의 값 교체하기

 

1. tmp 변수를 선언 후 x 값 저장

2. x에 y값 저장 

3. y에 tmp에 저장되어 있는 x값 저장

 

 

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
package j240930;
 
public class J101_4_VariableReplacement {
 
    public static void main(String[] args) {
        
        /*
         
        변수 x, y의 값을 서로 교체하여 출력하기
        
        */
        
        int x = 1;
        int y = 2;
        
        System.out.println(x+", "+y); // 1, 2
        
        int tmp = x;
        x = y;
        y = tmp;
        
        System.out.println(x+", "+y); // 2, 1
        
 
    }
 
}
 
cs
반응형

'JAVA' 카테고리의 다른 글

[JAVA][07] 형변환(Type Casting)  (0) 2024.10.22
[JAVA][06] 변수 기본 타입(Primitive Type)  (0) 2024.10.12
[JAVA][04] 변수(Variable)란?  (1) 2024.10.03
[JAVA][03] Hello World  (0) 2024.10.03
[JAVA][02] 이클립스 Perspective 설정  (0) 2024.10.03

+ Recent posts