Back-End/Java

[ JAVA ] String to int, long, short, byte 형 변환

oahee 2023. 7. 14. 14:42

에러 메시지는 다음과 같다.

Type mismatch: cannot convert from String to byte

>> 변수와 data의 형이 맞지 않아 발생한 오류이다.

      따라서 변수의 자료형을 바꿔주거나, data의 형을 변환해야 한다.

      아래는 data의 형변환 예제이다.

public class Ex10_2 {

	public static void main(String[] args) {
		String n="10";
		
		int i = Integer.parseInt(n);	// String to int
		long l = Long.parseLong(n);	// String to long
		short s = Short.parseShort(n);	// String to short
		byte b = Byte.parseByte(n);	// String to byte
		
	} //main

} //class

 

 

반대로 String으로 형변환 하고자 한다면 방법은 아래와 같다.

public class Ex15_02 {

	public static void main(String[] args) {
		
		int i = 10;
        
        // 방법1
		String si = i + "";
		
		// 방법2
		String st = String.valueOf(i);
		
		// 방법3
		String sr = Integer.toString(i); 
		
        
		// "1010" - 2진수
		System.out.println( Integer.toBinaryString(i) );
		System.out.println( Integer.toString(i, 2) );
        
		// "12" - 8진수
		System.out.println( Integer.toOctalString(i) );
		System.out.println( Integer.toString(i, 8) );
        
		// "a" - 16진수
		System.out.println( Integer.toHexString(i) );
		System.out.println( Integer.toString(i, 16) );
		
		
	} //main

} //class