1. 아래의 Accumulator를 완성하시오.
for (int i = 0; i <= 10; i++)
Accumulator.add(i); // 전달되는 값을 모두 누적
Accumulator.showResult(); // 최종 누적 결과를 출력 sum = 55
output
public class Accumulator {
private int sum;
public void add(int num) {
sum += num;
}
public void showResult() {
System.out.println("sum = " + sum);
}
}
public class Main {
public static void main(String[] args) {
Accumulator accumulator = new Accumulator();
for (int i = 0; i <= 10; i++) {
accumulator.add(i);
}
accumulator.showResult();
}
}
- 위 코드를 실행하면 sum = 55라는 결과가 출력됩니다. 이는 Accumulator 클래스의 add() 메서드를 통해 전달된 값들이 모두 누적되어 최종 결과인 55가 출력되기 때문입니다.
2. 아래의 결과를 예측하고, 이유를 설명하시오.
String str1 = "Simple String";
String str2 = "Simple String";
String str3 = new String("Simple String");
String str4 = new String("Simple String");
if(str1 == str2)
System.out.println("str1과 str2는 동일 인스턴스 참조");
else
System.out.println("str1과 str2는 다른 인스턴스 참조");
if(str3 == str4)
System.out.println("str3과 str4는 동일 인스턴스 참조");
else
System.out.println("str3과 str4는 다른 인스턴스 참조");
다음과 같은 결과가 출력됩니다.
str1과 str2는 동일 인스턴스 참조
str3과 str4는 다른 인스턴스 참조
이유
str1과 str2는 모두 리터럴인 "Simple String"을 가리키는 문자열입니다. Java에서는 문자열 리터럴은 Method Area의 String 풀(string pool)에 저장되며, 동일한 문자열 리터럴을 사용하는 경우 같은 인스턴스를 참조하게 됩니다. 따라서 str1 == str2는 true가 됩니다.
str3과 str4는 new String("Simple String")를 통해 새로운 String 인스턴스를 생성한 것입니다. new 연산자를 사용하면 각각 별도의 인스턴스를 생성하므로, str3 == str4는 false가 됩니다.