Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

Java Test 2차 오답노트(김병우) 본문

Java/기타

Java Test 2차 오답노트(김병우)

빌드이너프 2024. 3. 16. 22:19

02. Given the code fragment:

public static void main(String[] args) {
	String myStr = "Hello world ";
	myStr.trim();
	int i1 = myStr.lastIndexOf(" ");
	System.out.println(i1);
}

What is the result?

A) An exception is thrown at runtime.

B) -1

C) 5

D) 11

답: D

풀이:

lastIndexOf: 특정 문자나 문자열이 뒤에서부터 처음 발견되는 인덱스를 반환하며 찾지 못했을 경우 -1을 반환함

trim()을 사용했더라도 i1에 저장해준 것이 아니기 때문에 myStr은 바뀌지 않음

따라서 lastIndexOf()를 사용했을 때 공백(" ")은 11번째 있음

public class Test {
    public static void main(String[] args) {
        String myStr = "Hello world ";
        myStr.trim();
        int i1 = myStr.lastIndexOf(" ");
        System.out.println(i1);
    }
}
11

03. Given:

class Vehicle {
    String type = "4W";
    int maxSpeed = 100;
    public Vehicle(String type, int maxSpeed) {
        this.type = type;
        this.maxSpeed = maxSpeed;
	}
    public Vehicle() {
    }
}

class Car extends Vehicle {
    String trans;
    public Car(String trans) { // line n1
        this.trans = trans;
	}

	public Car(String type, int maxSpeed, String trans) { // line n2
		super(type, maxSpeed);
		this.trans = trans;
	}
}

And given the code fragment:

Car c1 = new Car("Auto");
Car c2 = new Car("4W", 150, "Manual");
System.out.println(c1.type + " " + c1.maxSpeed + " " + c1.trans);
System.out.println(c2.type + " " + c2.maxSpeed + " " + c2.trans);

What is the result?

A) null 0 Auto

     4W 150 Manual

B) 4W 100 Auto

     4W 150 Manual

C) Compilation fails only at line n1.

D) Compilation fails only at line n2.

E) Compilation fails at both line n1 and line n2.

답: B

풀이: 

new Car("Auto")는 type가 Vehicle의 type인 "4W", maxSpeed는 Vehicle의 maxSpeed인 100, trans는 Car의 Car(String trans) 때문에 "Auto"가 됨, 따라서 c1.type는 "4W", c1.maxSpeed는 100, c1.trans는 "Auto"가 된다

new Car(String type, int maxSpeed, String trans)는 type, maxSpped, trans가 입력해준 "4W", 150, "Manual"들이 각각 매개변수로 입력되어 c2.type는 "4W", c2.maxSpeed는 150, c1.trans는 "Manual"이 된다

public class Test {
    public static void main(String[] args) {
        Car c1 = new Car("Auto");
        Car c2 = new Car("4W", 150, "Manual");
        System.out.println(c1.type + " " + c1.maxSpeed + " " + c1.trans);
        System.out.println(c2.type + " " + c2.maxSpeed + " " + c2.trans);
    }
}
4W 100 Auto
4W 150 Manual
public class Vehicle {
    String type = "4W";
    int maxSpeed = 100;
    public Vehicle(String type, int maxSpeed) {
        this.type = type;
        this.maxSpeed = maxSpeed;
    }
    public Vehicle() {
    }
}

class Car extends Vehicle {
    String trans;
    public Car(String trans) { // line n1
        this.trans = trans;
    }
    public Car(String type, int maxSpeed, String trans) { // line n2
        super(type, maxSpeed);
        this.trans = trans;
    }
}

12. Given the code fragment:

public static void main(String[] args) {
	Predicate<Integer> p = n -> n % 2 == 1;
	// insert code here
}

Which code snippet at line 9 prints true?

A) Boolean result = p.apply(101);

     System.out.println(result);

B) Boolean result = p.test(101);

     System.out.println(result);

C) Integer result = p.test(101);

     System.out.println(result == 1);

D) System.out.println(p.test(100));

답: B

풀이:

람다 식에서 나머지(%) 연산이 "== 1" 이어야 함

모든 홀수는 true를 인쇄하므로 홀수로 메서드를 호출하고 변수에 할당

import java.util.function.Predicate;

public class Test {
    public static void main(String[] args) {
        Predicate<Integer> p = n -> n % 2 == 1;
        Boolean result = p.test(101);
        System.out.println(result);
    }
}
true

13. Given the code fragment:

public static void main(String[] args) {
    int i = 20;
    int j = 10;
    int k = (i += j) / 5;
    System.out.println(i + " : " + j + " : " + k);
}

What is the result?

A) 22 : 10 : 22

B) 20 : 10 : 6

C) 30 : 10 : 6

D) 20 : 30 : 6

답: C

풀이: 

i += j 이 부분에서 i가 20->30으로 변하는 것을 잘 봐야함

j는 처음 초기화 해준 값 그대로 10

k는 30/5=6

따라서 30 : 10 : 6이 나옴

public class Test {
    public static void main(String[] args) {
        int i = 20;
        int j = 10;
        int k = (i += j) / 5;
        System.out.println(i + " : " + j + " : " + k);
    }
}
30 : 10 : 6

14. Examine:

class E1 extends RuntimeException { }
class E2 extends Exception { }
public class App {
	public void m1() {
		System.out.println("m1.Accessed.");
		throw new E1();
	}

	public void m2() {
	    System.out.println("m2.Accessed.");
    	throw new E2();
	}
    
    public static void main(String[] args) {
	    int level = 5;
    	App obj = new App();
	    if (level >= 3 && level <= 5) {
    		obj.m1();
	    } else {
    		obj.m2();
	    }
	}
}

Which statement is true?

A) The program fails to compile due to the unhandled E1 exception. (처리되지 않은 E1 예외로 인해 프로그램이 컴파일되지 못함)

B) The program fails to compile due to the unhandled E2 exception. (처리되지 않은 E2 예외로 인해 프로그램이 컴파일되지 못함)

C) The program prints m1.Accessed. (프로그램이 m1.Accessed를 출력)

D) The program prints m2.Accessed. (프로그램이 m2.Accessed를 출력)

답: B

풀이:

예외의 경우 생성자에서 E2을 발생시킨다고 선언해야함

RuntimeException의 경우에는 그럴 필요가 없음

class E1 extends RuntimeException { }
class E2 extends Exception { }
public class Test {
    public void m1() {
        System.out.println("m1.Accessed.");
        throw new E1();
    }

    public void m2() throws E2 { // E2를 throws 해줌
        System.out.println("m2.Accessed.");
        throw new E2();
    }

    public static void main(String[] args) {
        int level = 5;
        Test obj = new Test();
        if (level >= 3 && level <= 5) {
            obj.m1();
        } else {
            obj.m2();
        }
    }
}

18. Which three statements describe the object-oriented features of the Java language? (Choose three.)

(자바 언어의 객체 지향적 특징을 설명하는 3개의 문장은 무엇입니까? (3개를 선택하십시오.))

A) Objects cannot be reused. (Objects는 재사용할 수 없습니다.)

B) A subclass must override the methods from a superclass. (하위 클래스는 상위 클래스의 메서드를 재정의해야 합니다)

C) Objects can share behaviors with other objects. (Objects는 다른 객체와 동작을 공유할 수 있습니다)

D) A package must contain a main class. (패키지에는 main 클래스가 포함되어야 합니다)

E) Object is the root class of all other objects. (Objects는 다른 모든 객체의 root(최고 상위) 클래스입니다)

F) A main method must be declared in every class. (main()은 모든 클래스에서 선언해야 합니다)

답: B, C ,E

풀이:

A: Objects 클래스는 최고 상위 클래스로 다른 클래스를 생성했을 때 생략되어서 안보일 뿐이지 항상 재사용되고 있기 때문에 오답

B: 하위 클래스 기준에서 상위 클래스가 추상 클래스이거나 인터페이스가 아닌 경우 메서드를 재정의할지 선택할 수 있는데 포괄적으로 보면 답이긴함

C: 다형성을 의미, Objects는 최고 상위 클래스로 다른 객체와 공유할 수 있다

D: 빈 패키지를 생성할 수 있으므로 main 클래스가 포함되지 않아도 됨

E: Objects는 모든 객체의 상위 클래스가 맞다

F: 빈 클래스를 생성할 수 있기 때문에 아님


21. Given the code fragments:

public class Student {
	String name;
	int age;
}

and:

public class Test { // 1
	public static void main(String[] args) { // 2
        Student s1 = new Student(); // 3
        Student s2 = new Student(); // 4
        Student s3 = new Student(); // 5
        s1 = s3; // 6
        s3 = s2; // 7
        s2 = null; // 8
	} // 9
} // 10

Which statement is true?

A) After line 8, three objects are eligible for garbage collection. (8라인 이후에는 3개의 객체가 GC의 대상이 됩니다)

B) After line 8, two objects are eligible for garbage collection. (8라인 이후에는 2개의 객체가 GC의 대상이 됩니다)

C) After line 8, one object is eligible for garbage collection. (8라인 이후에는 1개의 객체가 GC의 대상이 됩니다)

D) After line 9, none of the objects are eligible for garbage collection. (9라인 이후에는 0개의 객체가 GC의 대상이 됩니다)

답: C

풀이:

8 라인 이후에 s1을 아무것도 참조하지 않기 때문에 s1은 GC의 대상이 됨

8 라인 이후에 s2가 null이고 따라서 s3도 null을 갖게 됨, 따라서 null 값을 참조하고 있기 때문에 GC의 대상이 아님

즉, 8 라인 후 s1만 참조하지 않기 때문에 s1 객체만 GC의 대상이 됨, 1개만 GC의 대상이 됨


24. Given:

public class App {
    int foo;
    static int bar;
    static void process() {
        foo += 10;
        bar += 10;
    }
    
    public static void main(String[] args) {
        App firstObj = new App();
        App.process();
        System.out.println(firstObj.bar);
        
        App secondObj = new App();
        App.process();
        System.out.println(secondObj.bar);
    }
}

What is the result?

A) 10

     10

B) 10

     20

C) 20

     20

D) Compilation fails.

답: D

풀이:

static이 아닌 변수 foo는 static 컨텍스트에서 참조할 수 없다

즉 foo를 static으로 만들어 주면 컴파일 오류가 안남

여기서는 아니기 때문에 컴파일 오류 남 => D가 답

public class Test {
    static int foo;
    static int bar;
    static void process() {
        foo += 10;
        bar += 10;
    }

    public static void main(String[] args) {
        Test firstObj = new Test();
        Test.process();
        System.out.println(firstObj.bar);

        Test secondObj = new Test();
        Test.process();
        System.out.println(secondObj.bar);
    }
}
10
20

25. Which three are advantages of Java exception mechanism? (Choose three.)

(Java 예외 메커니즘의 장점은 무엇입니까? (3개를 선택))

A) Improves the program structure because the error handling code is separated from the normal program function.

(오류 처리 코드가 정상 프로그램 기능과 분리되어 있어 프로그램 구조를 개선)

B) Provides a set of standard exceptions that covers all possible errors.

(발생 가능한 모든 오류를 포괄하는 일련의 표준 예외를 제공)

C) Improves the program structure because the programmer can choose where to handle exceptions.

(프로그래머가 예외를 처리할 위치를 선택할 수 있기 때문에 프로그램 구조를 개선)

D) Improves the program structure because exceptions must be handled in the method in which they occurred.

(예외가 발생한 방식으로 처리해야 하므로 프로그램 구조를 개선함)

E) Allows the creation of new exceptions that are customized to the particular program being created.

(생성 중인 특정 프로그램에 사용자 정의된 새 예외를 생성할 수 있다)

답: A, C, E

풀이:

B: standard exceptions은 모든 오류를 다룰 수 없다

D: 일부 예외는 적절한 방식을 통해 방지할 수 있지만 일부는 우리가 제어할 수 없다

동일한 메서드에서 예외를 잡아서 이 예외를 처리하고 복구를 시도하거나, catch해서 다시 throw하거나, 처리 부분을 이 메서드 호출자에게 맡길 수 있음

예외를 처리하지 않으면 최종적으로 JVM에 예외가 발생하고 프로그램 실행이 중단됨

오류 처리 코드는 일반 프로그램 기능과 분리되어 프로그램 구조를 개선

 

Throwable에는 Exception과 Error가 있음

Exception과 모든 하위 항목은 일반적으로 복구 가능하므로 이를 처리하고 복구를 시도할 수 있음

RuntimeException을 제외한 Exception과 모든 하위 클래스를  검사된 Exception 라고 함(Java에서는 확인된 예외를 처리해야 함)

RuntimeException 및 그 하위 클래스를 확인되지 않은 Exception 또는 Runtime Exception 라고 함

Runtime Exception 또는 확인되지 않은 Exception 처리는 선택 사항(Java에서는 이를 의무화하지 않음)


28. Given the code fragment:

Person.java:

public class Person {
    String name;
    int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
    	return name;
    }
    
    public int getAge() {
    	return age;
    }
}

 

Test.java:

public class Test {
    public static void checkAge(List<Person> list, Predicate<Person> predicate) {
	    for (Person p : list) {
		    if (predicate.test(p)) {
			    System.out.println(p.name + " ");
		    }
	    }
    }

    public static void main(String[] args) {
        List<Person> list = Arrays.asList(
            new Person("Rick", 34),
            new Person("Smith", 28),
            new Person("Tom", 30));
        // line n1
    }
}

Which code fragment, when inserted at line n1, enables the code to print Rick?

(어떤 코드를 n1에 삽입했을 때 Rick을 출력함?)

A) checkAge(list, () -> p.getAge() > 30);

B) checkAge(list, Person p -> p.getAge() > 30);

C) checkAge(list, p -> p.getAge() > 30);

D) checkAge(list, (Person p) -> { p.getAge() > 30; });

답: C

풀이:

A: 컴파일 오류(p를 확인할 수 없음)

B: 컴파일 오류(',' 또는 ')' 예상됨)

D: 컴파일 오류(statement가 아님)

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

 

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Test {
    public static void checkAge(List<Person> list, Predicate<Person> predicate) {
        for (Person p : list) {
            if (predicate.test(p)) {
                System.out.println(p.name + " ");
            }
        }
    }

    public static void main(String[] args) {
        List<Person> list = Arrays.asList(
                new Person("Rick", 34),
                new Person("Smith", 28),
                new Person("Tom", 30));
        checkAge(list, p -> p.getAge() > 30);
    }
}
Rick

29. You are asked to create a method that accepts an array of integers and returns the highest value from array.

Given the code fragment:

(정수의 배열을 받아들이고 배열에서 가장 높은 값을 반환하는 방법을 만들어야 함)

public class Test {
    public static void main(String[] args) {
        int[] numbers = { 12, 13, 42, 32, 15, 128, 56, 38, 16 };
        int[] keys = findMax(numbers);
    }
    
    /* line n1 */ {
        int[] keys = new int[3];
        /* code goes here */
        return keys;
	}
}

Which method signature do you use at line n1?

A) public int findMax(int[] numbers)

B) static int[] findMax(int[] max)

C) static int findMax(int[] numbers)

D) final int findMax(int[])

답: B

풀이:

난 답으로 A를 선택했음 근데 return 값이 int 배열 이어야 하기 때문에 반환 값이 int가 아닌 int[]이어야 함

public class Test {
    public static void main(String[] args) {
        int[] numbers = { 12, 13, 42, 32, 15, 128, 56, 38, 16 };
        int[] keys = findMax(numbers);
    }

    static int[] findMax(int[] max) {
        int[] keys = new int[3];
        /* code goes here */
        return keys;
    }
}

35. Given the code fragment:

String[] arr = { "What", "Are", "You", "Doing" };
List<String> list = new ArrayList<>(Arrays.asList(arr));
if (list.removeIf(s -> { System.out.print(s); return s.length() <= 2; })) {
	System.out.print(" removed");
}

What is the result?

A) Compilation fails. (컴파일 실패)

B) The program compiles, but it prints nothing. (프로그램이 컴파일되지만 아무것도 출력되지 않습니다)

C) WhatAreYouDoing

D) WhatAreYouDoing removed

E) An UnsupportedOperationException is thrown at runtime. (UnsupportedOperationException 이 런타임에 throw됨)

답: C

풀이: 

arr안의 arr[0], arr[1], arr[2], arr[3]은 모두 문자의 수가 3이상이다, 즉 2보다 같거나 같은 arr의 값은 존재하지 않음What, Are, You, Doing은 모두 3이상System.out.print(s)가 실행되므로 WhatAreYouDoing이 출력됨

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        String[] arr = { "What", "Are", "You", "Doing" };
        List<String> list = new ArrayList<>(Arrays.asList(arr));
        if (list.removeIf(s -> { System.out.print(s); return s.length() <= 2; })) {
            System.out.print(" removed");
        }
    }
}
WhatAreYouDoing

38. Given the code fragment:

6 	public static void main(String[] args) {
7 		List<String> list = Arrays.asList("A", "B", "C", "D");
8 		Iterator<String> it = list.iterator();
9 		while (it.hasNext()) {
10 			String s = it.next();
11 			if (s == "C") {
12 				break;
13 			}
14 			else {
15 				continue;
16 				System.out.print(s);
17 			}
18 		}
19 	}

Which action enabled it to print AB? (AB를 출력할 수 있었던 작업은 무엇입니까?)

A) Comment line 14 to 17.

B) Comment line 16.

C) Comment line 15.

D) Comment line 12.

답: C

풀이:

일단 위의 코드를 실행할 경우 오류가 발생하는데, 15번째 줄 continue를 주석처리하면 AB를 출력할 수 있게 해준다

continue가 있으면 s를 출력하는 statement를 찾을 수가 없기 때문에 AB를 출력할 수 있는 주요 줄은 15번째 줄이 된다

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("A", "B", "C", "D");
        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            String s = it.next();
            if (s == "C") {
                break;
            }
            else {
//                continue;
                System.out.print(s);
            }
        }
    }
}
AB

42. Given the code fragment:

public static void main(String[] args) {
    int ans;
    try {
        int num = 20;
        int div = 0;
    ans = num / div;
    } catch (ArithmeticException e) {
    	ans = 0; // line n1
    } catch (Exception e) {
    	System.out.println("Invalid calculation");
    }
    System.out.println("Answer = " + ans); // line n2
}

What is the result?

A) Answer = 0

B) Invalid calculation

C) Compilation fails at only line n1.

D) Compilation fails at only line n2.

E) Compilation fails at line n1 and line n2.

답: D

풀이:

ans가 초기화되지 않았다

즉, catch 블록 안에서 ans가 0으로 초기화 되었는데 지역변수라 catch 블록을 빠져나가면 ans는 초기화되지 않은 상태가 되고 

line n2에서 ans를 출력하면 아직 초기화 되지 않았기 때문에 컴파일 에러가 발생함

public class Test {
    public static void main(String[] args) {
        int ans = 0;
        try {
            int num = 20;
            int div = 0;
            ans = num / div;
        } catch (ArithmeticException e) {
            ans = 0; // line n1
        } catch (Exception e) {
            System.out.println("Invalid calculation");
        }
        System.out.println("Answer = " + ans); // line n2
    }
}
Answer = 0

43. Given:

public class MyClass {
	public static void main(String[] args) {
        String s = "Java SE 8 1";
        int len = s.trim().length();
        System.out.println(len);
	}
}

What is the result?

A) Compilation fails.

B) 11

C) 8

D) 9

E) 10

답: B

풀이:

난 10을 답으로 했는데 문자열을 그냥 잘 못 센거 같음

다시 세니까 s가 11임

trim()해도 문자열 안의 공백은 지워지지 않음

public class Test {
    public static void main(String[] args) {
        String s = "Java SE 8 1";
        int len = s.trim().length();
        System.out.println(len);
    }
}
11

46. Given the code fragment:

String[] strs = new String[2];
int idx = 0;
for (String s : strs) {
	strs[idx].concat(" element " + idx);
	idx++;
}
for (idx = 0; idx < strs.length; idx++) {
	System.out.println(strs[idx]);
}

What is the result?

A) element 0

     element 1

B) null element 0

     null element 1

C) null

     null

D) A NullPointerException is thrown at runtime.

답: D

풀이:

null을 포함하는 객체에 대해 concat()가 호출되기 때문에 JVM은 null 포인터 예외를 발생시킴

print() 메소드는 JVM이 예외를 발생시키지 않고 null을 출력함

strs[0]이 null임


47. Given the code fragment:

int[] a = { 1, 2, 3, 4, 5 };
for (XXX) {
	System.out.print(a[e]);
}

Which option can replace XXX to enable the code to print 135?

(코드가 135를 인쇄할 수 있도록 XXX를 대체할 수 있는 옵션은 무엇입니까?)

A) int e = 0; e <= 4; e++

B) int e = 0; e < 5; e += 2

C) int e = 1; e <= 5; e += 1

D) int e = 1; e < 5; e += 2

답: B

풀이:

답은 B, C라는데 아무리 생각해도 B가 답임

만약 for문에서 e가 0부터 시작하고 +=2로 2씩 증가해야 135를 출력할 수 있다
C로 하면 애초에 5이하이기 때문에 a 배열 수보다 많아서 에러 발생함

public class Test {
    public static void main(String[] args) {
        int[] a = { 1, 2, 3, 4, 5 };
        for (int e = 0; e < 5; e += 2) {
            System.out.print(a[e]);
        }
    }
}
135

48. Given this segment of code:

ArrayList<Cycle> myList = new ArrayList<>();
myList.add(new MotorCycle());

Which two statements, if either is true, would make the code compile? (Choose two.)

A) MotorCycle is an interface that implements the Cycle class. (MotorCycle은 Cycle 클래스를 구현하는 인터페이스입니다)

B) Cycle is an interface that is implemented by MotorCycle class. (Cycle은 MotorCycle 클래스에 의해 구현되는 인터페이스입니다)

C) Cycle is an abstract superclass of MotorCycle. (Cycle은 MotorCycle의 추상적인 슈퍼 클래스입니다)

D) Cycle and MotorCycle both extend the Transportation superclass. (Cycle과 MotorCycle은 모두 Transportation 슈퍼클래스를 확장합니다)

E) Cycle and MotorCycle both implement the Transportation interface. (Cycle과 MotorCycle 모두 Transportation 인터페이스를 구현합니다)

F) MotorCycle is a superclass of Cycle. (MotorCycle은 Cycle의 슈퍼 클래스입니다)

답: B, C

풀이: 

난 A, B를 답으로 했는데 생각해보니

A: 인터페이스는 클래스를 구현할 수가 없음, 그래서 답이 아님

B : Cycle은 인터페이스가 될 수 있고,  변수는 인터페이스가 될 수 있으며 MotorCycle은 Cycle을 구현 Cycle의 하위 항목

C: Cycle은 Motorcycle의 슈퍼클래스가 가능함

D, E: 동일한 클래스를 확장하거나 구현하는 경우 서로의 부모와 자식이 아닌 경우 잘못된 것

F: 자식 클래스(MotorCycle)가 부모 클래스(Cycle)의 슈퍼 클래스는 말이 안됨


50. Which statement is true about the main() method?

A) It is invoked by JRE. (JRE에 의해 호출됩니다)

B) It is a final method. (final 메서드이다)

C) It returns true if it is executed successfully at run time. (실행 시 성공적으로 실행되면 true를 반환)

D) It must be defined within a public class. (public 클래스 내에서 정의해야 함)

답: A

B: main()메서드는 public static void main()이기 때문에 static임

C: void라서 반환 값이 없음

D: 정의는 public 아니라도 되지만 실행은 public이 아니면 실행 안될거임

'Java > 기타' 카테고리의 다른 글

Java Test 1차 풀이  (0) 2024.03.10
자바테스트 문제  (0) 2024.03.03
Eclipse 자동완성  (0) 2023.05.14
Eclipse 단축키  (0) 2023.05.14