티스토리 뷰

반응형

NEW QUESTION 1 Given the code fragment:

1

2

3

4

5

6

7

8

public static void main(String[] args) throws IOException {

  BufferedReader brCopy = null;

  try (BufferedReader br = new BufferedReader(new FileReader("employee.txt"))) { // line n1

    br.lines().forEach(c ->System.out.println(c));

    brCopy = br; //line n2

  }

  brCopy.ready(); //line n3;

}

cs

Assume that the ready method of the BufferedReader, when called on a closed BufferedReader, throws an exception, and employee.txt is accessible and contains valid text.
What is the result?
A. A compilation error occurs at line n3.
B. A compilation error occurs at line n1.
C. A compilation error occurs at line n2.
D. The code prints the content of the employee.txt file and throws an exception at line n3.

Answer: D

Explanation: br이 이미 try 문에서 close()되었으므로 참조하는 brCopy에서 ready를 쓸수없음.

NEW QUESTION 2 What is the result?

1

2

3

4

5

6

7

8

9

1

BiPredicate<String, String> bp = (s1, s2) -> s1.contains("SG") && s2.contains("Java");

BiFunction<String, String, Integer> bf = (String s1, String s2) -> {

    int fee = 0;

    if (bp.test(s1, s2)){

        fee = 100;

    }

    return fee;

};

int fee1 = bf.apply("D101SG","Java Programming");

System.out.println(fee1);

cs


A. A compilation error occurs at line 7.
B. 100
C. A compilation error occurs at line 8.
D. A compilation error occurs at line 15.
Answer: B

Explanation: BiPredicates는 서로 다른 타입의 2개의 인자를 받아 boolean을 리턴, BiFunction은 서로 다른 타입의 2개의 인재를 받아 또다른 타입으로 반환하는 함수.

NEW QUESTION 3 Given the code fragment:
Which code fragment, when inserted at line 7, enables printing 100?

1

2

3

4

IntConsumer consumer = e -> System.out.println(e);

Integer value = 90;

/*Insert code fragment here*/

consumer.accept(result);

cs


A. Function<Integer> funRef = e –> e + 10;
Integer result = funRef.apply(value);
B. IntFunction funRef = e –> e + 10;
Integer result = funRef.apply (10);
C. ToIntFunction<Integer> funRef = e –> e + 10;
int result = funRef.applyAsInt (value);
D. ToIntFunction funRef = e –> e + 10;
int result = funRef.apply (value);

Answer: A

Explanation: IntConsumer는 Int타입의 어떤 객체를 받아 void를 반환함.

NEW QUESTION 4 Given the code fragment:

1

2

3

for (Course a : Course.value()){

    System.out.print(a + " Fees " + a.getCost() + " ");

}

cs


Which is the valid definition of the Course enum?


A. Option A B. Option B C. Option C D. Option D

Answer: D

Explanation: enum의 생성자는 public 접근제어자를 허용하지 않는다

NEW QUESTION 5 Given the code fragment:

1

2

3

4

5

6

7

8

9

Stream<Path> files = Files.walk(Paths.get(System.getProperty("user.home")));

files.forEach(fName ->{ //line n1

  try {

    Path aPath = fName.toAbsolutePath(); //line n2

    System.out.println(fName + ":" + Files.readAttributes(aPath, BasicFileAttributes.class).creationTime());

  } catch(IOException ex) {

    ex.printStackTrace();

  }

});

Colored by Color Scripter

cs

What is the result?

A. All files and directories under the home directory are listed along with their attributes.
B. A compilation error occurs at line n1.
C. The files in the home directory are listed along with their attributes.
D. A compilation error occurs at line n2.

Answer: A

※import java.util.stream.Stream;
import java.nio.file.*;
import java.nio.file.attribute.*;

NEW QUESTION 6
Which statement is true about java.time.Duration?
A. It tracks time zones.
B. It preserves daylight saving time.
C. It defines time-based values.
D. It defines date-based values.

Answer: C

Explanation: Duration deals with time. for example
LocalTime gabzTime = LocalTime.of(12, 51, 0);
LocalTime ghettoTime = gabzTime.plus(Duration.ofSeconds(45)) ;
long timeDiff = Duration.between(gabzTime, ghettoTime); // 45 seconds

NEW QUESTION 7
Given:

1

2

3

4

5

6

7

8

class Resource implements AutoCloseable {

  public void close() throws Exception {

    System.out.println("Close-");

  }

  public void open() {

    System.out.println("Open-");

  }

}

Colored by Color Scripter

cs


and this code fragment:

1

2

3

4

5

6

7

8

9

10

11

12

Resource res1 = new Resource();

try {

  res1.open();

  res1.close();

} catch(Exception e) {

  System.out.println("Exception - 1");

}

try (res1 = new Resource()) { //line n1

  res1.open();

} catch(Exception e) {

  System.out.println("Exception - 2");

}

Colored by Color Scripter

cs


What is the result?
A. Open-Close– Exception – 1 Open–Close–
B. Open–Close–Open–Close–
C. A compilation error occurs at line n1.
D. Open–Close–Open–

Answer: C

Explanation: try-with-resource 구문은 변수선언을 안(line1)에서 해야함.

NEW QUESTION 8
Given the code fragment:

1

2

3

4

5

6

7

8

List<String> words = Arrays.asList("win","try","best","luck","do");

Predicate<String> test1 = w -> {

    System.out.println("Checking...");

    return w.equals("do");//line n1

};

Predicate test2 = (String w) -> w.length() > 3; //line 2

words.stream().filter(test2).filter(test1).count();

 

Colored by Color Scripter

cs


What is the result?
A. A compilation error occurs at line n1.
B. Checking...
C. Checking... Checking...
D. A compilation error occurs at line n2.

Answer: D

Explanation: Predicate<String> 제너릭 타입이 빠져있음

NEW QUESTION 9
Given the code fragment:

1

2

3

4

List <String> codes = Arrays.asList("DOC", "MPEG", "JPEG");

codes.forEach(c ->System.out.print(c + " "));

String fmt = codes.stream().filter(s ->s.contains("PEG")).reduce((s, t) ->s + t).get();

System.out.println("\n" + fmt);

Colored by Color Scripter

cs

What is the result?
A. DOC MPEG JPEG
MPEGJPEG
B. DOC MPEG
MPEGJPEG
MPEGMPEGJPEG
C. MPEGJPEG
MPEGJPEG
D. The order of the output is unpredictable.

Answer: A

Explanation: 두번째 라인에서 DOC MPEG JPEG 출력, 네번째라인에서 MPEGJPEG 출력.
reduce() 는 스트림의 요소로 연산한다. 첫번째 요소와 두번째 요소를 비교하여 결과값을 내고, 결과값과 세번째요소, 또 그의 결과값과 네번째요소...연속해서 비교한다.

NEW QUESTION 10
Given the code fragment:

1

2

3

4

List < Integer > values = Arrays.asList(1, 2, 3);

values.stream().map(n ->n * 2) //line n1

.peek(System.out::print) //line n2

.count();

Colored by Color Scripter

cs


What is the result?
A. 246
B. The code produces no output.
C. A compilation error occurs at line n1.
D. A compilation error occurs at line n2.

Answer: A

NEW QUESTION 11
Given the code fragment:

1

2

3

ProductCode < Number, Integer > c1 = new ProductCode < Number, Integer > (); /*c1 instantiantion*/

ProductCode < Number, String > c2 = new ProductCode < Number, String > (); /*c2 instantiation*/

 Colored by Color Scripter

cs


You have been asked to define the ProductCode class. The definition of the ProductCode class must allow c1 instantiation to succeed and cause a compilation error on c2 instantiation.
Which definition of ProductCode meets the requirement?

A. Option A
B. Option B
C. Option C
D. Option D

Answer: B

Explanation: java.lang.Number 부모클래스
● java.lang.Integer 자식클래스

NEW QUESTION 12 Given:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public class Job {

    String name;

    Integer cost;

    Job(String name, Integer cost){

        this.name = name;

        this.cost = cost;

    }

    String getName() { return name; }

    int getCost() { return cost; }

    public static void main(String[] args){

        Job j1 = new Job("IT", null);

        DoubleSupplier jS1 = j1::getCost;

        System.out.println(j1.getName() + ":" + jS1.getAsDouble());

    }

}

Colored by Color Scripter

cs


What is the result?

A. IT:null
B. A NullPointerException is thrown at run time.
C. A compilation error occurs.
D. IT:0.0

Answer: B

Explanation: j1::getCost;의 더블콜론은 메소드참조로, 메소드를 호출하는 것이 아니라 메소드 로직 자체를 참조하도록함. Supplier는 매개변수를 받지 않고 특정 타입의 결과를 리턴하는 함수형 인터페이스이다. 결국, 12-13라인은 (double)j1.getCost()을 호출하는 것과 같은데, int타입에는 null이 들어갈수없으므로 jS1.getAsDouble()에서 null포인터exception 난다.

NEW QUESTION 13
Given the code fragment:

1

2

Path p1 = Paths.get("/Pics/MyPic.jpeg");

System.out.println(p1.getNameCount() + ":" + p1.getName(1) + ":" + p1.getFileName());

cs


Assume that the Pics directory does NOT exist. What is the result?
A. An exception is thrown at run time.
B. 2:MyPic.jpeg: MyPic.jpeg
C. 1:Pics:/Pics/ MyPic.jpeg
D. 2:Pics: MyPic.jpeg

Answer: B

Explanation: getName(int index)- 인덱스 번호에 해당하는 주소를 가진 Path 객체 생성(루트 다음부터 인덱스 0)
, getNameCount()- 루트주소 다음부터 몇 개의 계층으로 이루어져 있는지 갯수 반환


NEW QUESTION 14
Given the code fragment:
Path file = Paths.get ("courses.txt"); // line n1

Assume the courses.txt is accessible.
Which code fragment can be inserted at line n1 to enable the code to print the content of the courses.txt file?

A. List<String> fc = Files.list(file);
fc.stream().forEach (s - > System.out.println(s));
B. Stream<String> fc = Files.readAllLines (file);
fc.forEach (s - > System.out.println(s));
C. List<String> fc = readAllLines(file);
fc.stream().forEach (s - > System.out.println(s));
D. Stream<String> fc = Files.lines (file);
fc.forEach (s - > System.out.println(s));

Answer: D

Explanation:

static List<String>

readAllLines(Path path)

Read all lines from a file.

static Stream<String>

lines(Path path)

Read all lines from a file as a Stream.


NEW QUESTION 15 Given:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public final class IceCream {

  public void prepare() {}

}

public class Cake {

  public final void bake(int min, int temp) {}

  public void mix() {}

}

public class Shop {

  private Cake c = new Cake();

  private final double discount = 0.25;

  public void makeReady() {

    c.bake(10, 120);

  }

}

public class Bread extends Cake {

  public void bake(int minutes, int temperature) {}

  public void addToppings() {}

}

Colored by Color Scripter

cs

Which statement is true?
A. A compilation error occurs in IceCream.
B. A compilation error occurs in Cake.
C. A compilation error occurs in Shop.
D. A compilation error occurs in Bread
E. All classes compile successfully.

Answer: D

Explanation: 클래스에 final이 붙으면 상속시킬수없고, 메소드에 final이 붙으면 오버라이드 할수없다.
16번째라인에서 컴파일 에러 남.

NEW QUESTION 16
Given the code fragment:

1

2

List<String> cs = Arrays.asList("Java","Java EE","Java ME");//line n1

System.out.print(b);

Colored by Color Scripter

cs


Which code fragment, when inserted at line n1, ensures false is printed?
A. boolean b = cs.stream().findAny().get().equals("Java");
B. boolean b = cs.stream().anyMatch(w -> w.equals ("Java"));
C. boolean b = cs.stream().findFirst().get().equals("Java");
D. boolean b = cs.stream().allMatch(w -> w.equals("Java"));

Answer: D

Explanation:
findFirst()와 findAny() 메소드는 해당 스트림에서 첫 번째 요소를 참조하는 Optional 객체를 반환합니다.
anyMatch() : 해당 스트림의 일부 요소가 특정 조건을 만족할 경우에 true를 반환함.
allMatch() : 해당 스트림의 모든 요소가 특정 조건을 만족할 경우에 true를 반환함.

NEW QUESTION 17
Given the code fragment:

1

2

3

4

5

List<String> valList = Arrays.asList("","George","","John","Jim");

Long newVal = valList.stream() // line n1

                     .filter(x -> !x.isEmpty())

                     .count();    //line n2

System.out.println(newVal);

Colored by Color Scripter

cs


What is the result?
A. A compilation error occurs at line n2.
B. 3
C. 2
D. A compilation error occurs at line n1.

Answer: B

NEW QUESTION 18
Given the content:

1

2

3

4

MessageBundle.properties file:

inquiry = How are you?

MessagesBundle_de_DE.properties file:

inquiry = Wie geht's?

cs

and given the code fragment:

1

2

3

4

Locale currentLocale;

//line 1

ResourceBundle messages = ResourceBundle.getBundle("MessagesBundle",currentLocale);

System.out.println(messages.getString("inquiry"));

Colored by Color Scripter

cs


Which two code fragments, when inserted at line 1 independently, enable the code to print "Wie geht’s?"

A. currentLocale = new Locale("de", "DE");
B. currentLocale = new Locale.Builder().setLanguage("de").setRegion("DE").build();
C. currentLocale = Locale.GERMAN;
D. currentlocale = new Locale();
currentLocale.setLanguage ("de");
currentLocale.setRegion ("DE");
E. currentLocale = Locale.getInstance(Locale.GERMAN,Locale.GERMANY);

Answer: A, B

Explanation:
아래 세 구문이 모두 같은 정의이다.
j4Locale = Locale.JAPAN;
j5Locale = new Locale.Builder().setLanguage("ja").setRegion("JP").build();
j6Locale = new Locale("ja", "JP");

new Locale(); 이러한 생성자는 존재하지 않는다.

Constructor and Description

Locale(String language)

Construct a locale from a language code.

Locale(String language, String country)

Construct a locale from language and country.

Locale(String language, String country, String variant)

Construct a locale from language, country and variant.


NEW QUESTION 19
Given:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public class Foo<K, V> {

    private K key;

    private V value;

   

    public Foo(K key, V value){

        this.key = key;

        this.value = value;

    }

    public static <T> Foo<T, T> twice(T value){

        return new Foo<T, T>(value, value);

    }

    public K getKey(){ return key; }

    public V getValue(){ return value; }

}

Colored by Color Scripter

cs


Which option fails?
A. Foo<String, Integer> mark = new Foo<String, Integer> ("Steve", 100);
B. Foo<String, String> pair = Foo.<String>twice ("Hello World!");
C. Foo<Object, Object> percentage = new Foo<String, Integer>("Steve", 100);
D. Foo<String, String> grade = new Foo <> ("John", "A");

Answer: C

Explanation: String, Integer가 Object로 convert될 수없다.

NEW QUESTION 20
Given the code fragment:

1

2

3

4

public static void main(String[] args){

    Stream.of("Java","Unix","Linux").filter(s-> s.contains("n"))

                                    .peek(s -> System.out.println("PEEK: " + s));//line n1

}

Colored by Color Scripter

cs


Which two code fragments, when inserted at line n1 independently, result in the output PEEK: Unix?
A. .anyMatch ();
B. .allMatch ();
C. .findAny ();
D. .noneMatch ();
E. .findFirst ();

Answer: C,E

Explanation:
findFirst()와 findAny() 메소드는 해당 스트림에서 첫 번째 요소를 참조하는 Optional 객체를 반환합니다.
anyMatch() : 해당 스트림의 일부 요소가 특정 조건을 만족할 경우에 true를 반환함.
allMatch() : 해당 스트림의 모든 요소가 특정 조건을 만족할 경우에 true를 반환함.

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
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 31
글 보관함