홈 › 초급 › 01 / 8

변수, 데이터 타입, 형변환

섹션 7진행 0 / 8

6. 연습 문제

문제 1

다음 데이터를 저장할 변수를 적절한 타입으로 선언하고 출력하세요: 상품 코드 "P-1001", 재고 수량 250, 무게 1.75(kg), 품절 여부 false, 전 세계 누적 판매량 5,200,000,000.

정답 보기
java
public class Exercise1 {
    public static void main(String[] args) {
        String productCode = "P-1001";
        int stock = 250;
        double weightKg = 1.75;
        boolean soldOut = false;
        long globalSales = 5_200_000_000L;   // 21억 초과 → long, L 접미사 필수

        System.out.println(productCode + " 재고=" + stock + " 무게=" + weightKg
                + "kg 품절=" + soldOut + " 누적판매=" + globalSales);
        // 출력: P-1001 재고=250 무게=1.75kg 품절=false 누적판매=5200000000
    }
}

문제 2

시험 응시자 83명 중 합격자 61명의 합격률을 소수점 둘째 자리까지 퍼센트로 출력하세요. (힌트: Math.round를 이용한 반올림, 또는 String.format("%.2f", ...))

정답 보기
java
public class Exercise2 {
    public static void main(String[] args) {
        int passed = 61, applicants = 83;

        double rate = (double) passed / applicants * 100;   // 캐스팅을 먼저!
        double rounded = Math.round(rate * 100) / 100.0;    // 소수 둘째 자리 반올림

        System.out.println("합격률: " + rounded + "%");
        System.out.println(String.format("합격률: %.2f%%", rate));
        // 출력: 합격률: 73.49%
        // 출력: 합격률: 73.49%
    }
}

문제 3

int 변수 a = 2_000_000_000, b = 2_000_000_000이 있습니다. a + b를 (1) int로 계산했을 때, (2) long으로 올바르게 계산했을 때, (3) Math.addExact를 썼을 때 각각 어떻게 되는지 코드로 확인하세요.

정답 보기
java
public class Exercise3 {
    public static void main(String[] args) {
        int a = 2_000_000_000, b = 2_000_000_000;

        int wrong = a + b;
        System.out.println("(1) int: " + wrong);
        // 출력: (1) int: -294967296

        long right = (long) a + b;   // 하나를 long으로 승격시키면 전체가 long 연산
        System.out.println("(2) long: " + right);
        // 출력: (2) long: 4000000000

        try {
            Math.addExact(a, b);
        } catch (ArithmeticException e) {
            System.out.println("(3) " + e.getMessage());
        }
        // 출력: (3) integer overflow
    }
}