티스토리 뷰

반응형

NEW QUESTION 21 Given:

1

2

3

4

IntStream stream = IntStream.of (1,2,3); 

IntFunction<Integer> inFu= x -> y -> x*y; //line n1 

IntStream newStream = stream.map(inFu.apply(10)); //line n2 

newStream.forEach(System.out::print);

cs


Which modification enables the code fragment to compile?
A. Replace line n1 with: IntFunction<UnaryOperator> inFu = x -> y -> x*y;
B. Replace line n1 with: IntFunction<IntUnaryOperator> inFu = x -> y -> x*y;
C. Replace line n1 with: BiFunction<IntUnaryOperator> inFu = x -> y -> x*y;
D. Replace line n2 with:IntStream newStream = stream.map(inFu.applyAsInt (10));

Answer: B

Explanation: IntFunction<R>은 int로 받아서 R타입으로 반환하는 함수이다.
map 스트림메소드는 스트림 내 요소를 가공하주므로 인자로 function을 받는다.
따라서 line2는 function 인자여야한다.
UnaryOperator는 매개변수 하나를 받고 동일한 타입을 리턴하는 함수형 인터페이스이다.
매개변수로 10을 받기 때문에 IntUnaryOperator가 가장 적절하다.

NEW QUESTION 22
Given:

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

public class Customer {

  private String fName;

  private String lName;

  private static int count;

  public Customer(String first, String last) {

    fName = first;

    lName = last; 

    ++count;

  }

  static {

    count = 0;

  }

  public static int getCount() {

    return count;

  }

}

public class App {

  public static void main(String[] args) {

    Customer c1 = new Customer("Larry", "Smith");

    Customer c2 = new Customer("Pedro", "Gonzales");

    Customer c3 = new Customer("Penny", "Jones");

    Customer c4 = new Customer("Lars", "Svenson");

    c4 = null;

    c3 = c2;

    System.out.println(Customer.getCount());

  }

}

 

Colored by Color Scripter

cs


What is the result?
A. 2 B. 3 C. 4 D. 5

Answer: C

Explanation: 싱글톤 패턴

NEW QUESTION 23
Given the code fragment:

1

2

3

4

5

6

Path path1 = Paths.get("/app/./sys/");

Path res1 = path1.resolve("log");

Path path2 = Paths.get("/server/exe/");

Path res2 = path2.resolve("/readme/");

System.out.println(res1);

System.out.println(res2);

cs


What is the result?
A. /app/sys/log
/readme/server/exe
B. /app/log
/sys/server/exe/readme
C. /app/./sys/log
/readme
D. /app/./sys/log
/server/exe/readme

Answer: C

Explanation: get()메소드를 통해 고정경로를 정의한다
resolve()메소드를 통해 고정된 루트경로에 부분 경로를 추가한다.
첫번째 라인에 두번째 라인경로를 추가한것이다.
“/readme”는 절대경로이므로 세번째라인에 네번째라인경로가 추가된것이 아니라 재정의되었다.

NEW QUESTION 24
What is true about the java.sql.Statement interface?

A. It provides a session with the database.
B. It is used to get an instance of a Connection object by using JDBC drivers.
C. It provides a cursor to fetch the resulting data.
D. It provides a class for executing SQL statements and returning the results.

Answer: D

NEW QUESTION 25 Given:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

abstract class Shape {

  Shape() { System.out.println("Shape"); }

  protected void area() { System.out.println("Shape"); }

}

class Square extends Shape {

  int side;

  Square(int side) {

    /* insert code here */

    this.side = side;

  }

  public void area() { System.out.println("Square"); }

}

class Rectangle extends Square {

  int len, br;

  Rectangle(int x, int y) {

    /* insert code here */

    len = x; br = y;

  }

  void area() { System.out.println("Rectangle"); }

}

Colored by Color Scripter

cs

Which two modifications enable the code to compile? (Choose two.)
A. At line 1, remove abstract
B. At line 9, insert super ( );
C. At line 12, remove public
D. At line 17, insert super (x);
E. At line 17, insert super (); super.side = x;
F. At line 20, use public void area ( ) {

Answer: DF

Explanation:


NEW QUESTION 26
Given the definition of the Emp class:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public class Emp {

  private String eName;

  private Integer eAge;

  Emp(String eN, Integer eA) {

    this.eName = eN;

    this.eAge = eA;

  }

  public Integer getEAge() {

    return eAge;

  }

  public String getEName() {

    return eName;

  }

}

cs

and code fragment:

1

2

3

4

5

List < Emp > li = Arrays.asList(new Emp("Sam", 20), 

                                                 new Emp("John", 60), new Emp("Jim", 51));

Predicate < Emp > agVal = s -> s.getEAge() > 50; //line n1 

li = li.stream().filter(agVal).collect(Collectors.toList());

Stream < String > names = li.stream() map. (Emp::getEName); //line n2 

names.forEach(n ->System.out.print(n + " "));

Colored by Color Scripter

cs


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

Answer: B

NEW QUESTION 27 Given the code fragment:

1

2

3

4

5

6

7

8

9

Connection con = null;

try {

    //line n1

    if(con != null){

        System.out.print("Connection Established.");

    }

}catch(Exception e){

    System.out.print(e);

}

Colored by Color Scripter

cs


Assume that dbURL, userName, and password are valid.
Which code fragment can be inserted at line n1 to enable the code to print Connection Established?

A. Properties prop = new Properties();
prop.put ("user", userName);
prop.put ("password", password);
con = DriverManager.getConnection (dbURL, prop);
B. con = DriverManager.getConnection (userName, password, dbURL);
C. Properties prop = new Properties();
prop.put ("userid", userName);
prop.put ("password", password);
prop.put("url", dbURL);
con = DriverManager.getConnection (prop);
D. con = DriverManager.getConnection (dbURL);
con.setClientInfo ("user", userName);
con.setClientInfo ("password", password);

Answer: A

NEW QUESTION 28
Given the content of /resources/Message.properties: welcome1="Good day!"
and given the code fragment:

1

2

3

4

5

6

Properties prop = new Properties();

FileInputStream fis = new FileInputStream("/resources/Message.properties");

prop.load(fis);

System.out.println(prop.getProperty("welcome1"));

System.out.println(prop.getProperty("welcome2", "Test")); //line n1 

System.out.println(prop.getProperty("welcome3"));

cs


What is the result?
A. Good day!
Test
followed by an Exception stack trace
B. Good day!
followed by an Exception stack trace
C. Good day!
Test
null
D. A compilation error occurs at line n1.

Answer: C

Explanation:
prop.getProperty("welcome2", "Test")는 default로 Test를 출력하고,
prop.getProperty("welcome3") 는 값이 없으므로 null을 출력한다

Modifier and Type

Method and Description

String

getProperty(String key)

Searches for the property with the specified key in this property list.

String

getProperty(String key, String defaultValue)

Searches for the property with the specified key in this property list.




NEW QUESTION 29
Given the structure of the Student table: Student (id INTEGER, name VARCHAR)
Given the records from the STUDENT table:

ID

NAME

102

Edwin

103

Edward

103

Edwin


Given the code fragment:

1

2

3

4

Connection conn = DriverManager.getConnection(dbURL, userName, passWord);

Statement st = conn.createdStatement();

String query = "DELETE FROM Student WHERE id = 103";

System.out.println("Status: " + st.execute(query));

cs


Assume that:
The required database driver is configured in the classpath.
The appropriate database is accessible with the dbURL, userName, and passWord exists.
What is the result?
A. The program prints Status: true and two records are deleted from the Student table.
B. The program prints Status: false and two records are deleted from the Student table.
C. A SQLException is thrown at runtime.
D. The program prints Status: false but the records from the Student table are not deleted.

Answer: B

Explanation: boolean execute(java.lang.String sql)문이 결과 집합을 반환하는 경우 true입니다. 업데이트 수를 반환하거나 결과를 반환하지 않는 경우 false입니다

NEW QUESTION 30
Given the code fragments:

1

2

3

4

5

6

7

class MyThread implements Runnable {

  private static AtomicInteger count = new AtomicInteger(0);

  public void run() {

    int x = count.incrementAndGet();

    System.out.print(x + " ");

  }

}

Colored by Color Scripter

cs

and

1

2

3

4

5

6

7

8

9

10

11

Thread thread1 = new Thread(new MyThread());

Thread thread2 = new Thread(new MyThread());

Thread thread3 = new Thread(new MyThread());

Thread[] ta = {

  thread1,

  thread2,

  thread3

};

for (int x = 0; x < 3; x++) {

  ta[x].start();

}

Colored by Color Scripter

cs

Which statement is true?
A. The program prints 1 2 3 and the order is unpredictable.
B. The program prints 1 2 3.
C. The program prints 1 1 1.
D. A compilation error occurs.

Answer: A
Explanation: Java 멀티스레드는 실행제어순서를 보장하지 않는다.

NEW QUESTION 31

Locale

Currency Symbol

Currency Code

US

$

USD

and the code fragment?

1

2

3

4

double d = 15;

Locale l = new Locale("en","US");

NumberFormat formatter = NumberFormat.getCurrencyInstance(l);

System.out.println(formatter.format(d));

cs


What is the result?
A. $15.00
B. 15 $
C. USD 15.00
D. USD $15

Answer: A

Explanation: formatter.getCurrency().getCurrencyCode(); //USD 출력

NEW QUESTION 32
You want to create a singleton class by using the Singleton design pattern.
Which two statements enforce the singleton nature of the design? (Choose two.)

A. Make the class static.
B. Make the constructor private.
C. Override equals() and hashCode() methods of the java.lang.Object class.
D. Use a static reference to point to the single instance.
E. Implement the Serializable interface.

Answer: BD

Explanation: 싱글턴 패턴의 공통적인 특징은 private constructor 를 가진다는 것과, static method 를 사용한다는 점입니다.

1

2

3

4

5

6

7

8

9

10

public class Singleton {

    // Eager Initialization

    private static Singleton uniqueInstance = new Singleton();

 

    private Singleton() {}

 

    public static Singleton getInstance() {

      return uniqueInstance; 

    } 

}

Colored by Color Scripter

cs


NEW QUESTION 33 Given the code fragments:

1

2

3

4

5

interface CourseFilter extends Predicate < String > {

  public default boolean test(String str) {

    return str.equals("Java");

  }

}

Colored by Color Scripter

cs

and

1

2

3

4

5

6

7

8

9

List < String > strs = Arrays.asList("Java", "Java EE", "Java ME");

Predicate < String > cf1 = s ->s.length() > 3;

Predicate cf2 = new CourseFilter() { //line n1 

  public boolean test(String s) {

    return s.contains("Java");

  }

};

long c = strs.stream().filter(cf1).filter(cf2).count(); //line n2 

System.out.println(c);

Colored by Color Scripter

cs

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

Answer: B

Explanation: unchecked or unsafe operations. 가 뜨기는 하지만 line n1에서 <String>이 없어도 됨

NEW QUESTION 34
Given that /green.txt and /colors/yellow.txt are accessible, and the code fragment:

1

2

3

4

Path source = Paths.get("/green.txt");

Path target = Paths.get("/colors/yellow.txt");

Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);

Files.delete(source);

Colored by Color Scripter

cs

Which statement is true?
A. The green.txt file content is replaced by the yellow.txt file content and the yellow.txt file is deleted.
B. The yellow.txt file content is replaced by the green.txt file content and an exception is thrown.
C. The file green.txt is moved to the /colors directory.
D. A FileAlreadyExistsException is thrown at runtime.

Answer: D

Explanation:

<아래>
ATOMIC_MOVE의 원자적 이동이란 파일 이동 중에 어떠한 방해가 생기더라도 이동 작업을 끝까지 보장한다는 의미입니다. 즉, 파일 이동 중에 어떤 프로세스가 간섭해서 중단명령을 내려도(interrupt) 이를 무시하고 이동을 완료한 뒤 대응합니다.
예를 들어 멀티 스레드 환경에서는 다른 스레드를 강제 중단시키는 interrupt 기능을 사용할 수 있습니다. 원래 interrupt가 발생하면 스레드가 바로 중단돼야 하지만 파일 전송의 경우 끊기면 문제가 발생할 수 있기 때문에 전송이 다 될 때까지 스레드를 중단시키지 않는 것입니다.
ATOMIC_MOVE - move 전용, 원자적 이동을 보장복사함.

Path move(Path source, Path dest. CopyOption)
- source 파일을 dest 경로로 이동
- source 파일이 없거나 dest 파일이 이미 있으면 예외 발생
- 두 경로가 동일하다면 source 파일의 이름을 dest로 변경
- dest 파일이 있더라도 덮어쓰는 등 CopyOption 사용 가능

The program will move “/green.txt” to “/colors/yellow.txt”, the original “/colors/yellow.txt” will be overwritten, and “/green.txt” will be deleted. This uses the CopyOption StandardCopyOption.ATOMIC_MOVE, which will move the file’s actions to atomic, that is, it will not be involved in other threads (such as the ability to grab write access to files).
Option A, write the opposite.
Option B, because “/colors/yellow.txt” already exists, does not use the CopyOption of StandardCopyOption.REPLACE_EXISTING, and therefore will throw a FileAlreadyExistsException before moving the file. The file will not be moved.
Option C does not.
Option D throws a FileAlreadyExistsException, see option B. (I think this is the correct answer).
Note that there may be some problems with the actual execution of this program, which is Java’s bug. When the author executes this program on the EXT4 file system on the Linux operating system, the StandardCopyOption.ATOMIC_MOVE CopyOption will force the existing file to be overwritten, so FileAlreadyExistsException will not be thrown. A NoSuchFileException will be thrown when the program reaches the line “Files.delete(source);”, because the source file will be deleted after it is moved.



NEW QUESTION 35
Given the structure of the STUDENT table: Student (id INTEGER, name VARCHAR)
Given:

1

2

3

4

5

6

7

8

9

10

11

1

public class Test {

  static Connection newConnection = null;

  public static Connection getDBConnection() throws SQLException {

    try (Connection con = DriverManager.getConnection(URL, username, password)) {

      newConnection = con;

    }

    return newConnection;

  }

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

    getDBConnection();

    Statement st = newConnection.createStatement();

    st.executeUpdate("INSERT INTO student VALUES (102, 'Kelvin')");

  }

}

Colored by Color Scripter

s


Assume that:
The required database driver is configured in the classpath. The appropriate database is accessible with the URL, userName, and passWord exists. The SQL query is valid. What is the result?
A. The program executes successfully and the STUDENT table is updated with one record.
B. The program executes successfully and the STUDENT table is NOT updated with any record.
C. A SQLException is thrown as runtime.
D. A NullPointerException is thrown as runtime.

Answer: C

Explanation: line 6에서 자동으로 con이 해제되므로 SQLException 발생한다.

NEW QUESTION 36 Given the code fragments:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public class Book implements Comparator < Book > {

  String name;

  double price;

  public Book() {}

  public Book(String name, double price) {

    this.name = name;

    this.price = price;

  }

  public int compare(Book b1, Book b2) {

    return b1.name.compareTo(b2.name);

  }

  public String toString() {

    return name + ":" + price;

  }

}

Colored by Color Scripter

cs

and

1

2

3

List < Book > books = Arrays.asList(new Book("Beginning with Java", 2), 

                                                          new Book("A Guide to Java Tour", 3));

Collections.sort(books, new Book());

System.out.print(books);

Colored by Color Scripter

cs


What is the result?
A. [A Guide to Java Tour:3.0, Beginning with Java:2.0]
B. [Beginning with Java:2, A Guide to Java Tour:3]
C. A compilation error occurs because the Book class does not override the abstract method compareTo().
D. An Exception is thrown at run time.

Answer: A

Explanation: Collections.sort(books, new Book());는 사전 편찬 순으로 정렬된다.

NEW QUESTION 37
Which statement is true about the DriverManager class?
A. It returns an instance of Connection.
B. it executes SQL statements against the database.
C. It only queries metadata of the database.
D. it is written by different vendors for their specific database.

Answer: A

Explanation: The DriverManager returns an instance of Doctrine\DBAL\Connection which is a wrapper around the underlying driver connection (which is often a PDO instance).

NEW QUESTION 38
Given:

1

2

3

4

5

6

7

8

9

10

11

12

13

public class Vehicle {

    int vId;

    String vName;

    public Vehicle (int vIdArg, String vNameArg){

        this.vId = vIdArg;

        this.vName = vNameArg;

    }

    public int getVId(){ return vId; }

    public String getVName(){ return vName; }

    public String toString() { 

        return vName;

    }

}

Colored by Color Scripter

cs


and the code fragment:

1

2

3

4

5

6

List<Vehicle> vehicle = Arrays.asList(

    new Vehicle(2, "Car"),

    new Vehicle(3, "Bike"),

    new Vehicle(1, "Truck"));

vehicle.stream()//line n1

        .forEach(System.out::print);

cs


Which two code fragments, when inserted at line n1 independently, enable the code to print TruckCarBike?
A. .sorted ((v1, v2) -> v1.getVId() < v2.getVId())
B. .sorted (Comparable.comparing (Vehicle: :getVName)).reversed()
C. .map (v -> v.getVId()).sorted ()
D. .sorted((v1, v2) -> Integer.compare(v1.getVId(), v2.getVid()))
E. .sorted(Comparator.comparing ((Vehicle v) -> v.getVId()))

Answer: D,E

Explanation:
A. .sorted ((v1, v2) -> v1.getVId() < v2.getVId()) //Boolean값이 return됨. 정렬불가
B. .sorted (Comparable.comparing (Vehicle::getVName)).reversed()// comparing 메소드는 Comparator 클래스 메소드이고, reversed 메소드 자체가 없음
C. .map (v -> v.getVId()).sorted () //123 , vid만 필터됨
D. .sorted((v1, v2) -> Integer.compare(v1.getVId(), v2.getVId()))
//Integer.compare는 A=B이면 0, A>B이면 1 A<B이면 -1을 리턴한다
//sorted 안에 사용되었으므로 vid를 기준으로 정렬
E. .sorted(Comparator.comparing ((Vehicle v) -> v.getVId()))

NEW QUESTION 39
Given the code fragment:

1

2

3

4

5

final String str1 = "Java";

StringBuffer strBuf = new StringBuffer("Course");

UnaryOperator<String> u = (str2) -> str1.concat(str2); //line n2

UnaryOperator<String> c = (str3) -> str3.toLowerCase();

System.out.println(u.apply(c.apply(strBuf))); //line n1

cs


What is the result?

A. A compilation error occurs at line n1.
B. courseJava
C. Javacourse
D. A compilation error occurs at line n2.

Answer: A

Explanation: StringBuffer는 String으로 자동 convert 되지 않는다. c.apply(strBuf.toString())으로 바꿔야한다.

NEW QUESTION 40
Given:

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

class Counter extends Thread{

    int i = 10;

    public synchronized void display(Counter obj){

        try{

            Thread.sleep(5);

            obj.increment(this);

            System.out.printIn(i);

        }catch(InterruptedException ex){}

    }

    public synchronized void increment(Counter obj){

        i++;

    }

}

public class Test{

    public static void main(String[] args){

        final Counter obj1 = new Counter();

        final Counter obj2 = new Counter();

        new Thread(new Runnable(){

            public void run() {obj1.display(obj2); }

        }).start();

        new Thread(new Runnable(){

            public void run() {obj2.display(obj1);}

        }).start();

    }

}

Colored by Color Scripter

cs


From what threading problem does the program suffer?
A. race condition
B. deadlock
C. starvation
D. livelock

Answer: B

Explanation: 18,21번째 줄을 보면 두개의 쓰레드가 같이 start되고 같은 자원을 공유하고있음. deadlock발생

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