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 1차 풀이 본문

Java/기타

Java Test 1차 풀이

빌드이너프 2024. 3. 10. 13:51

01. Given the code fragment:

abstract class Planet { // 1
	protected void resolve() { // 2
	} // 3
	abstract void rotate(); // 4
} // 5
 // 6
	class Earth extends Planet { // 7
		private void resolve() { // 8
		} // 9
		private void rotate() { // 10
	} // 11
} // 12

Which two modifications enables the code to compile?

A) Make the method at line 8 protected.

B) Make the method at line 2 private.

C) Make the method at line 10 protected.

D) Make the method at line 4 public.

E) Make the method at line 2 public.

답: A, C

풀이:

메서드 오버라이딩 시 접근 제어자를 조상보다 좁은 범위로 변경할 수 없다

따라서 resolve()와 rotate()의 접근 제어자를 protected로 수정하면 compile시 문제가 없게 된다

abstract class Planet { // 1
	protected void resolve() { // 2
	} // 3
	abstract void rotate(); // 4
} // 5
 // 6
	class Earth extends Planet { // 7
		protected void resolve() { // 8
		} // 9
		protected void rotate() { // 10
	} // 11
} // 12

02. Given this segment of code:

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

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

A) MotorCycle is an interface that implements the Cycle class.

B) Cycle is an interface that is implemented by the MotorCycle class.

C) Cycle is an abstract superclass of MotorCycle.

D) Cycle and MotorCycle both extend the Transportation superclass.

E) Cycle and MotorCycle both implement the Transportation interface.

F) MotorCycle is a superclass of Cycle.

답: B, C

풀이:

만약 둘 중 하나가 사실이라면, 어떤 두 문장이 코드를 컴파일하게 만들까요?

B) Cycle은 MotorCycle 클래스에 의해 구현되는 인터페이스

C) Cycle은 MotorCycle의 추상적인 슈퍼 클래스


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

A) It is invoked by JRE

B) It is a final method.

C) It returns true if it is executed successfully at run time.

D) It must be defined within a public class.

답: A

풀이:

main() 메서드에 대해 맞는 설명은 무엇입니까?

public static void main(String[] args)

A): main()는 jre[Java 런타임 환경(JRE)]에 의해 실행되는 것이 맞음

B): main()는 final 메서드가 아니다

C): return 타입이 boolean이 아니기 때문에 오답

D): main() 메서드가 꼭 public 이어야 할 필요없다


04. Given the code fragments:

A.java:
package p1;
public class A {
}
B.java:
package p1.p2;
// line n1
public class B {
 public void doStuff() {
 A b = new A();
 }
}
C.java:
package p3;
// line n2
public class C {
 public static void main(String[] args) {
 A o1 = new A();
 B o2 = new B();
 }
}

Which modification enables the code to compile?

A) Replace line n1 with:

     import p1.*;

     Replace line n2 with:

     import p1.p2.*;

B) Replace line n1 with:

      import p1.A;

      Replace line n2 with:

      import p1.*;

C) Replace line n1 with:

      import p1.A;

      Replace line n2 with: import p1.A;

      import p1.p2.B;

D) Replace line n1 with:

      import p1;

      Replace line n2 with: import p1;

      import p1.p2;

답: B

풀이:

B.java에서 A 클래스를 호출하기 위해 import p1.A;를 해줘야 함

C.java에서 A와 B를 사용하기 위해 import p1.A; import p1.p2.B;를 해주거나 import p1.*를 해줘야 함


05. Given the code fragment:

int wd = 0;
String[] days = { "sun", "mon", "wed", "sat" };
for (String s : days) {
 switch (s) {
 case "sat":
 case "sun":
 wd -= 2;
 break;
 case "mon":
 wd++;
 case "wed":
 wd += 1;
 }
}
System.out.println(wd);

What is the result?

A) 3

B) 4

C) -1

D) Compilation fails.

답: C

풀이:

sum일 때 wd = 0 -> -2

mon일 때 wd = -2 -> -1 -> 0

wed일 때 wd = 0 -> 1

sat일 때 wd = 1 -> -1

최종적으로 나오는 값은 -1

break 문장을 확실하게 못보면 틀리는 문제

package practice;

public class Main {
	public static void main(String[] args) {
		int wd = 0;
		String[] days = { "sun", "mon", "wed", "sat" };
		for (String s : days) {
		 switch (s) {
		 case "sat":
		 case "sun":
		 wd -= 2;
		 break;
		 case "mon":
		 wd++;
		 case "wed":
		 wd += 1;
		 }
		}
		System.out.println(wd);
	}
}

06. Given the code fragment:

public static void main(String[] args) {
 Short s1 = 200;
 Integer s2 = 400;
 Long s3 = (long) s1 + s2;
 String s4 = (String) (s3 * s2); // line n1
 System.out.println("Sum is " + s4); // line n2
}

What is the result?

A) Sum is 600

B) Compilation fails at line n1.

C) Compilation fails at line n2.

D) A ClassCastException is thrown at line n1.

E) A ClassCastException is thrown at line n2.

답: B

풀이: long 타입에서 String 타입으로 캐스팅이 안되기 때문에 컴파일 에러 발생

굳이 String으로 바꾸고 싶다면 ""을 더하여 문자열을 만들면 됨

package practice;

public class Main {
	public static void main(String[] args) {
		 Short s1 = 200;
		 Integer s2 = 400;
		 Long s3 = (long) s1 + s2;
		 String s4 = (s3 * s2) + ""; // line n1
		 System.out.println("Sum is " + s4); // line n2
	}
}

 

 


07. Given this array:

int[] array = { 8, 16, 32, 64, 128 };

Which two fragments, independently, print each element in this array? (Choose two.)

A)

for (int i : array) {
 System.out.print(array[i] + " ");
}

B)

for (int i : array) {
 System.out.print(i + " ");
}

C)

for (int i = 0 : array) {
 System.out.print(array[i] + " ");
}

 

D)

for (int i = 0; i < array.length; i++) {
 System.out.print(i + " ");
}

E)

for (int i = 0; i < array.length; i++) {
 System.out.print(array[i] + " ");
}

F)

for (int i; i < array.length; i++) {
 System.out.print(array[i] + " ");
}

 

답: B, E

풀이:

A)는 ArrayIndexOutOfBoundsException 에러 발생, 향상된 for문은 array를 받은 i를 for문으로 돌려야 함

B) 정답

package practice;

public class Main {
	public static void main(String[] args) {
		int[] array = { 8, 16, 32, 64, 128 };
		
		for (int i : array) {
			 System.out.print(i + " ");
		}
	}
}

// 8 16 32 64 128

C)는 향상된 for문엔 i를 초기화하지 않아도됨 또한 A)와 마찬가지로 i를 for문으로 돌려야 함

D)는 i문이 출력되므로 0 1 2 3 4가 출력됨 E)처럼 array의 i번째 요소를 출력해야함

E) 정답

package practice;

public class Main {
	public static void main(String[] args) {
		int[] array = { 8, 16, 32, 64, 128 };
		
		for (int i = 0; i < array.length; i++) {
			 System.out.print(array[i] + " ");
			}
	}
}
// 8 16 32 64 128

F)는 i가 초기화되지 않은 상태로 돌아가서 에러 남


08. Given the code fragment:

public static void main(String[] args) {
 List<String> names = new ArrayList<>();
 names.add("Robb");
 names.add("Bran");
 names.add("Rick");
 names.add("Bran");
 if (names.remove("Bran")) {
 names.remove("Jon");
 }
 System.out.println(names);
}

What is the result?

A) [Robb, Rick, Bran]

B) [Robb, Rick]

C) [Robb, Bran, Rick, Bran]

D) An exception is thrown at runtime.

답: A

풀이:

[Robb]

[Robb, Bran]

[Robb, Bran, Rick]

[Robb, Bran, Rick, Bran]

[Robb, Rick, Bran]

if 문에서 names.remove("Bran")을 하면 true가 반환되고 Jon을 지우라는 것은 의미 없는 문장

따라서 A가 정답

package practice;

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

public class Main {
	public static void main(String[] args) {
		 List<String> names = new ArrayList<>();
		 names.add("Robb");
		 names.add("Bran");
		 names.add("Rick");
		 names.add("Bran");
		 
		 if (names.remove("Bran")) {
		 names.remove("Jon");
		 }
		 System.out.println(names);
	}
}
// [Robb, Rick, Bran]

09. Given:

class Book { int pages; }
public class App {
 int count;
 public void method(Book x, int k) {
 x.pages = 100;
 k = 200;
 }
 public static void main(String[] args) {
 App obj = new App();
 Book objBook = new Book();
 System.out.println(objBook.pages + ":" + obj.count);
 obj.method(objBook, obj.count);
 System.out.println(objBook.pages + ":" + obj.count);
 }
}

What is the result?

A) 0:0 100:0

B) null:0 100:0

C) 0:0 100:200

D) null:null 100:null

답: A

풀이: 

첫 println()문: objBook.pages은 아무것도 지정하지 않아 0으로 초기화된 상태, obj.count도 0으로 초기화 된 상태

-> 0:0 출력됨

두 번째 println()문: method()가 실행되면서 Book의 pages 변수가 100으로 변경, k는 this.k가 아니고 할 수도 없음 따라서 k는 obj.count을 통해 100을 입력받지만 method()의 지역변수 k만 200으로 변경시켜주고 obj.count에는 아무런 영향을 주지 못함

-> 100:0 출력됨

package practice;

class Book { 
	int pages;
}

public class Main {
	int count;
 	public void method(Book x, int k) {
 		x.pages = 100;
 		k = 200;
 	}

 	public static void main(String[] args) {
 		Main obj = new Main();
 		Book objBook = new Book();
	 
 		System.out.println(objBook.pages + ":" + obj.count);
 		obj.method(objBook, obj.count);
 		System.out.println(objBook.pages + ":" + obj.count);
	 }
}

0:0
100:0

 


10. Given the code fragment:

float var1 = (12_345.01 >= 121_35.00) ? 12_456 : 124_56.02f;
float var2 = var1 + 1024;
System.out.println(var2);

 

What is the result?
A) An exception is thrown at runtime.
B) Compilation fails.
C) 13480.0
D) 13480.02
답: C

풀이:

var1에서 12_345.01이 121_35.00보다 크기 때문에 12_456이 저장됨 -> 12456.0

var2에서 12456.0 + 1024 = 13480.0 이됨

package practice;

public class Main {
 	public static void main(String[] args) {
 		float var1 = (12_345.01 >= 121_35.00) ? 12_456 : 124_56.02f; // 12456.0
 		float var2 = var1 + 1024;
 		System.out.println(var1);
 		System.out.println(var2);
 	}
}
12456.0
13480.0

 

 


11. Which two statements are true about the Java byte code? (Choose two.)
A) It can be serialized across network. (네트워크 전반에 걸쳐 직렬화할 수 있습니다.)
B) It can run on any platform that has a Java compiler. (자바 컴파일러가 있는 모든 플랫폼에서 실행할 수 있습니다.)
C) It has “.java” extension. ("java" 확장자가 있습니다.)
D) It can run on any platform. (모든 플랫폼에서 실행할 수 있습니다.)
E) It can run on any platform that has Java Runtime Environment. (Java Runtime Environment가 있는 모든 플랫폼에서 실행할 수 있습니다.)

답: A, E

풀이: 

A) 솔직히 이해를 못하겠음(관련 링크)

E) JVM이 있으면 어떠한 OS에 관계없이 자바 바이트 코드를 해석하므로 모든 플랫폼에서 실행할 수 있다


12. Given:

Base.java:
class Base {
 public void test() {
 System.out.println("Base");
 }
}
DerivedA.java:
class DerivedA extends Base {
 public void test() {
 System.out.println("DerivedA");
 }
}
DerivedB.java:
public class DerivedB extends DerivedA {
 public void test() {
 System.out.println("DerivedB");
 }
 public static void main(String[] args) {
 Base b1 = new DerivedB();
 Base b2 = new DerivedA();
 Base b3 = new DerivedB();
 b1 = (Base) b3;
 Base b4 = (DerivedA) b3;
 b1.test();
 b4.test();
 }
}

 

What is the result?
A) Base
     DerivedA
B) Base
     DerivedB
C) DerivedB
     DerivedB
D) DerivedB
     DerivedA
E) A ClassCastException is thrown at runtime.

답: C

풀이:

DrivedB가 Base와 DrivedA를 상속받았고 맨 마지막으로 오버로딩 된 test() 메서드가 실행되기 때문에 test() 메서드 실행 시 DrivedB가 실행된다.

package practice;

	class Base {
	 public void test() {
	 System.out.println("Base");
	 }
	}

	class DerivedA extends Base {
	 public void test() {
	 System.out.println("DerivedA");
	 }
	}

	public class Main extends DerivedA {
	 public void test() {
		 System.out.println("DerivedB");
	 }
	 public static void main(String[] args) {
		 Base b1 = new Main();
		 Base b2 = new DerivedA();
		 Base b3 = new Main();
		 b1 = (Base) b3;
		 Base b4 = (DerivedA) b3;
		 b1.test();
		 b4.test();
	 }
	}

// DerivedB
// DerivedB

 


13. Given:

class Student {
 String name;
 public Student(String name) {
 this.name = name;
 }
}
public class Test {
 public static void main(String[] args) {
 Student[] students = new Student[3];
 students[1] = new Student("Richard");
 students[2] = new Student("Donald");
 for (Student s : students) {
 System.out.println("" + s.name);
 }
 }
}

What is the result?
A) null
     Richard
     Donald
B) Richard
     Donald
C) Compilation fails.
D) An ArrayIndexOutOfBoundsException is thrown at runtime.
E) A NullPointerException is thrown at runtime.

답: E

풀이:

Students 배열의 0번째 배열이 null 값이기 때문에 NullPointerException이 발생됨

0번 째 값 넣고 출력하면 됨

package practice;

class Student {
	String name;
	public Student(String name) {
		this.name = name;
	}
}
	public class Main {
		public static void main(String[] args) {
			Student[] students = new Student[3];
			students[0] = new Student("Kim");
			students[1] = new Student("Richard");
			students[2] = new Student("Donald");
			for (Student s : students) {
				System.out.println("" + s.name);
			}
		}
}
// Kim
// Richard
// Donald

 


14. Given the following main method:

int num = 5;
do {
 System.out.print(num-- + " ");
} while (num == 0);

What is the result?
A) 5 4 3 2 1
B) 4 2 1
C) 5
D) Nothing is printed

답: C

풀이: 

num--는 후행연산자라서 일단 5가 출력된다음 num이 4로 변함

그런데 while문에서 num은 4를 만나버리기 때문에 false로 문이 종료되게 되어

결국 do while문에서 do는 한 번은 꼭 실행되므로 5가 출력됨

package practice;

public class Main {
 	public static void main(String[] args) {
 		int num = 5;
 		do {
 		 System.out.print(num-- + " ");
 		} while (num == 0);
 	}
}
// 5

 


15. Given:

public class MyString {
 String s;
 public boolean equals(MyString str) {
 return this.s.equalsIgnoreCase(str.toString());
 }
 MyString(String s) {
 this.s = s;
 }
}

and the code fragment:

String s1 = "Moon";
MyString s2 = new MyString("Moon");
if ((s1 == "Moon") && (s2.equals("Moon"))) {
 System.out.print("A");
} else {
 System.out.print("B");
}
if (s1.equalsIgnoreCase(s2.s)) {
 System.out.print("C");
} else {
 System.out.print("D");
}

 

What is the result?
A) AC
B) BC
C) AD
D) BD

답: B

풀이: 

첫 if문에서 s1 == "Moon"은 true: String은 값을 공유해서 사용하기 때문에 같다고 나옴

s2.equals("Moon")은 false: s2는 해쉬 값이라서 equals를 쓰더라도 false가 나옴

따라서 else로 넘어가 B가 출력됨

 

s2.s는 Moon이고 equalsIgnoreCase는 대소문자 구분없이 비교함, s1 Moon과 s2.s Moon은 같기 때문에 true

따라서 두 번째 if문에서는 C가 출력됨

package practice;

public class Main {
	String s;
	public boolean equals(Main str) {
		return this.s.equalsIgnoreCase(str.toString());
	}
	Main(String s) {
		this.s = s;
	}
	
	public static void main(String[] args) {		
		String s1 = "Moon";
		Main s2 = new Main("Moon");
		if ((s1 == "Moon") && (s2.equals("Moon"))) {
			System.out.print("A");
		} else {
			System.out.print("B");
		}
		if (s1.equalsIgnoreCase(s2.s)) {
			System.out.print("C");
		} else {
			System.out.print("D");
		}
	}
}
// BC

 


16. Given the code fragment:

LocalDateTime dt = LocalDateTime.of(2024, 1, 19, 1, 1);
dt.plusDays(30);
dt.plusMonths(1);
System.out.println(dt.format(DateTimeFormatter.ISO_DATE_TIME));

What is the result?
A) An exception is thrown at runtime.
B) 2024-01-19T01:01:00
C) 2024-03-20T01:01:00
D) 2024-01-19

답: B

풀이:

plus, minus 메소드를 통해서 연산을 하더라도 객체 생성시 가지고 있는 값은 변하지 않기 때문에 처음 입력한 날 그대로 나오게 되고,

ISO_DATE_TIME 형식에 따라 2024-01-19T01:01:00이 출력됨

package practice;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
 	public static void main(String[] args) {
 		LocalDateTime dt = LocalDateTime.of(2024, 1, 19, 1, 1);
 		dt.plusDays(30);
 		dt.plusMonths(1);
 		System.out.println(dt.format(DateTimeFormatter.ISO_DATE_TIME));
 	}
}
// 2024-01-19T01:01:00

17. Given:

public class Test {
 public static void main(String[] args) {
 int x = 1;
 int y = 1;
 if (x++ < ++y) {
 System.out.print("Hello ");
 } else {
 System.out.print("Welcome ");
 }
 System.out.print("Log " + x + ":" + y);
 }
}

What is the result?
A) Hello Log 2:2
B) Welcome Log 1:2
C) Welcome Log 2:1
D) Hello Log 1:2

답: A

풀이: 

x++보다 ++y가 선행 연산자 이므로 y가 2가되어 true가 된다 따라서 Hello 가 출력됨

x와 y 모두 if문을 나가면 연산자에 의해 둘 다 2가 되어

최종적으로 Hello Log 2:2가 출력됨

package practice;

public class Main {
	public static void main(String[] args) {
		int x = 1;
		int y = 1;
		if (x++ < ++y) {
			System.out.print("Hello ");
		} else {
			System.out.print("Welcome ");
		}
		System.out.print("Log " + x + ":" + y);
	}
}
// Hello Log 2:2

18. Given

public class Test {
 public static void main(String[] args) {
 int numbers[];
 numbers = new int[2];
 numbers[0] = 10;
 numbers[1] = 10;
 numbers = new int[4];
 numbers[2] = 30;
 numbers[3] = 40;
 for (int x : numbers) {
 System.out.print(" " + x);
 }
 }
}

What is the result?
A) 10 20 30 40
B) 0 0 30 40
C) Compilation fails.
D) An exception is thrown at runtime.

답: B

풀이:

numbers

numbers의 길이는 2이고 밑에처럼 0에는 10, 1에는 10 저장됨

0 1
10 10

새롭게 numbers 배열을 생성하고 0과 1번째는 안지정했으므로 0으로 초기화

2에는 30, 3에는 40이 입력됨

따라서 numbers의 요소들을 하나씩 출력하는 향상된 for문을 지나면 0 0 30 40이 출력됨

0 1 2 3
0 0 30 40

 

package practice;

public class Main {
	public static void main(String[] args) {
		int numbers[];
		numbers = new int[2];
		numbers[0] = 10;
		numbers[1] = 10;
		numbers = new int[4];
		numbers[2] = 30;
		numbers[3] = 40;
		for (int x : numbers) {
			System.out.print(" " + x);
		}
	}
}
// 0 0 30 40

 


19. Given the code fragment:

public static void main(String[] args) {
 ArrayList myList = new ArrayList();
 String[] myArray;
 try {
 while (true) {
 myList.add("My string");
 }
 } catch (RuntimeException re) {
 System.out.println("Caught a RuntimeException");
 } catch (Exception e) {
 System.out.println("Caught an Exception");
 }
 System.out.println("Ready to use");
}

What is the result?
A) Execution terminates in the first catch statement, and Caught a RuntimeException is printed to the console.

(첫 번째 catch 문에서 실행이 종료되고 Catched a RuntimeException이 콘솔에 인쇄됩니다.)

B) Execution terminates in the second catch statement, and Caught an Exception is printed to the console.

(두 번째 Catch 문에서 실행이 종료되고 Catched an Exception이 콘솔에 인쇄됩니다.)
C) A runtime error is thrown in the thread “main”. (런타임 오류가 스레드 "main"에 던져집니다.)
D) Execution completes normally, and Ready to use is printed to the console.

(실행이 정상적으로 완료되고 Ready to use(사용 준비 완료)가 콘솔에 인쇄됩니다.)
E) The code fails to compile because a throws keyword is required. (throws 키워드가 필요하기 때문에 코드를 컴파일하지 못합니다.)

답: C

풀이: 정확히 왜 이렇게 되는지 모르겠음

package practice;

import java.util.ArrayList;

public class Main {
	public static void main(String[] args) {
		ArrayList myList = new ArrayList();
		String[] myArray;
		try {
			while (true) {
				myList.add("My string");
			}
		} catch (RuntimeException re) {
			System.out.println("Caught a RuntimeException");
		} catch (Exception e) {
			System.out.println("Caught an Exception");
		}
		System.out.println("Ready to use");
	}
}

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.base/java.util.Arrays.copyOf(Arrays.java:3512)
	at java.base/java.util.Arrays.copyOf(Arrays.java:3481)
	at java.base/java.util.ArrayList.grow(ArrayList.java:237)
	at java.base/java.util.ArrayList.grow(ArrayList.java:244)
	at java.base/java.util.ArrayList.add(ArrayList.java:454)
	at java.base/java.util.ArrayList.add(ArrayList.java:467)
	at OCAJP/practice.Main.main(Main.java:11)

20. Given the code fragment:

public static void main(String[] args) {
 String[] arr = { "Hello", "How", "Are", "You", "Doing" };
 List<String> list = new ArrayList<>(Arrays.asList(arr));
 if (list.removeIf((String s) -> (return s.length() <= 3;))) {
 System.out.println(s + "removed");
 }
}

What is the result?
A) Compilation fails.
B) How, Are, and You removed.
C) An UnsupportedOperationException is thrown at runtime.
D) The program compiles, but it prints nothing.

답: A

풀이:

Collection<String> 유형의 removeIf(Predicate<? super String>) 메서드는 인수에 적용할 수 없기 때문에 컴파일 에러가 발생함


21. Given:

class CD {
 int r;
 CD(int r) {
 this.r = r;
 }
}
class DVD extends CD {
 int c;
 DVD(int r, int c) {
 // line n1
 super(r);
 }
}

And given the code fragment:

DVD dvd = new DVD(10, 20);


Which code fragment should you use at line n1 to instantiate the dvd object successfully?
A) super.r = r;
     this.c = c;
B) super(r);
     this(c);
C) super(r);
     this.c = c;
D) this.c = r;
     super(c);

답: C 

풀이: 

this. 를 사용해서 c가 DVD의 지역변수인 c에 입력될 수 있어야 한다

안그러면 DVD 생성자에서 입력받은 20이 입력되지 않기 때문이다

package practice;

class CD {
	int r;
	CD(int r) {
		this.r = r;
	}
}
class DVD extends CD {
	int c;
	DVD(int r, int c) {
		super(r);
		this.c = c;
	}
}

public class Main {
	public static void main(String[] args) {
		DVD dvd = new DVD(10, 20);
	}
}

 


22. Given the code fragment:

abstract class Toy {
 int price;
 // line n1
}

Which three code fragments are valid at line n1?
A)

public static void insertToy() {
	/* code goes here */
 }


B)

final Toy getToy() {
	return new Toy();
}


C)

pubic void printToy();


D)

public int calculatePrice() {
	return price;
}


E)

public abstract void computeDiscount();

답: A, D, E

풀이:

B)는 final 이 붙어 있어서 에러남

C)는 몸통{} 부분이 없다


23. Given the definitions of the Bird class and the Peacock class:

public class Bird {
 public void fly() {
 System.out.print("Fly.");
 }
}
public class Peacock extends Bird {
 public void dance() {
 System.out.print("Dance.");
 }
}

and the code fragment:

/* insert code snippet here. */
p.fly();
p.dance();


Which code snippet can be inserted to print Fly.Dance.?
A)

Bird p = new Peacock();


B)

Bird b = new Bird();
Peacock p = (Peacock) b;


C)

Peacock b = new Peacock();
Bird p = (Bird) b;


D)

Bird b = new Peacock();
Peacock p = (Peacock) b;

답: D

풀이:

D)는 Peacock 생성자를 생성하고 Bird로 받아 Peacock의 dance()를 사용할 수 없었지만

두 번째 줄 (Peacock)로 다시 형변환을 하여 부모의 메소드인 fly()를 상속받고 dance() 또한 사용할 수 있기 때문에 D)가 정답

package practice;

public class Bird {
	public void fly() {
		System.out.print("Fly.");
	}
}
package practice;

public class Peacock extends Bird {
	public void dance() {
		System.out.print("Dance.");
	}
}
package practice;

public class Main {
	public static void main(String[] args) {
		Bird b = new Peacock();
		Peacock p = (Peacock) b;
		
		p.fly();
		p.dance();
	}
}
// Fly.Dance.

24. Given the code fragment:

public static void main(String[] args) {
 try {
 int num = 10;
 int div = 0;
 int 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 only at line n1.
D) Compilation fails only at line n2.
E) Compilation fails at line n1 and line n2.

답: E

해설:

ans변수는 지역 변수이기 때문에 로컬 변수를 만들어 주지 않아 에러가 line n1과 n2에서 발생함

package practice;

public class Main {
	public static void main(String[] args) {
		int ans = 0;
		try {
			int num = 10;
			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

 


25. Given this code for a Planet object:

package planets;
public class Planet {
 public String name;
 public int moons;

 public Planet(String name, int moons) {
 this.name = name;
 this.moons = moons;
 }
}

And this method:

public static void main(String[] args) {
 Planet[] planets = {
 new Planet("Mercury", 0),
 new Planet("Venus", 0),
 new Planet("Earth", 1),
 new Planet("Mars", 2),
 };
 System.out.println(planets);
 System.out.println(planets[2].name);
 System.out.println(planets[2].moons);
}

What is the output?
A) Planets
    Earth
    1
B) [Lplanets.Planet;@75b84c92
    Earth
    1
C) [Lplanets.Planet;@75b84c92
    planets.Planet@6bc7c054
    1
D) [Lplanets.Planet;@75b84c92
    planets.Planet@6bc7c054
    [Lplanets.Moon;@15db9742
E) [Lplanets.Planet;@75b84c92
    Venus
    0

답: B

해설:

0 1 2 3
Mercury 0 Venus 0 Earth 1 Mars 2

표 처럼 저장되어 있고

plants를 바로 출력하면 해당하는 해쉬 코드가 출력됨

plants[2]의 name을 출력하면 Earth가 나옴

plants[2]의 moons를 출력하면 1이 나옴

package practice;

public class Main {
	public static void main(String[] args) {
		Planet[] planets = {
				new Planet("Mercury", 0),
				new Planet("Venus", 0),
				new Planet("Earth", 1),
				new Planet("Mars", 2),
		};
		System.out.println(planets);
		System.out.println(planets[2].name);
		System.out.println(planets[2].moons);
		
		for(int i=0; i<planets.length; i++) {
			System.out.println(planets[0]);
		}
	}
}

class Planet {
	public String name;
	public int moons;
	
	public Planet(String name, int moons) {
		this.name = name;
		this.moons = moons;
	}
}

26. Given the code fragment:

public class Test {
 void readCard(int cardNo) throws Exception {
 System.out.println("Reading card");
 }
 void checkCard(int cardNo) throws RuntimeException { // line n1
 System.out.println("Checking card");
 }
 public static void main(String[] args) {
 Test ex = new Test();
 int cardNo = 12345;
 ex.readCard(cardNo); // line n2
 ex.checkCard(cardNo); // line n3
 }
}

What is the result?
A) Reading card
    Checking card
B) Compilation fails only at line n1.
C) Compilation fails only at line n2.
D) Compilation fails only at line n3.
E) Compilation fails at both line n2 and line n3.

답: C

해설:

Exception은 예측이 가능한 경우에 사용하고, RuntimeException은 발생할 수도 있고 발생하지 않을 수도 있는 경우에 사용

오류가 나는 n2부분에서 오류는 readCard의 오류 던지는 부분에서 Exception이 아닌 RuntimeException으로 바꿔주면 해결된다

package practice;

public class Main {
	void readCard(int cardNo) throws RuntimeException {
		System.out.println("Reading card");
	}
	void checkCard(int cardNo) throws RuntimeException { // line n1
		System.out.println("Checking card");
	}
	public static void main(String[] args) {
		Main ex = new Main();
		int cardNo = 12345;
		ex.readCard(cardNo); // line n2
		ex.checkCard(cardNo); // line n3
	}
}
Reading card
Checking card

 


27. Given the code fragment:

public static void main(String[] args) { // 3
int iVar = 100; // 4
float fVar = 100.100f; // 5
double dVar = 123; // 6
fVar = iVar; // 7
iVar = fVar; // 8
fVar = dVar; // 9
dVar = fVar; // 10
iVar = dVar; // 11
dVar = iVar; // 12
} // 13

Which three lines fail to compile? (Choose three.)
A) Line 7
B) Line 8
C) Line 9
D) Line 10
E) Line 11
F) Line 12

답: B, C, E

풀이:

B: float와 int는 같은 4byte라서 자동형변환이 되지 않는다

C: double이 float보다 더 크기 때문에 명시적 형변환을 해줘야 한다

E: double은 int보다 크기가 더 크고 실수형이기 때문에 명시적 형변환을 해줘야 한다

package practice;

public class Main {
	public static void main(String[] args) { // 3
		int iVar = 100; // 4
		float fVar = 100.100f; // 5
		double dVar = 123; // 6
		fVar = iVar; // 7
		iVar = (int)fVar; // 8
		fVar = (float)dVar; // 9
		dVar = fVar; // 10
		iVar = (int)dVar; // 11
		dVar = iVar; // 12
		} // 13
}

 


28. Given the code from the Greeting.java file:

public class Greeting {
 public static void main(String[] args) {
 System.out.println("Hello " + args[0]);
 }
}

Which set of commands prints Hello Duke in the console?
A) javac Greeting
java Greeting Duke
B) javac Greeting.java Duke
java Greeting
C) javac Greeting.java
java Greeting Duke
D) javac Greeting.java
java Greeting.class Duke

답: C

풀이:

프로그램을 컴파일하려면 java Greeting Duke : "Duke" 인수를 사용하여 프로그램을 실행해야 함


29. Given:

public class FieldInit {
 Character c;
 boolean b;
 float f;
 void printAll() {
 System.out.println("c = " + c);
 System.out.println("b = " + b);
 System.out.println("f = " + f);
 }
 public static void main(String[] args) {
 FieldInit f = new FieldInit();
 f.printAll();
 }
}

What is the result?
A) c = null
     b = true
     f = 0.0
B) c =
     b = false
     f = 0.0
C) c = null
     b = false
     f = 0.0
D) c = 0
     b = false
     f = 0.0f

답: C

풀이:

c는 Character 타입이기 때문에 null로 초기화

b는 booelan 타입이므로 fasle로 초기화

f는 float 타입이므로 0.0으로 초기화됨

실행을 하면 printAll()에서 c, b, f를 출력하기 때문에 null, false, 0.0의 결과가 나오게 됨

package practice;

public class Main {
	Character c;
	boolean b;
	float f;
	void printAll() {
		System.out.println("c = " + c);
		System.out.println("b = " + b);
		System.out.println("f = " + f);
	}
	public static void main(String[] args) {
		Main f = new Main();
		f.printAll();
	}
}
c = null
b = false
f = 0.0
null

 


30. Which three statements are true about exception handling? (Choose three.)

예외 처리에 대해 다음 세 가지 설명 중 맞는 것은 무엇입니까?

A) Only unchecked exceptions can be rethrown. (선택하지 않은 예외만 다시 던질 수 있습니다.)
B) All subclasses of the RuntimeException class are not recoverable. (RuntimeException 클래스의 모든 하위 클래스를 복구할 수 없습니다.)
C) The parameter in a catch block is of Throwable type. (캐치 블록의 매개 변수는 Throwable 유형입니다.)
D) All subclasses of the RuntimeException class must be caught or declared to be thrown. (RuntimeException 클래스의 모든 하위 클래스를 잡거나 던지도록 선언해야 합니다.)
E) All subclasses of the RuntimeException class are unchecked exception. (RuntimeException 클래스의 모든 하위 클래스는 선택되지 않은 예외입니다.)
F) All subclasses of the Error class are not recoverable. (오류 클래스의 모든 하위 클래스를 복구할 수 없습니다.)

답: C, E, F


31. Which three statements are true about the structure of a Java class? (Choose three.)

자바 클래스의 구조에 대해 다음 중 맞는 세 가지 진술은 무엇입니까?
A) A public class must have a main method. (public class에는 main 메서드가 있어야 합니다.)
B) A class can have only one private constructors. (클래스에는 private 구성자가 하나만 있을 수 있습니다.)
C) A method can have the same name as a field. (메서드는 필드와 동일한 이름을 가질 수 있습니다.)
D) A class can have overloaded static method. (클래스가 정적 메서드에 overloaded가 걸릴 수 있습니다.)
E) The methods are mandatory components of a class. (메서드는 클래스의 필수 구성 요소입니다.)
F) The field need not to be initialized before use. (필드를 사용하기 전에 초기화할 필요가 없습니다.)

답: C, D, F


32. Given the code fragment:

public static void main(String[] args) {
 ArrayList<Integer> points = new ArrayList<>();
 points.add(1);
 points.add(2);
 points.add(3);
 points.add(4);
 points.add(null);
 points.remove(1);
 points.remove(null);
 System.out.println(points);
}

What is the result?
A) A NullPointerException is thrown at runtime.
B) [1, 2, 4]
C) [1, 2, 4, null]
D) [1, 3, 4, null]
E) [1, 3, 4]
F) Compilation fails.

답: E

해설:

points.add(1); [1]
points.add(2); [1, 2]
points.add(3); [1, 2, 3]
points.add(4); [1, 2, 3, 4]
points.add(null); [1, 2, 3, 4, null]
points.remove(1); [1, 3, 4, null]
points.remove(null); [1, 3, 4]

package practice;

import java.util.ArrayList;

public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> points = new ArrayList<>();
		points.add(1);
		points.add(2);
		points.add(3);
		points.add(4);
		points.add(null);
		points.remove(1);
		points.remove(null);
		System.out.println(points);
	}
}
[1, 3, 4]

 

33. Given the code fragments:

public static void main(String[] args) {
 LocalDate date = LocalDate.of(2024, 1, 19);
 date.plusDays(10);
 System.out.println(date);
}

What is the result?
A) 2024-01-19
B) 2024-01-29
C) 2024-01-29 00:00
D) A DateTimeException is thrown at runtime.

답: A

풀이:

plus, minus 메소드를 통해서 연산을 하더라도 객체 생성시 가지고 있는 값은 변하지 않음

따라서 2024-01-19 출력됨

package practice;

import java.time.LocalDate;

public class Main {
	public static void main(String[] args) {
		LocalDate date = LocalDate.of(2024, 1, 19);
		date.plusDays(10);
		System.out.println(date);
	}
}
2024-01-19

 


34. Given:

class LogFileException extends Exception {}
class AccessViolationException extends RuntimeException {}
1 public class App {
2 public static void main(String[] args) throws LogFileException {
3 App obj = new App();
4 try {
5 obj.open();
6 obj.process();
7 // insert code heare
8 } catch (Exception e) {
9 System.out.println("Completed");
10 }
11 }
12 public void process() {
13 System.out.println("Processed");
14 throw new LogFileException();
15 }
16 public void open() {
17 System.out.println("Opened.");
18 throw new AccessViolationException();
19 }
20 }

Which action fixes the compiler error?
A) At line 16, add throws AccessViolationException
B) At line 12, add throws LogFileException
C) At line 2, replace throws LogFileException with throws AccessViolationException
D) At line 7, insert throw new LogFileException();

답: B

풀이: 

package practice;

class LogFileException extends Exception {}
class AccessViolationException extends RuntimeException {}

public class Main {
	public static void main(String[] args) throws LogFileException {
		Main obj = new Main();
		try {
			obj.open();
			obj.process();
			// insert code heare
		} catch (Exception e) {
			System.out.println("Completed");
		}
	}
	
	public void process() {
		System.out.println("Processed");
		throw new LogFileException();
	}
	public void open() {
		System.out.println("Opened.");
		throw new AccessViolationException();
	}
}
Opened.
Completed

 


35. Given:

public class TestScope {
 public static void main(String[] args) {
 int var1 = 200;
 System.out.print(doCalc(var1));
 System.out.print(" " + var1);
 }
 static int doCalc(int var1) {
 var1 = var1 * 2;
 return var1;
 }
}

What is the result?
A) 400 200
B) 200 200
C) 400 400
D) Compilation fails.

답: A

풀이: 

System.out.print(doCalc(var1)); 에서 doCalc의 var1의 출력 값은 doCalc()의 지역 변수이므로 main()의 var1의 값 200에 영향을 주지 않는다 그래서 처음 print문에서 doCalc의 200 * 2를 한 400이 출력되고,

두 번째 print문에서 main()의 var1의 값인 200이 출력된다


36. Given:

Acc.java:
package p1;
public class Acc {
 int p;
 private int q;
 protected int r;
 public int s;
}
Test.java:
package p2;
import p1.Acc;
public class Test extends Acc {
 public static void main(String[] args) {
 Acc obj = new Test();
 }
}

Which statement is true?
A) Both p and s are accessible via obj. (p와 s 모두 obj를 통해 액세스할 수 있습니다.)
B) Only s is accessible via obj. (obj를 통해서만 접근할 수 있습니다.)
C) Both r and s are accessible via obj. (r과 s 모두 obj를 통해 액세스할 수 있습니다.)
D) p, r, and s are accessible via obj. (p, r 및 s는 obj를 통해 액세스할 수 있습니다.)

답: B

풀이:

Object는 모든 클래스의 상위 클래스라서 모두 접근 가능함


37. Examine the content of App.java: (App.java의 내용을 검사)

package p1;
public class App {
 public static void main(String[] args) {
 System.out.println("Java");
 }
}

and of Test.java:

package p1.p2;
public class Test { }

Which is true?
A) The App.class file is stored within the p1 folder. The Test.class file is stored within the p2 subfolder of p1.

(App.class 파일은 p1 폴더 내에 저장되며 Test.class 파일은 p1의 p2 하위 폴더 내에 저장됩니다.)
B) The App class is accessible within the Test class without an import statement.

(App 클래스는 가져오기 문 없이 Test 클래스 내에서 액세스할 수 있습니다.)
C) import p1.App; is used to access the App class within the Test class.

(p1.App을 가져옵니다. Test 클래스 내의 App 클래스에 액세스하는 데 사용됩니다.)
D) It is optional to have package statement as the first line of class definitions.

(클래스 정의의 첫 번째 행으로 패키지 문을 사용하는 것은 선택 사항입니다.)

답: C

풀이: 

App은 p1 패키지에 저장되었고, Test는 p1폴더 안의 p2 폴더에 저장되어 있다


38. Given these classes:

public class Employee {
 public int salary;
}
public class Manager extends Employee {
 public int budget;
}
public class Director extends Manager {
 public int stockOptions;
}

And given this main method:

public static void main(String[] args) {
 Employee employee = new Employee();
 Employee manager = new Manager();
 Employee director = new Director();
 // line n1
}

Which two options compiled when placed at line n1 of the main method? (Choose two.)

(주요 방법의 n1행에 배치할 때 컴파일된 두 가지 옵션은 무엇입니까?)
A) director.stockOptions = 1_000;
B) employee.salary = 50_000;
C) manager.budget = 1_000_000;
D) manager.stockOption = 500;
E) employee.budget = 200_000;
F) director.salary = 80_000;

답: B, F

풀이: 

A): Employee는 salary 변수만 사용가능하기 때문에 (Director)로 형변환하지 않는 이상 사용할 수 없다

B): Employee는 salary 변수 사용가능

C): Employee는 salary 변수만 사용가능하기 때문에 (Manager), (Director)로 형변환하지 않는 이상 사용할 수 없다

D): Employee는 salary 변수만 사용가능하기 때문에 (Director)로 형변환하지 않는 이상 사용할 수 없다

E): Employee는 salary 변수만 사용가능하기 때문에 (Manager), (Director)로 형변환하지 않는 이상 사용할 수 없다

F): Employee는 salary 변수 사용가능

package practice;

public class Employee {
	public int salary;
}
package practice;

public class Manager extends Employee {
	public int budget;
}
package practice;

public class Director extends Manager {
	 public int stockOptions;
}

 

package practice;

public class Main {
	public static void main(String[] args) {
		Employee employee = new Employee();
		Employee manager = new Manager();
		Employee director = new Director();

		director.stockOptions = 1_000; // (Director)로 형변환 해야 함
		employee.salary = 50_000;
		manager.budget = 1_000_000; // (Manager), (Director)로 형변환 해야 함
		manager.stockOption = 500; // (Director)로 형변환 해야 함
		employee.budget = 200_000; // (Manager), (Director)로 형변환 해야 함
		director.salary = 80_000;
	}
}

39. Given:

class Product {
 double price;
}
public class Test {
 public void updatePrice(Product product, double price) {
 price = price * 2;
 product.price = product.price + price;
 }
 public static void main(String[] args) {
 Product product = new Product();
 product.price = 200;
 double newPrice = 100;
 Test t = new Test();
 t.updatePrice(product, newPrice);
 System.out.println(product.price + " : " + newPrice);
 }
}

What is the result?
A) 200.0 : 100.0
B) 400.0 : 200.0
C) 400.0 : 100.0
D) Compilation fails.

답: C

풀이:

product.price는 처음엔 0으로 Product에서 초기화 됨

-> main() 안에서 200으로 변경 -> updatePrice()에서 price를 newPrice가 받게 되는데 이때 price가 100에서 100 *2 = 200이 된 것을 product.price가 200(product.price) + (200)price = 400이 됨

최종적으로 product.price는 400, newPrice는 200이라고 생각할 수 있지만 updatePrice에서 바뀐건 지역변수 price라서 상관없기 때문에 newPirce는 그대로 100

그런데 둘 다 double 형이니깐 product.price는 400.0, newPrice는 100.0임

package practice;

class Product {
	double price;
}

public class Main {
	public void updatePrice(Product product, double price) {
		price = price * 2;
		product.price = product.price + price;
}

	public static void main(String[] args) {
		Product product = new Product();
		product.price = 200;
		double newPrice = 100;
		Main t = new Main();
		t.updatePrice(product, newPrice);
		System.out.println(product.price + " : " + newPrice);
	}
}
400.0 : 100.0

 


40. Which statement is true about Java byte code? (자바 바이트 코드에 대한 설명 중 맞는 것은?)
A) It can run on any platform. (모든 플랫폼에서 실행할 수 있습니다.)
B) It can run on any platform only if it was compiled for that platform. (해당 플랫폼에 대해 컴파일된 경우에만 모든 플랫폼에서 실행할 수 있습니다.)
C) It can run on any platform that has the Java Runtime Environment.(Java Runtime Environment가 있는 모든 플랫폼에서 실행할 수 있습니다.)
D) It can run on any platform that has a Java compiler.(Java 컴파일러가 있는 모든 플랫폼에서 실행할 수 있습니다)
E) It can run on any platform only if that platform has both the Java Runtime Environment and a Java compiler.

(해당 플랫폼에 Java Runtime Environment와 Java 컴파일러가 모두 있는 경우에만 모든 플랫폼에서 실행할 수 있습니다.)

답: C

풀이:

java byte 코드는 이미 .java -> .class에서 byte 코드로 변환되었기 때문에 JVM 자바 가상 머신만 있으면 모든 플랫폼에서 실행가능하다


41. Given the code fragment:

public static void main(String[] args) {
 String[] arr = { "Hi", "How", "Are", "You" };
 List<String> arrList = new ArrayList<>(Arrays.asList(arr));
 if (arrList.removeIf(s -> { System.out.print(s); return s.length() <= 2; })) {
 System.out.println(" removed.");
 }
}

What is the result?
A) Compilation fails.
B) The program compiles, but it prints nothing.
C) HiHowAreYou removed
D) An UnsupportedOperationException is thrown at runtime.

답: C
풀이:

arr 배열에서 Hi, How, Are, You는 모두 2이상의 문자열이다

if문에서 2이하이면 지우는 것인데 모두 2이상이라서 출력이 되고 print라서 붙여서 HiHowAreYou로 출력되고

removed는 앞에 띄어 쓰기가 1개 있으므로 최종 출력은 HiHowAreYou removed이다

package practice;

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

public class Main {
	public static void main(String[] args) {
		String[] arr = { "Hi", "How", "Are", "You" };
		List<String> arrList = new ArrayList<>(Arrays.asList(arr));
		if (arrList.removeIf(s -> { System.out.print(s); return s.length() <= 2; })) {
			System.out.println(" removed.");
		}
	}
}
HiHowAreYou removed.

42. Given the code fragment:

class X { // 1
  public void printFileContent() { // 2
    /* code goes here */ // 3
    throw new IOException(); // 4
  } // 5
} // 6
  public class Test { // 7
    public static void main(String[] args) { // 8
      X xobj = new X(); // 9
      xobj.printFileContent(); // 10
    } // 11
} // 12

Which two modifications should you make so that the code compiles successfully? (Choose two.)

(코드가 성공적으로 컴파일되기 위해 어떤 두 가지 수정을 해야 합니까?)
A) Replace line 13 with:
    try {
        xobj.printFileContent();
    } catch (Exception e) {
    } catch (IOException e) {
    }
B) Replace line 7 with throw IOException("Exception raised");
C) Replace line 11 with public static void main(Stirng[] args) throws Exception {
D) At line 14, insert throw new IOException();
E) Replace line 5 with public void printFileContent() throws IOException {

답: C, E


43. Which two statements are true? (Choose two.) (어떤 두 문장이 true입니까?)
A) Error class is unextendible. (Error 클래스를 확장할 수 없습니다)
B) Error class is extendable. (Error 클래스를 확장할 수 있습니다))
C) Error is a RuntimeException. (에러는 Runtime 예외입니다)
D) Error is an Exception. (Error는 예외입니다)
E) Error is a Throwable. (에러는 throw 던질 수 있습니다.)

답: B, E


44. Given the code fragment:

public class Game {
 public static void menu() {
 System.out.println("1. Left 2. Right 0. Stop");
 }
 public static void main(String[] args) {
 int option;
 /* insert code here */
 }
}

and the requirements of the application: (응용 프로그램의 요구 사항:)
    - It must display the menu. (메뉴를 표시)
    - It must print the option selected. (선택한 옵션을 print)
     - It must continue its execution till it resads ‘0’. ('0'이 될 때까지 계속 실행)
Which code fragment can be used to meet the requirements?
A)

for (option = 0;
 option != 0;
 option = /* code that reads the option goes here */) {
 /* code that print the option go here */
}


B)

while (option != 0) {
 menu();
 option = // code that reads the option goes here
 /* code that print the option go here */
}


C)

do {
 menu();
 option = // code tha reads the option goes here
 /* code that prints the option goes here */
} while (option != 0);


D)

while (option >= 0) {
 menu();
 option = // code that reads the option goes here
 /* code that print the option go here */
}

답: C


45. Given:

public class Test {
 public static final int MIN = 1;
 public static void main(String[] args) {
 int x = args.length;
 if (checkLimit(x)) { // line n1
 System.out.println("Java SE");
 } else {
 System.out.println("Java EE");
 }
 }
 public static boolean checkLimit(int x) {
 return (x >= MIN) ? true : false;
 }
}

And given the commands:

javac Test.java
java Test 1


What is the result?
A) Java SE
B) Java EE
C) Compilation fails at line n1
D) A NullPointerException is thrown at runtime.

답: A

풀이:

MIN은 static이고 final 이라서 무조건 1이다

checkLimit()에서 x는 Test 1을 입력하고 1보다 무조건 길이가 길기 때문에 return 값으로 true를 반환해준다

그러면 line n1 에서 true이기 때문에 Java SE가 실행된다

package practice;

public class Main {
	public static final int MIN = 1;
	public static void main(String[] args) {
		int x = args.length;
		if (checkLimit(x)) { // line n1
			System.out.println("Java SE");
		} else {
			System.out.println("Java EE");
		}
	}
	
	public static boolean checkLimit(int x) {
		return (x >= MIN) ? true : false;
	}
}
Java SE

46. Given:

public static void main(String[] args) {
 String ta = "A ";
 ta = ta.concat("B ");
 String tb = "C ";
 ta = ta.concat(tb);
 ta.replace('C', 'D');
 ta = ta.concat(tb);
 System.out.println(ta);
}

What is the result?
A) A B C D
B) A C D
C) A B C C
D) A B D
E) A B D C

답: C

풀이:

concat은 문자열을 이어줌

여기에서 replace로 바꿔주는 문장에서 ta에 다시 저장하지 않았기 때문에 ta는 그대로이다 이때 A B C가 됨

밑의 코드에서 비교해보기

package practice;

public class Main {
	public static void main(String[] args) {
		String ta = "A "; // A
		ta = ta.concat("B "); // A B
		String tb = "C ";
		ta = ta.concat(tb); // A B C
		ta = ta.replace('C', 'D');  // A B D
		ta = ta.concat(tb);  // A B D C
		System.out.println(ta);
	}
}
A B D 
A B D C
package practice;

public class Main {
	public static void main(String[] args) {
		String ta = "A "; // A
		ta = ta.concat("B "); // A B
		String tb = "C ";
		ta = ta.concat(tb); // A B C
		ta.replace('C', 'D');  // A B C
		System.out.println(ta);
		ta = ta.concat(tb);  // A B C C
		System.out.println(ta);
	}
}
A B C 
A B C C

47. Given the class definitions:

class C1 {}
class C2 extends C1 {}
class C3 extends C2 {}

and the code fragment:

C1 obj1 = (C1) new C2(); // 16
C2 obj2 = (C2) new C3(); // 17
C2 obj3 = (C2) new C1(); // 18
C3 obj4 = (C3) obj2; // 19

 

Which line throws ClassCastException?
A) line 16
B) line 17
C) line 18
D) line 19

답: C

풀이:

C(18)는 C2가 C1보다 하위 클래스인데 다형성이 적용이 되지 않는다

반대로 C1 obj3 = (C1) new C2()는 가능하다

package practice;

class C1 {}
class C2 extends C1 {}
class C3 extends C2 {}

public class Main {
	public static void main(String[] args) {
		C1 obj1 = (C1) new C2();
		C2 obj2 = (C2) new C3();
		C2 obj3 = (C2) new C1(); // 형변환 안됨
		C3 obj4 = (C3) obj2;
	}
}
class practice.C1 cannot be cast to class practice.C2

48. Given:

class Vehicle {
 Vehicle() {
 System.out.println("Vehicle");
 }
}
class Bus extends Vehicle {
 Bus() {
 System.out.println("Bus");
 }
}
public class Transport {
 public static void main(String[] args) {
 Vehicle v = new Bus();
 }
}

What is the result?
A) Vehicle
    Bus
B) Bus
    Vehicle
C) Bus
D) The program doesn’t print nothing.

답: A

풀이:

Bus() 생성자가 실행되고 이때 super()가 생략되어있다

super() = Vehicle()이고 그래서 Vehicle이 출력되고 Bus가 출력된다

package practice;

class Vehicle {
	Vehicle() {
		System.out.println("Vehicle");
	}
}

class Bus extends Vehicle {
	Bus() {
		super();
		System.out.println("Bus");
	}
}

public class Main {
	public static void main(String[] args) {
		Vehicle v = new Bus();
	}
}
Vehicle
Bus

 


49. Given the code fragment:

List<String> arrayList = new ArrayList<>();
arrayList.add("Tech");
arrayList.add("Expert");
arrayList.set(0, "Java");
arrayList.forEach(a -> a.concat("Forum"));
arrayList.replaceAll(s -> s.concat("Group"));
System.out.println(arrayList);

What is the result?
A) [JavaForum, ExpertForum]
B) [JavaGroup, ExpertGroup]
C) [JavaForumGroup, ExpertForumGroup]
D) [JavaGroup, TechGroup, ExpertGroup]

답: B

풀이:

[Tech]

[Tech, Expert]

[Java, Expert]

[JavaGroup, ExpertGroup]

package practice;

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

public class Main {
	public static void main(String[] args) {
		List<String> arrayList = new ArrayList<>();
		arrayList.add("Tech"); // [Tech]
		arrayList.add("Expert"); // [Tech, Expert]
		arrayList.set(0, "Java"); // [Java, Expert]
		arrayList.forEach(a -> a.concat("Forum")); // 적용 안됨
		arrayList.replaceAll(s -> s.concat("Group")); // [JavaGroup, ExpertGroup]

		System.out.println(arrayList);
	}
}
[JavaGroup, ExpertGroup]

50. Given:

String stuff = "TV";
String res = null;
if (stuff.equals("TV")) {
 res = "Walter";
} else if (stuff.equals("Movie")) {
 res = "White";
} else {
 res = "No result";
}

Which code fragment can replace the if block?
A) stuff.equals("TV") ? res = "Walter" : stuff.euqals("Movie") ? res = "White" : res = "No result";
B) res = stuff.euqals("TV") ? "Walter" else stuff.equals("Movie") ? "White" : "No result";
C) res = stuff.equals("TV") ? stuff.equals("Movie") ? "Walter" : "White" : "No result";
D) res = stuff.equals("TV") ? "Walter" : stuff.equals("Movie") ? "White" : "No result”;

답: D

풀이:

꼭 res라는 변수에 저장을 해줘야 함

if와 else if문과 else문을 true와 false로 구분해서, ? 바로 뒤에는 true가 오는 문장을, : 뒤에는 fasle가 오는 문장을 적어주면 됨

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

Java Test 2차 오답노트(김병우)  (0) 2024.03.16
자바테스트 문제  (0) 2024.03.03
Eclipse 자동완성  (0) 2023.05.14
Eclipse 단축키  (0) 2023.05.14