Java

[Java] Java의 정석(기초편) 연습문제 풀이Chapter03

ab0utcom 2026. 1. 8. 03:13

3-1

다음 중 형변환을 생략할 수 있는 것은?(모두)

byte b = 10;
char ch = 'A';
int i = 100;
long l = 1000L;

① b = (byte)i;

② ch = (char)b;

③ short s = (short)ch;

④ float f = (float)l;

⑤ i = (int)ch;

 

Ans) 4,5

1: 큰 타입인 int에서 작은 타입인 byte로 형변환은 명시적 형변환 필요

2: signed에서 unsigned로 변환이므로 캐스팅 필요

3: 같은 4비트이지만 성질이 다름. 캐스팅 필요

4: float가 더 큰 자료형이므로 명시적 형변환 필요 X

5: int가 더 큰 자료형이므로 명시적 형변환 필요 X


3-2

다음 연산의 결과를 적으시오

public class Exercise3_2 {
	public static void main(String[] args) {
	    int x = 2;
	    int y = 5;
	    char c = 'A';
	    
	    System.out.println(1 + x << 33);
	    System.out.println(y >= 5 || x < 0 && x > 2);
	    System.out.println(y += 10 - x++);
	    System.out.println(x += 2);
	    System.out.println(!('A' <= c && c <= 'Z'));
	    System.out.println('C' - 'c');
	    System.out.println('5' - '0');
	    System.out.println(c + 1);
	    System.out.println(++c);
	    System.out.println(c++);
	    System.out.println(c);
	}
}

 

Ans)

6

true

13

5

false

-32

5

66

B

B

C

 

Sol)

1: Java에서 int의 shift연산은 하위 5개 비트만 유효하다. 즉 33번 shift는 32%32 = 1번 shift와 같다.

... 0011 = 3 에서 왼쪽으로 shift 1번 일어나면

... 0110 = 6 이 된다.

2: &&가 ||보다 먼저 계산된다.

3: x++을 해도 당장은 기존의 x인 2로 계산된다. y = y + (10 - x)이다. 그리고 앞으로 x는 1 증가한다.

4: 증가된 x=3에서 +=2를 하면 5

5: 'A' <= 'A' <= 'Z' → true이고, !true = false다

6: 'C' = 67, 'c' = 99이므로 산술 연산하면 -32

7: 둘의 유니코드가 어떻든 5차이남을 알 수 있다.

8: c = 'A' = 65에서 산술연산 +1을 하여 66

9: ++은 산술 연산을 안한다. 따라서 'A'에서 유니코드값 1 증가한 'B'

10: 출력하고 증가하므로 출력값은 'B'

11: 전 줄에서 증가했으므로 'C'


3-3

public class Main {
	public static void main(String[] args) {
	    int num = 456;
	    System.out.println(num -= num%100);
	}
}

 


3-4

public class Exercise3_4
{
	public static void main(String[] args) {
		int numOfApples = 123;
		int sizeOfBucket = 10;
		int numOfBucket = (numOfApples / sizeOfBucket) + 1;
		
		System.out.println("필요한 바구니의 수 :"+numOfBucket);
	}
}

 

사과 전체 개수를 바구니 개수로 나눈 몫 + 1일 것이다.


3-5

public class Exercise3_5
{
	public static void main(String[] args) {
		int num = 0;
		System.out.println(num>=0 ? (num > 0 ? "양수" : 0) : "음수");
	}
}

3-6

public class Main
{
	public static void main(String[] args) {
		int fahrenheit = 100;
		float celcius = (int)(((5f/9) * (fahrenheit - 32))*100 + 0.5) / 100f ;
		
		System.out.println("Fahrenheit:"+fahrenheit);
		System.out.println("celcius:"+celcius);
		
	}
}

 

섭씨로 변환한 이후에, 100을 곱하고 0.5를 더한 후, 소수점을 버리고 다시 100으로 나누면 소수 둘째자리로 반올림할 수 있다.