0% found this document useful (0 votes)
110 views90 pages

JAVA QUESTIONS total list

The document contains a series of programming questions and their correct answers, primarily focused on Java programming concepts such as class structures, method overrides, exception handling, and annotations. Each question is followed by multiple-choice options, with the correct answer indicated for each. The questions cover a range of topics including data types, collections, streams, and security vulnerabilities in code.

Uploaded by

harilavgs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views90 pages

JAVA QUESTIONS total list

The document contains a series of programming questions and their correct answers, primarily focused on Java programming concepts such as class structures, method overrides, exception handling, and annotations. Each question is followed by multiple-choice options, with the correct answer indicated for each. The questions cover a range of topics including data types, collections, streams, and security vulnerabilities in code.

Uploaded by

harilavgs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Question #1

Given:
public class Tester {

public static void main(String[] args) {

int x = 0 , y = 6 for(; x < y ; x ++ , y --) { // line 1

if ( x / 2 ==0) { continue; } System.out.println ( x +"-"+y) ;


}
}
}
What is the result?
A.
2-4
B.
0-6
1-5
2-4
C. 1-5
Most Voted
D.
1-5
2-4
E. The compilation fails due to an error in line 1.
F. 0-6
G. 0-6
2-4

Correct Answer:
C
Question #3

Given:

import java.util.*;

public class Foo {

public List<Integer> foo (Set<CharSequence> m) {...}

}
and

import java.util.*;

public class Bar extends Foo {

//line n1

Which two method definitions at line n1 in the Bar class compile? (Choose two.)
A.
public List<Number> foo(Set<String> m) {...}
B. B
public List<Integer> foo(Set<CharSequence> m) {...}
Most Voted
C. C
public List<Integer> foo(TreeSet<String> m) {...}
Most Voted
D. D
public List<Object> foo(Set<CharSequence> m) {...}
E. E
public ArrayList<Integer> foo(Set<String> m) {...}
F. F
public ArrayList<Number> foo(Set<CharSequence> m) {...}

Correct Answer:
CF

Question #4

Given:

public class Tester (

public static void main(String[] args) { StringBuilder sb = new StringBuilder(5);

sb.append("HOWDY");
36.insert(0,1);

sb.replace(3, 5, "LL");

sb.insert (6, "COW");

sb.delete(2, 7); System.out.println(sb.length());

1
What is the result?
A. A
5
B. B
4
Most Voted
C. C
3
D. D
An exception is thrown at runtime

Correct Answer:
B

Question #5

Given the code fragment:


for(var i = 0; i < 10; i++) {
switch(i % 5) {
case 2:
i += 2*i;
break;
case 3:
i++;
break;
case 1:
case 4:
i++;
continue;
break;
default:
System.out.print(i + " ");
i++;
}
}
What is the result?
A. A
0 8 10
B. B
0
C. C
The code prints nothing.
D. D
049
E. E
08
Most Voted

Correct Answer:
E

Question #6

Given the code fragment:


Locale locale Locale.US;
// line 1
double currency = 1 00.00;
System.out.println(formatter. format (currency));
You want to display the value of currency as $100.00.
Which code inserted on line 1 will accomplish this?
A. A
NumberFormat formatter = NumberFormat.getInstance(locale).getCurrency();
B. B
NumberFormat formatter = NumberFormat.getCurrency(locale);
C. C
NumberFormat formatter = NumberFormat.getInstance(locale);
D. D
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
Most Voted

Correct Answer:
A

Question #7

Which three initialization statements are correct? (Choose three.)


A. A
int[][][] e = {{1,1,1},{2,2,2}};
B. B
short sh = (short)’A’;
Most Voted
C. C
float x = 1f;
Most Voted
D. D
byte b = 10;
char c = b;
E. E
String contact# = “(+2) (999) (232)”;
F. F
int x = 12_34;
Most Voted
G. G
boolean false = (4 != 4);

Correct Answer:
CBF

Question #8

Your organization makes mlib.jar available to your cloud customers. While working
on a new feature for mlib.jar, you see that the customer visible method public void
enableService(String hostName, String portNumber) executes this code fragment
try {
accessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
transportSocket = new Socket(hostname, portNumber);
return null;
});
}
and you see this grant is in the security policy file:
grant codebase "file:${mlib.home}/j2se/home/mlib.jar" {
permission java.io.SocketPermission "*", "connect";
};
What security vulnerability does this expose to your cloud customer's code?
A. A
privilege escalation attack against the OS running the customer code
Most Voted
B. B
SQL injection attack against the specified host and port
C. C
XML injection attack against any mlib server
D. D
none because the customer code base must also be granted SocketPermission
E. E
denial of service attack against any reachable machine

Correct Answer:
B

Question #9

Given:

public class Tester {


public static void main(String[] args) {
Person p = new Person("Joe");
checkPerson(p);
System.out.println(p);
p = null;
System.out.println(p);
}
and
public static Person checkPerson(Person p) {
if (p == null) {
p = new Person("Mary");
} else {
p = null;
}
return p;
}
}
What is the result?
A. A
Joe -
null
Most Voted
B. B
null
Mary
C. C
Joe -
Marry
D. D
null
null

Correct Answer:
A

Question #10

Given:
List<String> list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
List<String> list2 = Collections.unmodifiableList(list1);
list1.add("C");
System.out.println(list1);
System.out.println(list2);
What is the result?
A. A
[A, B, C]
followed by an exception thrown on line 11.
B. B
[A, B, C]
[A, B]
C. C
[A, B, C]
[A, B, C]
Most Voted
D. D
On line 9, an exception is thrown at run time.

Correct Answer:
C

Question #11

Which module-info.java is correct for a service provider for a print service defined in
the PrintServiceAPI module?
A. A
module PrintServiceProvider {
requires PrintServiceAPI;
exports org.printservice.spi;
}
B. B
module PrintServiceProvider {
requires PrintServiceAPI;
provides org.printservice.spi.Print with
com.provider.PrintService;
}
Most Voted
C. C
module PrintServiceProvider {
requires PrintServiceAPI;
uses com.provider.PrintService;
}
D. D
module PrintServiceProvider {
requires PrintServiceAPI;
exports org.printservice.spi.Print with
com.provider.PrintService;
}

Correct Answer:
A

Question #12

Given the code fragment:


public static void main(String[] args) {
var symbols = List.of("USD", "GBP", "EUR", "CNY");
var exchangeRate = List.of(1.0, 1.3255, 1.1969, 0.1558094);

var map1 = IntStream.range(0, Math.min(symbols.size(), exchangeRate.size()))


.boxed()
.collect(Collectors.toMap(i -> symbols.get(i), i -> 1.0 / exchangeRate.get(i)));

var map2 = map1.entrySet().stream()


.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
LinkedHashMap::new));

map2.forEach((k, v) -> System.out.printf("%s -> %.2f%n", k, v));


}
What is the result?
A. A
EUR -> 0.84 -

GBP -> 0.75 -

USD -> 1.00 -


CNY -> 6.42
B. B
The compilation fails.
C. C
CNY -> 6.42 -

EUR -> 0.84 -

GBP -> 0.75 -


USD -> 1.00
Most Voted
D. D
USD -> 1.00 -

GBP -> 0.75 -

EUR -> 0.84 -


CNY -> 6.42

Correct Answer:
B

Question #13

Why would you choose to use a peek operation instead of a forEach operation on a
Stream?
A. A
to process the current item and return void
B. B
to remove an item from the end of the stream
C. C
to process the current item and return a stream
Most Voted
D. D
to remove an item from the beginning of the stream

Correct Answer:
C
Question #14

Given:
import java.io.*;
public class Tester {
public static void main(String[] args) {
try {
doA();
doB();
} catch (IOException e) {
System.out.print("c");
return;
} finally {
System.out.print("d");
}
System.out.print("e");
}

private static void doA() {


System.out.print("a");
if (false) {
throw new IndexOutOfBoundsException();
}
}

private static void doB() throws FileNotFoundException {


System.out.print("b");
if (true) {
throw new FileNotFoundException();
}
}
}
What is the result?
A. A
abcd
Most Voted
B. B
The compilation fails.
C. C
adf
D. D
abd
E. E
abdf
Correct Answer:
A
Question #16

Given:
@Repeatable(Meals.class)
@Target(ElementType.TYPE)
@interface Meal {
String starter() default "";
String mainCourse();
String dessert() default "";
}
and
@Target(ElementType.TYPE)
public @interface Meals {
Meal[] value();
}

Which two are valid usages of the annotation? (Choose two.)


A. A
@Meal(mainCourse=”pizza”)
@Meal(dessert=”pudding”)
public class Main {
}
B. B
@Meal(mainCourse=null)
public class Main {
}
C. C
@Meal(starter=”snack”, dessert=”ice cream”)
public class Main {
}
D. D
@Meal(mainCourse=”pizza”)
@Meal(mainCourse=”salad”)
public class Main {
}
Most Voted
E. E
@Meal(mainCourse=”pizza”, starter=”snack”, dessert=”pudding”) public class Main {
}
Most Voted
Correct Answer:
BE

Question #17

Given:
public enum Season {
WINTER('w'), SPRING('s'), SUMMER('h'), FALL('f');
char c;
private Season(char c) {
this.c = c;
}
}
and the code fragment:
public static void main(String[] args) {
Season[] sA = Season.values(); // line n1
}
Which three code fragments, at line n1, prints SPRING? (Choose three.)
A. A
System.out.println(Season.valueOf(“SPRING”).ordinal());
B. B
System.out.println(Season.values(1));
C. C
System.out.println(Season.SPRING);
Most Voted
D. D
System.out.println(Season.valueOf(“SPRING”));
Most Voted
E. E
System.out.println(Season.valueOf(‘s’));
F. F
System.out.println(sA[0]);
G. G
System.out.println(sA[1]);
Most Voted

Correct Answer:
BCE

Hide Answer
uestion Discussion12 ChatGPT Statistics
Share
Question #18

Given:
public class DNAsynth {
int aCount;
int tCount;
int cCount;
int gCount;

DNAsynth(int a, int tCount, int c, int g){


// line 1
}

int setCCount(int c) {
return c;
}

void setGCount(int gCount) {


this.gCount = gCount;
}
}
Which two lines of code when inserted in line 1 correctly modifies instance
variables? (Choose two.)
A. A
cCount = setCCount(c);
B. B
setCCount(c) = cCount;
C. C
setGCount(g);
Most Voted
D. D
tCount = tCount;
E. E
aCount = a;
Most Voted

Correct Answer:
BD

Question #19
Given:
Given:
/proj/msg/messages.properties file:
message=Hello {0}, regards {1}

and

/proj/msg/messages_ja_JP.properties file:
message=こんにちは {0}, しくお願いします {1}

and

/proj/msg/Test.java class:

package msg;
public class Test {
public static void main(String[] args) {
// line 1
System.out.println(message);
}
}
and

and

You want to print the message こんにちは Joe, しくお願いします, Jane.


Which code inserted on line 1 will accomplish this?
A. A
ResourceBundle msg = ResourceBundle.getBundle(“/proj/msg/messages”, new
Locale(“ja”,“JP”));
Object[] names = “Joe”, “Jane”);
String message = MessageFormat.format(msg.getString(“message”),names);
B. B
ResourceBundle msg = ResourceBundle.getBundle(“msg.messages”, Locale.JAPAN);
Object[] names = “Joe”, “Jane”);
String message = MessageFormat.format(msg.getString(“message”),names);
C. C
Locale.setDefault(Locale.JAPAN);
ResourceBundle messages = ResourceBundle.getBundle(“messages”);
String message = MessageFormat.format(msg.getString(“message”),“Joe”,“Jane”);
D. D
ResourceBundle msg = ResourceBundle.getBundle(“messages”, Locale.JAPAN);
String[] names = “Joe”, “Jane”);
String message = MessageFormat.format(msg.getString(“message”),names);
Most Voted
Correct Answer:
D

Question #20

Given:
import java.sql.Timestamp;
public class Test {
public static void main(String[] args) {
Timestamp ts = new Timestamp(1);
}
}
and the commands:
javac Test.java
jdep=summary Test.class
What is the result on execution of these commands?
A. A
Test.class - > java.sql -> java.base
B. B
On execution, the jdeps command displays an error.
C. C
Test.class -> java.base -
Test.class - > java.sql
D. D
Test.class -> java.base -

Test.class - > java.sql -


java.sql -> java.base
Most Voted

Correct Answer:
C
Question #21

A company has an existing Java 8 jar file, sales-app-1.1.1.jar, that uses several
Apache open source jar files that have not been modularized.
commons-beanutils-1.9.3.jar
commons-collections4-4.2.jar
(Automatic-Module-Name: org.apache.commons.collections4)
commons-lang3-3.8.1.jar
(Automatic-Module-Name: org.apache.commons.lang3)
commons-text-1.3.jar
(Automatic-Module-Name: org.apache.commons.text)
Which module-info.java file should be used to convert sales-app-1.1.jar to a module?
A. A
module com.company.sales_app {
requires commons.beanutils;
requires org.apache.commons.collections4;
requires org.apache.commons.lang3;
requires org.apache.commons.text;
}
Most Voted
B. B
module com.company.sales_app {
requires org.apache.commons.beanutils;
requires org.apache.commons.collections4;
requires org.apache.commons.lang3;
requires org.apache.commons.text;
}
C. C
module com.company.sales_app {
requires commons.beanutils;
requires commons.collections4;
requires commons.lang3;
requires commons.text;
}
D. D
module com.company.sales_app {
requires commons.beanutils-1.9.3;
requires commons.collections4-4.2;
requires commons.lang3-3.8.1;
requires commons.text-1.3;
}

Correct Answer:
A

Question #22

Which two are valid statements? (Choose two.)


A. A
BiPredicate<Integer, Integer> test = (final Integer x, var y) -> (x.equals(y));
B. B
BiPredicate<Integer, Integer> test = (var x, final var y) -> (x.equals(y));
Most Voted
C. C
BiPredicate<Integer, Integer> test = (Integer x, final var y) -> (x.equals(y));
D. D
BiPredicate<Integer, Integer> test = (final var x, y) -> (x.equals(y));
E. E
BiPredicate<Integer, Integer> test = (Integer x, final Integer y) -> (x.equals(y));
Most Voted

Correct Answer:
CE

Question #23

Given:
public class Person {
private String name = "Green";
public void setName(String name) {
String title = "Mr. ";
name = title + name;
}
public String toString() {
return name;
}
}
and
public class Test {
public static void main(String args[]) {
Person p = new Person();
p.setName("Blue");
System.out.println(p);
}
}
What is the result?
A. A
Mr. Green
B. B
Green
Most Voted
C. C
An exception is thrown at runtime.
D. D
Mr. Blue

Correct Answer:
C

Question #24

Given:
import java.util.function.BiFunction;
public class Pair<T> {
final BiFunction<T, T, Boolean> validator;
T left = null;
T right = null;
private Pair<T> validator=null;

Pair(BiFunction<T, T, Boolean> v, T x, T y) {
validator = v;
set(x, y);
}
void set(T x, T y) {
if(!validator.apply(x, y)) throw new IllegalArgumentException();
setLeft(x);
setRight(y);
}
void setLeft(T x) {
left = x;
}
void setRight(T y) {
right = y;
}
final boolean isValid() {
return validator.apply(left, right);
}
}
It is required that if p instanceof Pair then p.isValid() returns true.
Which is the smallest set of visibility changes to insure this requirement is met?
A. A
left, right, setLeft, and setRight must be private.
B. B
setLeft and setRight must be protected.
C. C
left and right must be private.
Most Voted
D. D
isValid must be public.

Correct Answer:
D
Question #25

char[] characters = new char[100];


try (FileReader reader = new FileReader("file_to_path");) {
// line 1
System.out.println(String.valueOf(characters));
} catch (IOException e) {
e.printStackTrace();
}
You want to read data through the reader object.
Which statement inserted on line 1 will accomplish this?
A. A
characters = reader.read();
B. B
reader.readLine();
C. C
characters.read();
D. D
reader.read(characters);
Most Voted

Correct Answer:
B

Question #26

Given:
package com.foo;
public class Foo {
static final int A = 0;
public static final int B = 0;
private static final int C = 0;
int d = 0;
protected int e = 0;
public int f = 0;
private int g = 0;
public void foo(int h) {
int i = 0;
}
package com.foo.bar;
public class Bar extends com.foo.Foo {
@Override
public void foo(int j) {
// line 1
}
} (Choose four.)
A. A
e
Most Voted
B. B
f
Most Voted
C. C
A
D. D
j
Most Voted
E. E
d
F. F
c
G. G
i
H. H
B
Most Voted
I. I
h
J. J
g

Correct Answer:
CFHJ

Hide Answer
uestion Discussion5 ChatGPT Statistics
Share
Question #27

Which code fragment represents a valid Comparator implementation?


A. A
B. B

C. C

Most Voted
D. D

Correct Answer:
A

Hide Answer
uestion Discussion15 ChatGPT Statistics
Share
Question #28

Given the code fragment:


public class Main {
public static void main(String[] args) {
List<Integer> list = new CopyOnWriteArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(5);
CyclicBarrier barrier = new CyclicBarrier(2, () -> System.out.print(list));

IntStream.range(0, 5).forEach(n -> executorService.execute(() -> {


try {
list.add(n);
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
System.out.println("Exception");
}
}));
executorService.shutdown();
}
}
Which statement is true?
A. A
It never finishes.
Most Voted
B. B
The action of CyclicBarrier is called five times.
C. C
It finishes without any exception.
D. D
Threads in executorService execute for each of the two threads.

Correct Answer:
A

Hide Answer
uestion Discussion10 ChatGPT Statistics
Share
Question #29

Given:
public interface Rectangle {
default double calculateSurfaceArea(double l, double w) {
return l * w;
}
}

public interface Ellipse {


default double calculateSurfaceArea(double majorR, double minorR) {
return Math.PI * majorR * minorR;
}
}

public class Cylinder implements Rectangle, Ellipse {


public double calculateSurfaceArea(double l, double w, double majorR, double
minorR) {
double rectangle = Rectangle.super.calculateSurfaceArea(l, w);
double ellipseArea = Ellipse.super.calculateSurfaceArea(majorR, minorR);
return rectangle + ellipseArea / 2;
}
}
What prevents this code from compiling?
A. A
The calculateSurfaceArea method within Cylinder must be declared default.
B. B
Cylinder is not properly calling the Rectangle and Ellipse interfaces’
calculateSurfaceArea methods.
C. C
Cylinder requires an implementation of calculateSurfaceArea with two parameters.
Most Voted
D. D
The calculateSurfaceArea method within Rectangle and Ellipse requires a public
access modifier.

Correct Answer:
B

Question #30

Given a Member class with fields for name and yearsMembership, including getters
and setters and a print method, and a list of clubMembers members:
String testName = "smith";
int testMembershipLength = 5;
long matches = clubMembers
.peek(new Consumer<Member>() {
@Override
public void accept(Member m) {
m.print();
}
})
.filter(m -> m.getYearsMembership() >= testMembershipLength)
.map(m -> testName.compareToIgnoreCase(m))
.filter(a -> a > 0)
.count();
System.out.println(matches);
Which two Stream methods can be changed to use method references? (Choose
two.)
A. A
.filter(Integer::equals(0))
B. B
.map(testName::compareToIgnoreCase)
Most Voted
C. C
.filter(Member::getYearsMembership() >= testMembershipLength)
D. D
.peek(Member::print)
Most Voted

Correct Answer:
BC

Question #31

Given:
Path p1 = Paths.get(“/scratch/exam/topsecret/answers”);
Path p2 = Paths.get(“/scratch/exam/answers/temp.txt”);
Path p3 = Paths.get(“/scratch/answers/topsecret”);
Which two statements print ..\..\..\answers\topsecret? (Choose two.)
A. A
System.out.print(p3.relativize(p1));
B. B
System.out.print(p2.relativize(p3));
Most Voted
C. C
System.out.print(p1.relativize(p3));
Most Voted
D. D
System.out.print(p3.relativize(p2));
E. E
System.out.print(p1.relativize(p2));
F. F
System.out.print(p2.relativize(p1));

Correct Answer:
AC

Hide Answer
uestion Discussion10 ChatGPT Statistics
Share
Question #32

Given the code fragment:


class Classes implements Serializable {
String id;
}
class Person {
String name;
transient String address;
}
class Student extends Person implements Serializable {
String studentNo;
Classes classes = new Classes();
}
Which fields are serialized in a Student object?
A. A
studentNo and classes
B. B
studentNo and name
C. C
studentNo, classes and name
Most Voted
D. D
studentNo, classes, name, and address

Correct Answer:
A

Hide Answer
uestion Discussion5 ChatGPT Statistics
Share
Question #33

Given:
public class Main {
public static void main(String[] args) {
List<String> fruits = List.of("banana", "orange", "apple", "lemon");
Stream<String> s1 = fruits.stream();
Stream<String> s2 = s1.peek(i -> System.out.print(i + " "));
System.out.println("---");
Stream<String> s3 = s2.sorted();
Stream<String> s4 = s3.peek(i -> System.out.print(i + " "));
System.out.println("---");
String strFruits = s4.collect(Collectors.joining(","));
}
}
What is the output?
A. A
banana orange apple lemon
-----
apple banana lemon orange
-----
B. B
-----
banana orange apple lemon
-----
apple banana lemon orange
C. C
-----
-----
D. D
-----
-----
banana orange apple lemon apple banana lemon orange
Most Voted
E. E
banana orange apple lemon apple banana lemon orange
-----
-----

Correct Answer:
D

Hide Answer
uestion Discussion4 ChatGPT Statistics
Share
Question #34

public class Foo {


public void foo(Collection arg) {
System.out.println("Bonjour le monde!");
}
}

and

public class Bar extends Foo {


public void foo(List arg) {
System.out.println("Hello world!");
}

public static void main(String... args) {


List<String> li = new ArrayList<>();
Collection<String> co = li;
Bar b = new Bar();
b.foo(li);
b.foo(co);
}
}

What is the output?


A. A
Bonjour le monde!
Bonjour le monde!
B. B
Hello world!
Hello world!
C. C
Hello world!
Bonjour le monde!
Most Voted
D. D
Bonjour le monde!
Hello world!

Correct Answer:
C

Hide Answer
uestion Discussion4 ChatGPT Statistics
Share
Question #35

Given:
import java.util.List;
import java.util.Optional;

public class Test {


public static void main(String[] args) {
List<Item> items = List.of(
new Item("A", 10),
new Item("B", 2),
new Item("C", 12),
new Item("D", 5),
new Item("E", 6)
);
double avg = items.stream().mapToInt(i -> i.amount).average().orElse(0.0);
Optional<Item> item = items.parallelStream()
.filter(i -> i.amount < avg).findAny();

System.out.println(item.orElseThrow());
}
}

class Item {
public String name;
public int amount;

public Item(String name, int amount) {


this.name = name;
this.amount = amount;
}

@Override
public String toString() {
return "Name: " + name + ", Amount: " + amount;
}
}
What is true?
A. A
A NoSuchElementException is thrown at run time.
B. B
The compilation fails.
C. C
This should print the same result each time the program runs.
D. D
This may not print the same result each time the program runs.
Most Voted

Correct Answer:
D
Question #36

Given:
public class Main {
public static void main(String[] args) {
String[] furnitures = {"Door", "Window", "Chair"};
var sb = new StringBuilder();
for (var i = 0; i < furnitures.length; i++) {
var index = i + 1;
sb.append(index);
sb.append(")");
sb.append(furnitures[i].charAt(i));
sb.append(" ");
if (index < furnitures.length) {
sb.append(" ");
}
}

sb.delete(sb.length() - 2, sb.length() - 1);


sb.insert(0, '[').insert(sb.length(), ']');
System.out.println(sb);
}
}

What is the result?


A.
What is the result?
A. A
The compilation fails.
Most Voted
B. B
[0). D, | 1). i, | 2). a]
C. C
[). o, | 1). a, | 2).]
D. D
[0). o, | 1). i, | 2). r]
E. E
ArrayIndexOutOfBounds Exception is thrown at runtime.

Correct Answer:
A

Hide Answer
uestion Discussion5 ChatGPT Statistics
Share
Question #37

Given:
public class Tester {
public static int reduce(int x) {
int y = 4;
class Computer {
int reduce(int x) {
return x - y--;
}
}
Computer a = new Computer();
return a.reduce(x);
}

public static void main(String[] args) {


System.out.print(reduce(1));
}
}
What is the result?
A. A
An exception is thrown at runtime.
B. B
-3
C. C
-2
D. D
The compilation fails.
Most Voted

Correct Answer:
D

Hide Answer
uestion Discussion7 ChatGPT Statistics
Share
Question #38

Given the code fragment:


public class Main { // line 1
private int count = 0; // line 2
public static void main(String[] args) {
Main test = new Main();
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
service.submit(() -> {
for (int j = 0; j < 10000; j++) { // line 3
test.count++;
}
});
}
service.shutdown();
}
}
You must make the count variable thread safe.
Which two modifications meet your requirement? (Choose two.)
A. A
replace line 2 with public static synchronized void main(String[] args) {
B. B
replace line 1 with private volatile int count = 0;
C. C
replace line 3 with
synchronized(test) {
test.count++;
}
Most Voted
D. D
replace line 1 with private AtomicInteger count = new AtomicInteger(0); and replace
line 3 with test.count.incrementAndGet();
Most Voted
E. E
replace line 3 with
synchronized(test.count) {
test.count++;
}

Correct Answer:
DE

Hide Answer
uestion Discussion4 ChatGPT Statistics
Share
Question #39

Given the code fragment:


// Line 1
public class Computator<N extends Number, C extends Collection<N>> { // Line 2
public double sum(C collection) { // Line 3
double sum = 0.0; // Line 4
for (N n : collection) {
sum += n.doubleValue();
}
return sum;
}

public static void main(String... args) { // Line 5


var numbers = List.of(5, 4, 6, 3, 7, 2, 8, 1, 9);
Computator<Integer, List<Integer>> c = new Computator<>();
System.out.println(c.sum(numbers));
}
}
Which action enables Computator class to compile?
A. A
change Line 1 to add throws NumberFormatException
B. B
change Line 3 to Double sum = 0.0;
C. C
change Line 5 to List<Double> numbers = List.of(5, 4, 6, 3, 7, 2, 8, 1, 9);
D. D
change Line 2 to public Double sum ( C collection) {
Most Voted
E. E
change Line 4 to for (Double n : collection) {

Correct Answer:
D

Hide Answer
uestion Discussion9 ChatGPT Statistics
Share
Question #40

Given the code fragment:


char d = 100, e = 'e'; // line 1
int x = d; // line 2
int y = (int) e; // line 3
System.out.println((char) x + (char) y); // line 4
What is the result?
A. A
The compilation fails due to an error in line 2.
B. B
201
C. C
de
D. D
203
E. E
The compilation fails due to an error in line 3.
Most Voted
F. F
The compilation fails due to an error in line 1.

Correct Answer:
E

Question #41

Given the code fragment:


public void foo(Function<Integer, String> fun) {...}
Which two compile? (Choose two.)
A. A
foo( n -> Integer.toHexString(n) )
Most Voted
B. B
foo( toHexString )
C. C
foo( n -> n + 1 )
D. D
foo( int n -> Integer.toHexString(n) )
E. E
foo( n -> Integer::toHexString )
F. F
foo( Integer::toHexString )
Most Voted
G. G
foo( n::toHexString )
H. H
foo( (int n) -> Integer.toHexString(n) )

Correct Answer:
AC

Hide Answer
uestion Discussion4 ChatGPT Statistics
Share
Question #42
Which declaration of an annotation type is legal?
A. A
@interface Author {
String name() default “”;
String date();
}
Most Voted
B. B
@interface Author extends Serializable {
String name() default “”;
String date();
}
C. C
@interface Author {
String name() default null;
String date();
}
D. D
@interface Author {
String name();
String date;
}
E. E
@interface Author {
String name();
String date default “”;
}

Correct Answer:
A

Hide Answer
uestion Discussion8 ChatGPT Statistics
Share
Question #43

Given:
public interface APIInterface (
and
public default void process() (System.out.println ("Process() called 1."); }
public abstract class AbstractAPI {
and
public abstract void process();}
public class Api Impl extends AbstractAPI implements APIInterface {
public void process();
}

System.out.println("Process() called 2.");}


public static void main(String[] args) {
var impl = new ApiImpl();
impl.process();

}}

What is the result?


A. A
The program prints Process()called 2.
Most Voted
B. B
A java.lang.NoSuchMethodException is thrown.
C. C
The program prints Process()called 1.
D. D
A java.lang.IllegalAccessException is thrown.
E. E
The compilation fails.

Correct Answer:
E

Hide Answer
uestion Discussion29 ChatGPT Statistics
Share
Question #44

Given:
interface MyInterface1 {
public int method() throws Exception;
private void pMethod() { /* an implementation of pMethod */ }
}

interface MyInterface2 {
public static void sMethod() { /* an implementation of sMethod */ }
private boolean equals();
}

interface MyInterface3 {
public void method();
}

interface MyInterface4 {
public void method(String str);
}

interface MyInterface5 {
public static void sMethod();
public void method(String str);
}

Which two interfaces can be used in lambda expressions? (Choose two.)


A. A
B. MyInterface4
C. B
Which two interfaces can be used in lambda expressions? (Choose two.)
A. A
MyInterface4
B. B
MyInterface5
C. C
MyInterface1
Most Voted
D. D
MyInterface3
Most Voted
E. E
MyInterface2

Correct Answer:
DE

Hide Answer
uestion Discussion11 ChatGPT Statistics
Question #45

Given:
class Super {
static String greeting() { return "Good Night"; }
String name() { return "Harry"; }
}

class Sub extends Super {


static String greeting() { return "Good Morning"; }
String name() { return "Potter"; }
}

class Test {
public static void main(String[] args) {
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name());
}
}

What is the result?


A.
Good Night, Harry

B.

What is the result?


A. A
Good Night, Harry
B. B
Good Morning, Potter
C. C
Good Morning, Harry
D. D
Good Night, Potter
Most Voted

Correct Answer:
B
Question #46

Question #46

public class Tester {


private static int i;
private static int[] primes = {2, 3, 5, 7};
private static String result = "";
public static void main(String[] args) {
while (i < primes.length) {
if (i == 3) {
break;
}
i++;
result += primes[i];
}
System.out.println(result);
}
}

What is the result?


A. A
357
Most Voted
B.
What is the result?
A. A
357
Most Voted
B. B
35
C. C
235
D. D
2357
E. E
An ArrayIndexOutOfBoundsException is thrown at runtime.

Correct Answer:
A

Hide Answer
uestion Discussion7 ChatGPT Statistics
Share
Question #47

Given:
Given:
class Super {
final int num; // line n1
public Super(int num) {
this.num = num;
}
final void method() {
System.out.println("Output from Super");
}
}
class Sub extends Super {
int num; // line n2
Sub(short num) { // line n3
super(num);
}
protected void method() { // line n4
System.out.println("Output from Sub");
}
}

line n3
Which line of code results in a compilation error?
A. A
line n1
B. B
line n3
C. C
line n2
D. D
line n4
Most Voted

Correct Answer:
D

Hide Answer
uestion Discussion8 ChatGPT Statistics
Share
Question #48

Given the code fragment:


public class Main {
public static void main(String... args) {
List<String> list1 = new ArrayList<>(
List.of("Earth", "Wind", "Fire"));
List<String> list2 = List.copyOf(list1);
list2.sort((String item1, String item2) -> item1.compareTo(item2));
System.out.println(list2.equals(list1));
}
}

What is the result?


A. A
A java.lang.NullPointerException is thrown.
B. B
false
C. C
A java.lang.UnsupportedOperationException is thrown.
Most Voted
D. D
true

Correct Answer:
A

Hide Answer
uestion Discussion7 ChatGPT Statistics
Share
Question #49

Given:
public class ExSuper extends Exception {
private final int eCode;
public ExSuper(int eCode, Throwable cause) {
super(cause);
this.eCode = eCode;
}

public ExSuper(int eCode, String msg, Throwable cause) {


this.eCode = eCode;
}

public String getMessage() {


return this.eCode + ": " + super.getMessage() + " " + this.getCause().getMessage();
}
}

public class ExSub extends ExSuper {


public ExSub(int eCode, String msg, Throwable cause) {
super(eCode, msg, cause);
}
and the code fragment:
try {
String param1 = "Oracle";
if (param.equalsIgnoreCase("oracle")) {
throw new ExSub(9001, "APPLICATION ERROR-9001", new
FileNotFoundException("MyFile.txt"));
}
throw new ExSub(9001, new FileNotFoundException("MyFile.txt")); // Line 1
} catch (ExSub ex) {
System.out.println(ex.getMessage());
}
What is the result?
A. A
9001: java.io.FileNotFoundException: MyFile.txt-MyFile.txt
B. B
9001: APPLICATION ERROR-9001-MyFile.txt
9001: java.io.FileNotFoundException: MyFile.txt-MyFile.txt
C. C
9001: APPLICATION ERROR-9001-MyFile.txt
Most Voted
D. D
Compilations fails at Line 1.

Correct Answer:
D

Hide Answer
uestion Discussion8 ChatGPT Statistics
Share
Question #50

Which two interfaces are considered to be functional interfaces? (Choose two.)


A. A
@FunctionalInterface
interface InterfaceC {
public boolean equals(Object o);
int breed(int x);
int calculate(int x, int y);
}
B. B
@FunctionalInterface
interface InterfaceD {
int breed(int x);
}
Most Voted
C. C
@FunctionalInterface
interface InterfaceE {
public boolean equals(int i);
int breed(int x);
}
D. D
interface InterfaceA {
int GERM = 13;
public default int getGERM() { return GERM; }
}
E. E
interface InterfaceB {
int GERM = 13;
public default int getGERM() { return get(); }
private int get() { return GERM; }
public boolean equals(Object o);
int breed(int x);
}
Most Voted

Correct Answer:
AC -

Question #51

Which code fragment does a service use to load the service provider with a Print
interface?
A. A
private java.util.ServiceLoader loader = ServiceLoader.load(Print.class)
Most Voted
B. B
private Print print = new com.service.Provider.PrintImpl();
C. C
private java.util.ServiceLoader loader = new java.util.ServiceLoader<>()
D. D
private Print print = com.service.Provider.getInstance();

Correct Answer:
A

Hide Answer
uestion Discussion6 ChatGPT Statistics
Share
Question #52

Given:

Given:

public final class X {


private String name;
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}
public String toString() { return getName(); }
}

and

public class Y extends X {


public Y(String name) {
super();
setName(name);
}

public static void main(String... args) {


Y y = new Y("HH");
System.out.println(y);
}
}

What is the result?


A. A
null
B. B
HH
C. C
Y@<>
D. D
The compilation fails
Most Voted
Correct Answer:
D

Hide Answer
uestion Discussion7 ChatGPT Statistics
Share
Question #53

Given:

class Scope {
static int myint=666;
public static void main(String[] args) {
int myint = myint;
System.out.println(myint);
}
}

Which is true?
A. A
Code compiles but throws a runtime exception when run.
B. B
It prints 666.
C. C
The code compiles and runs successfully but with a wrong answer (i.e., a bug).
D. D
The code does not compile successfully.
Most Voted

Correct Answer:
A

Hide Answer
uestion Discussion9 ChatGPT Statistics
Share
Question #54

Given:

package test.t1;
public class A {
public int x = 42; // line 1
protected A() {}
}

and

package test.t2;
import test.t1.*;
public class B extends A { // line 2
int x = 17; // line 3
public B() { super(); }
}

and

package test;
import test.t1.*;
import test.t2.*;
public class Tester {
public static void main(String[] args) { // line 4
A obj = new B(); // line 5
System.out.println(obj.x); // line 5
}
}

What is the result?


A. A
42

and

and

What is the result?


A. A
42
Most Voted
B. B
The compilation fails due to an error in line 1.
C. C
The compilation fails due to an error in line 2.
D. D
The compilation fails due to an error in line 3.
E. E
The compilation fails due to an error in line 4.
F. F
The compilation fails due to an error in line 5.
G. G
17

Correct Answer:
G

Hide Answer
uestion Discussion9 ChatGPT Statistics
Share
Question #55

Given:

// line 1
var fruits = List.of("apple", "orange", "banana", "lemon");
fruits.forEach(function);

Which statement on line 1 enables this code to compile?


A. A
Consumer function = (String f) -> (System.out.println(f);};
Most Voted
B. B
Supplier function = () -> fruits.get (0);
C. C
Predicate function = a -> a.equals("banana");
D. D
Function function = x -> x.substring(0,2);

Correct Answer:
D
Question #56

Given:
public class Option {
public static void main(String[] args) {
System.out.println("Ans : " + convert("a").get());
}

private static Optional<Integer> convert(String s) {


try {
return Optional.of(Integer.parseInt(s));
} catch (Exception e) {
return Optional.empty();
}
}
}

What is the result?


A. A
A java.util.NoSuchElementException is thrown at run time.

Most Voted

What is the result?


A. A
A java.util.NoSuchElementException is thrown at run time.
Most Voted
B. B
Ans : a
C. C
The compilation fails.
D. D
Ans :

Correct Answer:
A

Hide Answer
uestion Discussion13 ChatGPT Statistics
Share
Question #57

Given:

public class Point {


@JsonField(type=JsonField.Type.STRING, name="name")
private String _name;

@JsonField(type=JsonField.Type.INT)
private int x;

@JsonField(type=JsonField.Type.INT)
private int y;
}

What is the correct definition of the JsonField annotation that makes the Point class
compile?
A. A

B. B

C. C

D. D

Most Voted

Correct Answer:
C

Hide Answer
uestion Discussion9 ChatGPT Statistics
Share
Question #58

Given:

public class Test {


public static void main(String[] args) {
Anotherclass ac = new Anotherclass();
SomeClass sc = new Anotherclass();
sc.methodA();
ac.methodA();
}
}

class SomeClass {
public void methodA() {
System.out.println("SomeClass#methodA()");
}
}

class Anotherclass extends SomeClass {


public void methodA() {
System.out.println("AnotherClass#methodA()");
}
}

What is the result?


A. A
AnotherClass#methodA()
SomeClass#methodA()
B. B
A ClassCastException is thrown at runtime.
C. C
The compilation fails.
Most Voted
D. D
AnotherClass#methodA()
AnotherClass#methodA()
E. E
SomeClass#methodA()
AnotherClass#methodA()
F. F
SomeClass#methodA()
SomeClass#methodA()

Correct Answer:
B

Hide Answer
uestion Discussion5 ChatGPT Statistics
Share
Question #59

Given:

public interface A {
public Iterable a();
}
public interface B extends A {
public Collection a();
}
public interface C extends A {
public Path a();
}
public interface D extends B, C {
}

Why does D cause a compilation error?


A. A
D does not define any method.
B. B
D inherits a() only from C.
C. C
D inherits a() from B and C but the return types are incompatible.
Most Voted
D. D
D extends more than one interface.

Correct Answer:
C

Hide Answer
uestion Discussion3 ChatGPT Statistics
Share
Question #60

Your organization provides a cloud server to your customer to run their Java code.
You are reviewing the changes for the next release and you see this change in one of
the config files:

old: JAVA_OPTS="$JAVA_OPTS -Xms8g -Xmx8g"


new: JAVA_OPTS="$JAVA_OPTS -Xms8g -Xmx8g -noverify"

Which is correct?
A. A
You accept the change because -noverify is necessary for your code to run with the
latest version of Java.
B. B
You reject the change because -Xms8g -Xmx8g uses too much system memory.
C. C
You accept the change because -noverify is a standard option that has been
supported since Java 1.0.
D. D
You reject the change because -noverify is a critical security risk.
Most Voted

Correct Answer:
D
Question #61

Given:

public interface Worker {


public void doProcess();
}

and

public class HardWorker implements Worker {


public void doProcess() {
System.out.println("doing things");
}
}

and

public class Cheater implements Worker {


public void doProcess() { }
}

public class Main<T extends Worker> extends Thread { // Line 1


private List<T> processes = new ArrayList<>(); // Line 2
public void addProcess(HardWorker w) { // Line 3
processes.add(w);
}

public void run() {


processes.forEach((p) -> p.doProcess());
}
}

What needs to change to make these classes compile and still handle all types of
Interface Worker?
A. A
Replace Line 3 with public void addProcess (Worker w) {.
B. B
Replace Line 1 with public class Main extends Thread {.
C. C
Replace Line 2 with private List processes = new ArrayList<>();.
D. D
Replace Line 3 with public void addProcess(T w) {.
Most Voted

Correct Answer:
D

Hide Answer
uestion Discussion9 ChatGPT Statistics
Share
Question #62

Given:

public class Test{


public void process(byte v){
System.out.println("Byte value " +v);
}

public void process(short v){


System.out.println("Short value " +v);
}

public void process(Object v){


System.out.println("Object value " +v);
}

public static void main(String[] args) {


byte x = 12;
short y = 13;
new Test().process(x+y); // line 1
}
}

What is the output?


A. A
Short value 25
B. B
The compilation fails due to an error in line 1.
C. C
Byte value 25
D. D
Object value 25
Most Voted

Correct Answer:
B

Hide Answer
uestion Discussion5 ChatGPT Statistics
Share
Question #63

Given:
var fruits = List.of("apple", "orange", "banana", "lemon");
Optional<String> result = fruits.stream().filter(e -> e.contains("n")).findAny(); // line 1
System.out.println(result.get());

You replace the code on line 1 to use ParallelStream.

Which one is correct?


A. A
The code will produce the same result.
B. B
The compilation fails.
C. C
A NoSuchElementException is thrown at run time.
D. D
The code may produce a different result.
Most Voted

Correct Answer:
D

Hide Answer
uestion Discussion7 ChatGPT Statistics
Share
Question #64

class MyPersistenceData {
String str;
private void methodA() {
System.out.println("methodA");
}
}
Which method should be overridden?
A. A
the readExternal method
B. B
nothing
Most Voted
C. C
the readExternal and writeExternal method
D. D
the writeExternal method

Correct Answer:
C

Hide Answer
uestion Discussion6 ChatGPT Statistics
Share
Question #65

Given:
public class Foo {
public void foo(Collection arg) {
System.out.println("Bonjour le monde!");
}
}

and

public class Bar extends Foo {


public void foo(Collection arg) {
System.out.println("Hello world!");
}

public void foo(List arg) {


System.out.println("Hola Mundol!");
}
}

and

Foo f1 = new Foo();


Foo f2 = new Bar();
Bar b1 = new Bar();
List<String> l1 = new ArrayList<>();

Which three are correct? (Choose three.)


A. A
f2.foo(li) prints Hola Mundo!
B. B
b1.foo(li) prints Bonjour le monde!
C. C
b1.foo(li) prints Hello world!
D. D
f1.foo(li) prints Bonjour le monde!
Most Voted
E. E
f2.foo(li) prints Hello world!
Most Voted
F. F
f2.foo(li) prints Bonjour le monde!
G. G
f1.foo(li) prints Hola Mundo!
H. H
b1.foo(li) prints Hola Mundo!
Most Voted
I. I
f1.foo(li) prints Hello world!

Correct Answer:
A, C, I
Question #66

Given the code fragment:

public class Test {


private final int x = 1;
static final int y;
public Test() {
System.out.print(x);
System.out.print(y);
}
public static void main(String args[]) {
new Test();
}
}

What is the result?


A. A
10
B. B
1
C. C
The compilation fails at line 9.
D. D
The compilation fails at line 16.
E. E
The compilation fails at line 13.
Most Voted

Correct Answer:
E
Hide Answer
uestion Discussion14 ChatGPT Statistics
Share
Question #67

Given this enum declaration:

Examine this code:

System.out.println(Alphabet.getFirstLetter());

What code should be written at line 3 to make this code print A?


A. A
static String getFirstLetter() { return Alphabet.values()[1].toString();
B. B
static String getFirstLetter() { return A.toString(); }
Most Voted
C. C
final String getFirstLetter() { return A.toString(); }
D. D
String getFirstLetter() { return A.toString(); }

Correct Answer:
D

Hide Answer
uestion Discussion10 ChatGPT Statistics
Share
Question #68

Given the code fragment:

What is the result?


A. A
5
B. B
11
C. C
15
Most Voted
D. D
21
E. E
23

Correct Answer:
D

Hide Answer
uestion Discussion11 ChatGPT Statistics
Share
Question #69

Given the declaration:

@inteface Resource {
String[] value();
}

Examine this code fragment:

/* Loc1 */ class ProcessOrders { ... }

Which two annotations may be applied at Loc1 in the code fragment? (Choose two.)
A. A
@Resource({“Customer1”, “Customer2”})
Most Voted
B. B
@Resource(value={{}})
C. C
@Resource
D. D
@Resource(“Customer1”)
Most Voted
E. E
@Resource()

Correct Answer:
AD
Question #71

Given:

var c = new CopyOnWriteArrayList<>(List.of("1", "2", "3", "4"));


Runnable r = () -> {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
System.out.println(e);
}
c.set(3, "four");
System.out.print(c + " ");
};

Thread t = new Thread(r);


t.start();
for (var s : c) {
System.out.print(s + " ");
Thread.sleep(100);
}

What is the output?


A. A
1 2 [1, 2, 3, four] 3 four
B. B
1 2 [1, 2, 3, 4] 3 4
C. C
1 2 [1, 2, 3, 4] 3 four
D. D
1 2 [1, 2, 3, four] 3 4
Most Voted

Correct Answer:
B

Hide Answer
uestion Discussion11 ChatGPT Statistics
Share
Question #72

Given the code fragment:

Which can replace line 2?


A. A
UnaryOperator u = (int i) -> i * 2;
B. B
UnaryOperator u = (var i) -> (i * 2);
Most Voted
C. C
UnaryOperator u = var i -> { return i * 2; };
D. D
UnaryOperator u = i -> { return i * 2);

Correct Answer:
B

Hide Answer
uestion Discussion5 ChatGPT Statistics
Share
Question #73

Given the content from lines.txt:

C-
C++

Java -

Go -

Kotlin -

and
String fileName = "lines.txt";
List<String> list = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
list = stream
.filter(line -> line.equalsIgnoreCase("JAVA"))
.map(String::toUpperCase)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
list.forEach(System.out::println);

What is the result?


A. A
C-
C++

Go -
Kotlin
B. B
JAVA
C. C
C-
C++

GO -
KOTLIN
D. D
C-
C++

JAVA -

GO -
KOTLIN
Most Voted

Correct Answer:
D

Hide Answer
uestion Discussion4 ChatGPT Statistics
Share
Question #74
Given:

ArrayList<Integer> al = new ArrayList<>();


al.add(1);
al.add(2);
al.add(3);
Iterator<Integer> itr = al.iterator();
while (itr.hasNext()) {
if (itr.next() == 2) {
al.remove(2);
System.out.print(itr.next());
}
}

What is the result?


A. A
1 2 followed by an exception
B. B
1245
C. C
A ConcurrentModificationException is thrown at run time.
Most Voted
D. D
1 2 3 followed by an exception

Correct Answer:
C

Hide Answer
uestion Discussion4 ChatGPT Statistics
Share
Question #75

Given:

public class Foo {


public static String ALPHA = "alpha";
protected string beta = "beta";
private final String delta;
public Foo(String d) {
delta = ALPHA + d;
}
public String foo() {
return beta += delta;
}
}

Which change would make Foo more secure?


A. A
public String beta = "beta";
B. B
public static final String ALPHA = "alpha";
Most Voted
C. C
private String delta;
D. D
protected final String beta = "beta";

Correct Answer:
C
Question #76

Given:

public interface ExampleInterface{ }

Which two statements are valid to be written in this interface? (Choose two.)
A. A
public String methodD();
Most Voted
B. B
public int x;
C. C
final void methodG(){
System.out.println("G");
}
D. D
final void methodE();
E. E
public abstract void methodB();
Most Voted
F. F
public void methodF(){
System.out.println("F") ;
}
G. G
private abstract void methodC();

Correct Answer:
AE

Hide Answer
uestion Discussion3 ChatGPT Statistics
Share
Question #77

Given:

public class strBldr {


static StringBuilder sbl = new StringBuilder("yo ");
StringBuilder sb2 = new StringBuilder("hi ");

public static void main(String[] args) {


sbl = sbl.append(new strBldr().foo(new StringBuilder("hey")));
System.out.println(sbl);
}

StringBuilder foo(StringBuilder s) {
System.out.print(s + " oh " + sb2);
return new StringBuilder("ey");
}
}

What is the result?


A. A
hey oh hi
B. B
yo ey
C. C
A compile time error occurs.
D. D
oh hi hey
E. E
hey oh hi yo ey
Most Voted
F. F
hey oh hi ey

Correct Answer:
E

Hide Answer
uestion Discussion2 ChatGPT Statistics
Share
Question #78

Which module defines the foundational APIs of the Java SE Platform?


A. A
java.base
Most Voted
B. B
java.se
C. C
java.lang
D. D
java.object

Correct Answer:
A

Hide Answer
uestion Discussion6 ChatGPT Statistics
Share
Question #79

Given the code fragment:

Integer i = 11;

Which two statements compile? (Choose two.)


A. A
Double c = (Double) i;
B. B
Double b = Double.valueOf(i);
Most Voted
C. C
Double a = i;
D. D
double e = Double.parseDouble(i);
E. E
double d = i;
Most Voted

Correct Answer:
AB
Question #80

Given:

interface AbilityA {
default void action() {
System.out.println("a action");
}
}

and

interface AbilityB {
void action();
}

public class Test implements AbilityA, AbilityB { // line 1


public void action() {
System.out.println("ab action");
}

public static void main(String[] args) { // line 2


AbilityB x = new Test();
x.action();
}
}

What is the result?


A. A
The compilation fails on line 2.
B. B
ab action
Most Voted
C. C
An exception is thrown at run time.
D. D
a action
E. E
The compilation fails on line 1.

Correct Answer:
E

Question #81

Given:

public class A {
int a = 0;
int b = 0;
int c = 0;
public void foo(int i) {
a += b * i;
c = b * i;
}

public void setB(int i) {


b = i;
}
}

Which makes class A thread safe?


A. A
Class A is thread safe.
B. B
Make foo and setB synchronized.
Most Voted
C. C
Make foo synchronized.
D. D
Make A synchronized.
E. E
Make setB synchronized.
Correct Answer:
D

Hide Answer
uestion Discussion5 ChatGPT Statistics
Share
Question #82

A company has an existing Java app that includes two Java 8 jar files, sales-8.10.jar
and clients-10.2.jar.

The jar file, sales-8.10.jar, references packages in clients-10.2.jar, but clients-10.2.jar


does not reference packages in sales-8.10.jar.

They have decided to modularize clients-10.2. jar.

Which module-info.java file would work for the new library version clients-10.3.jar?
A. A
module com.company.clients{
requires com.company.clients;
}
B. B
module com.company.clients{
uses com.company.clients;
}
C. C
module com.company.clients {
exports com.company.clients.Client;
}
D. D
module com.company.clients {
exports com.company.clients;
}
Most Voted

Correct Answer:
C

Hide Answer
uestion Discussion7 ChatGPT Statistics
Share
Question #83
Which two statements are correct about modules in Java? (Choose two.)
A. A
module-info.java cannot be empty.
B. B
module-info.java can be placed in any folder inside module-path.
C. C
By default, modules can access each other as long as they run in the same folder.
D. D
A module must be declared in module-info.java file,
Most Voted
E. E
java.base exports all of the Java platforms core packages.
Most Voted

Correct Answer:
AE

Hide Answer
uestion Discussion4 ChatGPT Statistics
Share
Question #84

Assuming the user credentials are correct, which expression will create a Connection?
A. A
DriverManager.getConnection("http://database.jdbc.com", "J_SMITH", "dt12%2f3")
B. B
DriverManager.getConnection("jdbc:derby:com")
Most Voted
C. C
DriverManager.getConnection("jdbc.derby.com")
D. D
DriverManager.getConnection()
E. E
DriverManager.getConnection("J_SMITH", "dt12%2f3")

Correct Answer:
A
Hide Answer
uestion Discussion8 ChatGPT Statistics
Share
Question #85

Given:

1. interface Pastry {
2. void getIngredients();
3. }
4. abstract class Cookie implements Pastry {}
5. class ChocolateCookie implements Cookie {
6. public void getIngredients() {}
7. }
8. class CoconutChocolateCookie extends ChocolateCookie {
9. void getIngredients(int x) {}
10. }

Which is true? (Choose four.)


A. A
The compilation fails due to an error in line 4.
B. B
The compilation fails due to an error in line 9.
Most Voted
C. C
The compilation fails due to an error in line 10.
D. D
The compilation fails due to an error in line 2.
E. E
The compilation fails due to an error in line 6.
Most Voted
F. F
The compilation fails due to an error in line 7.
G. G
The compilation succeeds.

Correct Answer:
ACEF
Question #86

Given:
public class Employee {
private String name;
private String neighborhood;
private int salary;
// Constructors and setter and getter methods go here
}

and the code fragment:

List<Employee> roster = new ArrayList<>();


Predicate<Employee> p = e -> e.getSalary() > 30;
Function<Employee, Optional<String>> f = e ->
Optional.ofNullable(e.getNeighborhood());

Which two Map objects group all employees with a salary greater than 30 by
neighborhood? (Choose two.)
A. A

Most Voted
B. B

C. C

D. D

E. E

Correct Answer:
A

Hide Answer
uestion Discussion6 ChatGPT Statistics
Question #87

Given:
Given:
import java.util.ArrayList;
import java.util.Arrays;
public class NewMain {
public static void main(String[] args) {
String[] catNames = {"abyssinian", "oxicat",
"korat", "laperm", "bengal", "sphynx"};
var cats = new ArrayList<>(Arrays.asList(catNames));
cats.sort((var a, var b) -> -a.compareTo(b));
cats.forEach(System.out::println);
}
}

What is the result?


A. A
abyssinian
oxicat
korat
laperm
bengal
sphynx
B. B
abyssinian
bengal
korat
laperm
oxicat
sphynx
C. C
sphynx
oxicat
laperm
korat
bengal
abyssinian
Most Voted
D. D
nothing

Correct Answer:
C

Hide Answer
uestion Discussion8 ChatGPT Statistics
Share
Question #88

Given:

public class Price {


private final double value;
public Price(String value) {
this(Double.parseDouble(value));
}

public Price(double value) {


this.value = value;
}

public double getValue() { return value; }


public static void main(String[] args) {
Price p1 = new Price("1.99");
Price p2 = new Price(2.99);
Price p3 = new Price(0);
System.out.println(p1.getValue() + ";" + p2.getValue() + ";" + p3.getValue());
}
}

What is the result?


A. A
1.99,2.99,0
B. B
1.99,2.99,0.0
C. C
The compilation fails.
Most Voted
D. D
1.99,2.99

Correct Answer:
B

Hide Answer
uestion Discussion5 ChatGPT Statistics
Share
Question #89

Given:
public class Person {
private String name;
private Person child;
public Person(String name, Person child) {
this(name);
this.child = child;
}
public Person(String name) {
this.name = name;
}
public String toString() {
return name + " child";
}
}

and

public class Tester {


public static Person createPeople() {
Person jane = new Person("Jane");
Person john = new Person("John", jane);
return jane;
}

public static Person createPerson(Person person) {


person = new Person("Jack", person);
return person;
}

public static void main(String[] args) {


Person person = createPeople();
/* line 1 */
person = createPerson(person);
/* line 2 */
String name = person.toString();
System.out.println(name);
}
}

Which statement is true?


A. A
The memory allocated for Jack object can be reused in line 2.
B. B
The memory allocated for Jane object can be reused in line 1.
C. C
The memory allocated for Jane object can be reused in line 2.
D. D
The memory allocated for John object can be reused in line 1.
Most Voted

Correct Answer:
A

Hide Answer
uestion Discussion1 ChatGPT Statistics
Share
Question #90

Given:

public class X {
protected void print(Object obj) {
System.out.println(obj);
}

public final void print(Object... objects) {


for(Object object : objects) {
print(object);
}
}

public void print(Collection collection) {


collection.forEach(System.out::println);
}
}

public class Y extends X {


public void print(Object obj) {
System.out.print("[" + obj + "]");
}

public void print(Object... objects) {


for(Object object : objects) {
System.out.println("[" + object + "]");
}
}

public void print(Collection collection) {


print(collection.toArray());
}
}
Why does this compilation fail?

Why does this compilation fail?


A. A
The method X.print (object) is not accessible to Y.
B. B
The method Y.print (Object) does not call the method super.print (Object).
C. C
In method X.print (Collection), System.out::println is an invalid Java identifier.
D. D
The method Y.print (Object...) cannot override the final method X.print (Object...).
Most Voted
E. E
The method print (Object) and the method print (Object...) are duplicates of each
other.

Correct Answer:
D
Question #91

Given:

Iterator loop = List.of(1,2,3).iterator();


while (loop.hasNext()) {
foo(loop.next());
}

Iterator loop2 = List.of(1,2,3).iterator();


while (loop.hasNext()) {
bar(loop2.next());
}

for (Iterator loop2 = List.of(1,2,3).iterator(); loop.hasNext(); ) {


bar(loop2.next());
}

for (Iterator loop = List.of(1,2,3).iterator(); loop.hasNext(); ) {


foo(loop.next());
}

Which loop incurs a compile time error?


A. A
the loop starting line 11
Most Voted
B. B
the loop starting line 7
C. C
the loop starting line 14
D. D
the loop starting line 3

Correct Answer:
A

Hide Answer
uestion Discussion4 ChatGPT Statistics
Share
Question #92

Given the code fragment:

var i = 1;
var result = IntStream.generate(() -> { return i; })
.limit(100).sum();
System.out.println(result);

Which statement prints the same value of result? (Choose two.)


A. A
System.out.printIn(IntStream.range(0, 99).count());
B. B
System.out.printIn(IntStream.rangeClosed(1, 100).count());
Most Voted
C. C
System.out.printIn(IntStream.range(1, 100).count());
D. D
System.out.printIn(IntStream.rangeClosed(0, 100).map(x -> x).count());

Correct Answer:
BD

Hide Answer
uestion Discussion7 ChatGPT Statistics
Share
Question #93

Given:

int i = 3;
int j = 25;
System.out.println(i > 2 ? i > 10 ? 1 * (j + 10) : 1 * j + 5 : i);

What is the result?


A. A
385
B. B
3
C. C
The compilation fails.
D. D
80
Most Voted
E. E
25

Correct Answer:
A

Hide Answer
uestion Discussion2 ChatGPT Statistics
Share
Question #94

Which two var declarations are correct? (Choose two.)


A. A
var names = new ArrayList<>();
Most Voted
B. B
var _ = 100;
C. C
var var = “hello”;
Most Voted
D. D
var y = null;
E. E
var a;

Correct Answer:
AC

Hide Answer
uestion Discussion3 ChatGPT Statistics
Share
Question #95

Given:

public interface API { //line 1


public void checkValue(Object value) throws IllegalArgumentException; //line 2
public boolean isValueANumber(Object val) {
if(val instanceof Number) {
return true;
} else {
try {
Double.parseDouble(val.toString());
return true;
} catch (NumberFormatException ex) {
return false;
}
}
}
}

Which two changes need to be made to make this class compile? (Choose two.)
A. A
Change Line 1 to a class:
public class API {
B. B
Change Line 2 to an abstract method:
public abstract void checkValue(Object value)
throws IllegalArgumentException;
Most Voted
C. C
Change Line 2 access modifier to protected:
protected void checkValue(Object value)
throws IllegalArgumentException;
D. D
Change Line 1 to extend java.lang.AutoCloseable:
public interface API extends AutoCloseable {
E. E
Change Line 1 to an abstract class:
public abstract class API {
Most Voted

Correct Answer:
BE
Question #96

Given:
public interface A {
abstract void x();
public default void y() { }
}

and

public abstract class B {


public abstract void z();
}

public class C extends B implements A {


/* insert code here */
}
What code inserted into class C would allow it to compile?
A. A
public void x() { }
public void z() { }
Most Voted
B. B
public void x() { }
protected void y() { super.y(); }
public void z() { }
C. C
void x() { }
public void y() { }
public void z() { }
D. D
void x() { super.y(); }
public void z() { }
E. E
void x() { }
public void z() { }

Correct Answer:
A

Hide Answer
uestion Discussion3 ChatGPT Statistics
Share
Question #97

Given:

public interface Adaptorfirst {


void showFirst();
}

Which three classes successfully override showFirst()? (Choose three.)


A. A

Most Voted
B. B

Most Voted
C. C

D. D
E. E

Most Voted
F. F

Correct Answer:
ABE

Hide Answer
uestion Discussion3 ChatGPT Statistics
Share
Question #98

Given:
public class X {
private Collection collection;
public void set(Collection collection) {
this.collection = collection;
}
and

public class Y extends X {


public void set(Map<String,String> map) {
super.set(map); // line 1
}
}
Which two lines can replace line 1 so that the Y class compiles? (Choose two.)
A. A
super.set(List map)
B. B
map.forEach((k, v) -> set(v)));
C. C
set(map.values());
Most Voted
D. D
set(map)
E. E
super.set(map.values());
Most Voted

Correct Answer:
CE

Hide Answer
uestion Discussion3 ChatGPT Statistics
Share
Question #99

Given the code fragment:

int x = 0;
do {
x++;
if (x == 1) {
continue;
}
System.out.println(x);
} while (x < 1);

What is the result?


A. A
0
B. B
It prints 1 in infinite loop.
C. C
1
D. D
The program prints nothing.
Most Voted
E. E
1

Correct Answer:
D

Hide Answer
uestion Discussion2 ChatGPT Statistics
Share
Question #100

Given TripleThis.java:

import java.util.function.*;
public class TripleThis {
public static void main(String[] args) {
Function<Integer, Integer> tripler = x -> { return (Integer) x * 3; };
TripleThis.printValue(tripler, 4);
}

public static <T> void printValue(Function<T, T> f, T num) {


System.out.println(f.apply(num));
}
}

Compiling TripleThis.java gives this compiler warning:

Note: TripleThis.java uses unchecked or unsafe operations.

Which two replacements remove this compiler warning and prints 12? (Choose two.)
A. A
Replace line 12 with public static void printValue(Function f, int num) {
Most Voted
B. B
Replace line 12 with public static void printValue(Function f, T num) {
C. C
Replace line 9 with Function tripler = x —> { return (Integer) x * 3; }
D. D
Replace line 12 with public static void printValue(Function f, Integer num) {
Most Voted
E. E
Replace line 9 with Function tripler = x -> { return x * 3; }
F. F
Replace line 9 with Function tripler = x -> [ return x * 3; ]

Correct Answer:
AD
Question #101

Given the code fragment:

Given the code fragment:

public class Test {


class L extends Exception { }
class M extends L { }
class N extends RuntimeException { }
public void p() throws L { throw new M(); }
public void q() throws N { throw new N(); }
public static void main(String[] args) {
Test t = new Test();
t.p();
t.q();
/* line 1 */
System.out.println("Exception caught");
}
}

What change on line 1 will make this code compile?


A. A
Add catch(M | L e)
B. B
Add catch(L e)
Most Voted
C. C
Add catch(N | L | M e)
D. D
Add catch(L | N e)
E. E
Add catch(L | M | N e)

Correct Answer:
B

Hide Answer
uestion Discussion2 ChatGPT Statistics
Share
Question #102

Given the code fragment:

public class Main {


static String prefix = "Mondial:";
private String name = "domainmodel";
public static String getName() {
return new Main().name;
}

public static void main(String[] args) {


Main m = new Main();
System.out.println(/* Insert code here */);
}
}

Which two code snippets inserted independently inside println method print
Mondial:domainmodel? (Choose two.)
A. A
Main.prefix + Main.name
B. B
prefix + getName
C. C
Main.prefix + Main.getName()
Most Voted
D. D
new Main().prefix + new Main().name
Most Voted
E. E
prefix + name
F. F
prefix + Main.name

Correct Answer:
BC

Hide Answer
uestion Discussion9 ChatGPT Statistics
Share
Question #103

Given the code fragment:

public class CreateArrayListExample {


public static void main(String[] args) {
List vegetables = new ArrayList<>();
vegetables.add("Kale");
vegetables.add(0, "Lettuce");
System.out.println(vegetables);
List fish = new ArrayList<>();
fish.add("Salmon");
fish.add(0, "Seabass");
System.out.println(fish);
}
}

What is the result?


A. A
[Lettuce, Kale]
B. B
A compilation error is thrown.
C. C
[Lettuce, Kale]
[Seabass, Salmon]
Most Voted
D. D
[Kale, Lettuce]
[Salmon, Seabass]

Correct Answer:
B

Hide Answer
uestion Discussion3 ChatGPT Statistics
Share
Question #104

Given:

Automobile.java -
public abstract class Automobile { // line 1
abstract void wheels();
}

// Car.java
public class Car extends Automobile { // line 2
void wheels(int i) { // line 3
System.out.print(4);
}

public static void main(String[] args) {


Automobile ob = new Car(); // line 4
ob.wheels();
}
}

What must you do so that the code prints 4?


A. Remove the parameter from wheels method in line 3.

What must you do so that the code prints 4?


A. A
Remove the parameter from wheels method in line 3.
Most Voted
B. B
Remove abstract keyword in line 1.
C. C
Replace the code in line 2 with Car ob = new Car();.
D. D
Add @Override annotation at line 2.
Correct Answer:
A

Hide Answer
uestion Discussion3 ChatGPT Statistics
Share
Question #105

Which module is required for any application using Swing or AWT?


A. A
java.desktop
Most Voted
B. B
java.prefs
C. C
java.se
D. D
java.logging
E. E
java.rmi

Correct Answer:
A

You might also like