Paradox Simulation

728x90
반응형

이번엔 자바에서 Integer 기능을 알아보겠다.

 

우선적으로 int와 Integer의 차이점이 있다.

 

int

int 같은경우엔 자료형이라고 표현한다.

주요 특징으로는 산술연산 가능하며 null 초기화가 불가능하다.

따라서 0으로 초기화하는 방법을 이용하고있다.

 

ex) int temp = 0;

 

Integer

다음으로는 Wrapper 클래스의 객체로 사용되고있는 Integer 이다.

 

산술연산이 불가능하지만 null 초기화가 가능하다.

null 값 처리가 가능하여 나중에 SQL과 연동할 시 처리가 용이해진다.

 

Wrapper 클래스라서 특정 기본형 타입으로 나타내는데, Integer 같은경우엔 int형을 저장할 수 있다.

 

ex) Integer temp = new Integer(10);

 

Integer의 값을 int로 옮길 때 다음과 같이 사용한다.

 

Integer to int

Integer temp = new Integer(10);
int tempA = temp.intValue();

 

이와같이 Wrapper 클래스로 되어있는 객체들은 메서드를 통하여 변환을 한다.

 

 

다음은 java에서 형변환을 할때 자주쓰는 string to int, int to string에 대해서 서술하겠다.

 

우선적으로 Java에서 String to int방법은 다음과 같다.

 

String to int

String temp = "111";
int num = Integer.parseInt(temp);

 

예외 처리 없는 에러

만약 temp 값에 111같이 변환가능한 int 값이 아닌 "111a" 등 문자열이 포함되어있다면 다음과 같이 에러가 발생하게 된다.

 

public class testStringtoInt {
    public static void main(String[] args){
        String temp = "111a";
        int tempInt = Integer.parseInt(temp);
    }
}

 

 

Exception 처리에 대해선 보통은 try ~ catch ~ 문을 이용하게 된다.

 

try{
	// 실행할 기능들
} catch (NumberFormatException e) {
	// Exception 발생 시 처리할 내용
} finally {
	// try catch 이후 실행시키는 구문
}

예외 처리에 대해서는 다음과 같이 정리했다.

2023.01.31 - [프로그래밍/JAVA 프로그래밍] - Java - 예외처리, try / catch / finally

 

코드로 작성해보겠다.

public class testStringtoInt {
    public static void main(String[] args){
        try{
            String temp = "111a";
            int tempInt = Integer.parseInt(temp);
            System.out.println(tempInt);
        } catch (Exception e){
            System.out.println("에러발생");
        } finally {
            String temp = "1111";
            int tempInt = Integer.parseInt(temp);
            System.out.println(tempInt);
        }
    }
}

수많은 Integer 의 메서드들

Integer.toString(int)

public class IntegerMethod {
    public static void main(String[] args) {
        int temp = 123;
        String tempString = Integer.toString(temp);
    }
}

int to String

즉, int 값을 String 형으로 변환할때 사용된다.

 

Integer.toBinaryString(int)

public class IntegerMethod {
    public static void main(String[] args) {
        int temp = 11;
        String tempString = Integer.toBinaryString(temp);
        System.out.println("11의 2진수 값 : " + tempString);
    }
}

10진수로 표현되는 int 형을 String형으로 변환하며 그 숫자값을 2진수로 변환시키는 메서드이다.

 

 

Integer.toOctalString(int)

public class IntegerMethod {
    public static void main(String[] args) {
        int temp = 11;
        String tempString = Integer.toOctalString(temp);
        System.out.println("11의 8진수 값 : " + tempString);
    }
}

 

 

더 많은 메서드들이 있지만, 주로 쓰는 메서드들로 다뤄봤다.

728x90
반응형
250x250
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band