Java

[Java] char에서 int로 변수 타입 변경

oneH 2024. 8. 26. 20:39

 

 

 

 

1. 자동 형변환을 이용한 타입 변경

 

  자동 형변환을 이용한 char->int 변경이다.

public class hello {
    public static void main(String[] args) {
        char c = '2';
        int number = c; // int number = (int) c
        System.out.print(c);
    }
}

 

2

출력결과

 

 

 

 

2. 아스키코드를 이용한 타입 변경

 

public class hello {
    public static void main(String[] args) {
        char c = '2';
        System.out.print(c-'0');
    }
}

 

  숫자 0~9는 아스키코드에서 48~57 사이이다. 따라서 '숫자' - '0' = 숫자이다.

 

 

 

 

3. Character.getNumericValue() method

  

  Character 객체의 메서드를 사용하는 방법이다.

 

public class hello {
    public static void main(String[] args) {
        char c = '2';
        int number = Character.getNumericValue(c);
        System.out.print(number);
    }
}