Java Quiz
Java Quiz
Java Quiz
Q1. Given the string "strawberries" saved in a variable called fruit, what would fruit.substring(2, 5)
return?
rawb
raw
awb
traw
Q3. Given the following definitions, which of these expression will NOT evaluate to true?
boolean b1 = true, b2 = false; int i1 = 1, i2 = 2;
(i1 | i2) == 3
i2 && b1
b1 || !b2
(i1 ^ i2) < 4
1: class Main {
2: public static void main (String[] args) {
3: int array[] = {1, 2, 3, 4};
4: for (int i = 0; i < array.size(); i++) {
5: System.out.print(array[i]);
6: }
7: }
8: }
Q5. Which of the following can replace the CODE SNIPPET to make the code below print "Hello
World"?
interface Interface1 {
static void print() {
System.out.print("Hello");
}
}
interface Interface2 {
static void print() {
System.out.print("World!");
}
}
super1.print(); super2.print();
this.print();
super.print();
Interface1.print(); Interface2.print();
CD
CDE
D
"abcde"
class Main {
public static void main (String[] args){
System.out.println(print(1));
}
static Exception print(int i){
if (i>0) {
return new Exception();
} else {
throw new RuntimeException();
}
}
}
interface Two {
default void method () {
System.out.println("One");
}
}
class Main {
public static void main (String[] args) {
List list = new ArrayList();
list.add("hello");
list.add(2);
System.out.print(list.get(0) instanceof Object);
System.out.print(list.get(1) instanceof Integer);
}
}
package mypackage;
public class Math {
public static int abs(int num){
return num < 0 ? -num : num;
}
}
package mypackage.elementary;
public class Math {
public static int abs (int num) {
return -num;
}
}
import mypackage.Math;
import mypackage.elementary.*;
class Main {
public static void main (String args[]){
System.out.println(Math.abs(123));
}
}
Explanation: The answer is "123". The abs() method evaluates to the one inside mypackage.Math class, because The import
statements of the form:
import packageName.subPackage.*
1: class MainClass {
2: final String message(){
3: return "Hello!";
4: }
5: }
class Main {
public static void main(String[] args) {
System.out.println(args[2]);
}
}
class Main {
public static void main(String[] args){
int a = 123451234512345;
System.out.println(a);
}
}
"123451234512345"
Nothing - this will not compile.
a negative integer value
"12345100000"
Reasoning: The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Therefore, this code
will not compile as the number assigned to 'a' is larger than the int type can hold.
class Main {
public static void main (String[] args) {
String message = "Hello world!";
String newMessage = message.substring(6, 12)
+ message.substring(12, 6);
System.out.println(newMessage);
}
}
Q15. How do you write a foreach loop that will iterate over ArrayList<Pencil>pencilCase?
for (Pencil pencil : pencilCase) {}
for (pencilCase.next()) {}
for (Pencil pencil : pencilCase.iterator()) {}
for (pencil in pencilCase) {}
Q16. What does this code print?
System.out.print("apple".compareTo("banana"));
0
positive number
negative number
compilation error
Q17. You have an ArrayList of names that you want to sort alphabetically. Which approach would
NOT work?
names.sort(Comparator.comparing(String::toString))
Collections.sort(names)
names.sort(List.DESCENDING)
names.stream().sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList())
Q18. By implementing encapsulation, you cannot directly access the class's _ properties unless you
are writing code inside the class itself.
private
protected
no-modifier
public
Q19. Which is the most up-to-date way to instantiate the current date?
new SimpleDateFormat("yyyy-MM-dd").format(new Date())
new Date(System.currentTimeMillis())
LocalDate.now()
Calendar.getInstance().getTime()
Q20. Fill in the blank to create a piece of code that will tell whether int0 is divisible by 5 :
boolean isDivisibleBy5 = _____
Q21. How many times will this code print "Hello World!"?
class Main {
public static void main(String[] args){
for (int i=0; i<10; i=i++){
i+=1;
System.out.println("Hello World!");
}
}
}
10 times
9 times
5 times
infinite number of times
Explanation: Observe the loop increment. It's not an increment, it's an assignment(post).
Q22. The runtime system starts your program by calling which function first?
print
iterative
hello
main
/* Constructor B */
Jedi(String name, String species, boolean followsTheDarkSide){}
}
Q25. What will this program print out to the console when executed?
import java.util.LinkedList;
[5, 1, 10]
[10, 5, 1]
[1, 5, 10]
[10, 1, 5]
"Hello"
A runtime exception is thrown.
The code does not compile.
"ello"
Q27. Object-oriented programming is a style of programming where you organize your program
around _ rather than _ and data rather than logic.
functions; actions
objects; actions
actions; functions
actions; objects
import java.util.*;
class Main {
public static void main(String[] args) {
List<Boolean> list = new ArrayList<>();
list.add(true);
list.add(Boolean.parseBoolean("FalSe"));
list.add(Boolean.TRUE);
System.out.print(list.size());
System.out.print(list.get(1) instanceof Boolean);
}
}
Q32. Which is the most reliable expression for testing whether the values of two string variables are
the same?
string1 == string2
string1 = string2
string1.matches(string2)
string1.equals(string2)
A, B, and D
A, C, and D
C and D
A and D
class Main {
static int count = 0;
public static void main(String[] args) {
if (count < 3) {
count++;
main(null);
} else {
return;
}
System.out.println("Hello World!");
}
}
import java.util.*;
class Main {
public static void main(String[] args) {
String[] array = {"abc", "2", "10", "0"};
List<String> list = Arrays.asList(array);
Collections.sort(list);
System.out.println(Arrays.toString(array));
}
}
[abc, 0, 2, 10]
The code does not compile.
[abc, 2, 10, 0]
[0, 10, 2, abc]
Explanation: The java.util.Arrays.asList(T... a) returns a fixed-size list backed by the specified array. (Changes to the returned list
"write through" to the array.)
class Main {
public static void main(String[] args) {
String message = "Hello";
print(message);
message += "World!";
print(message);
}
static void print(String message){
System.out.print(message);
message += " ";
}
}
Hello World!
HelloHelloWorld!
Hello Hello World!
Hello HelloWorld!
x
null
10
5
Q38. Which approach cannot be used to iterate over a List named theList?
A
Iterator it = theList.iterator();
for (it.hasNext()) {
System.out.println(it.next());
}
theList.forEach(System.out::println);
Q42. How does the keyword volatile affect how a variable is handled?
It will be read by only one thread at a time.
It will be stored on the hard drive.
It will never be cached by the CPU.
It will be preferentially garbage collected.
an alphanumeric character
a negative number
a positive number
a ClassCastException
Q47. If you encounter UnsupportedClassVersionError it means the code was ___ on a newer version of
Java than the JRE ___ it.
executed; interpreting
executed; compiling
compiled; executing
compiled, translating
Q48. Given this class, how would you make the code compile?
public TheClass() {
x += 77;
}
public TheClass() {
x = null;
}
public TheClass() {
x = 77;
}
Explanation: final class members are allowed to be assigned only in three places: declaration, constructor or an instance-initializer
block.
Q49. How many times f will be printed?
4
3
5
A Runtime exception will be thrown
1, 2, and 3
only 3
2 and 3
only 2
Q51. Which keyword lets you call the constructor of a parent class?
parent
super
this
new
1: int a = 1;
2: int b = 0;
3: int c = a/b;
4: System.out.println(c);
Q53. Normally, to access a static member of a class such as Math.PI, you would need to specify the
class "Math". What would be the best way to allow you to use simply "PI" in your code?
Add a static import.
Declare local copies of the constant in your code.
This cannot be done. You must always qualify references to static members with the class form which they came from.
Put the static members in an interface and inherit from that interface.
Reasoning:
The default Java type which Java will be using for a float variable will be double.
So, even if you declare any variable as float, what the compiler has to actually do is to assign a double value to a float variable,
which is not possible. So, to tell the compiler to treat this value as a float, that 'F' is used.
Q58. What language construct serves as a blueprint containing an object's properties and
functionality?
constructor
instance
class
method
Q59. What does this code print?
10 10
5 10
10 5
55
try {
System.out.println("Hello World");
} catch (Exception e) {
System.out.println("e");
} catch (ArithmeticException e) {
System.out.println("e");
} finally {
System.out.println("!");
}
Hello World
It will not compile because the second catch statement is unreachable
Hello World!
It will throw runtime exception
Q62. Which operator would you use to find the remainder after division?
%
//
/
DIV
Reference
Reference
groucyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Press me one more time..");
}
});
Reference
Q66. Which functional interfaces does Java provide to serve as data types for lambda expressions?
Observer, Observable
Collector, Builder
Filter, Map, Reduce
Consumer, Predicate, Supplier
Reference
Reference
Reference
Q69. How do you force an object to be garbage collected?
Set object to null and call Runtime.gc()
Set object to null and call System.gc()
Set object to null and call Runtime.getRuntime().runFinalization()
There is no way to force an object to be garbage collected
Reference
Q70. Java programmers commonly use design patterns. Some examples are the _, which helps
create instances of a class, the _, which ensures that only one instance of a class can be created;
and the _, which allows for a group of algorithms to be interchangeable.
static factory method; singleton; strategy pattern
strategy pattern; static factory method; singleton
creation pattern; singleton; prototype pattern
singleton; strategy pattern; static factory method
Q71. Using Java's Reflection API, you can use _ to get the name of a class and _ to retrieve an array
of its methods.
this.getClass().getSimpleName(); this.getClass().getDeclaredMethods()
this.getName(); this.getMethods()
Reflection.getName(this); Reflection.getMethods(this)
Reflection.getClass(this).getName(); Reflection.getClass(this).getMethods()
Q73. Which access modifier makes variables and methods visible only in the class where they are
declared?
public
protected
nonmodifier
private
Duck(String name) {
this.name = name;
}
Reference
two
four
three
five
p
r
e
i
Q81. What phrase indicates that a function receives a copy of each argument passed to it rather than
a reference to the objects themselves?
pass by reference
pass by occurrence
pass by value
API call
5
8
1
3
Explanation: Changing line 2 to public static final String message raises the error
message not initialized in the default constructor
falsefalse
truetrue
falsetrue
truefalse
class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("hello");
sb.deleteCharAt(0).insert(0, "H")." World!";
System.out.println(sb);
}
}
Q88. How would you use the TaxCalculator to determine the amount of tax on $50?
class TaxCalculator {
static calculate(total) {
return total * .05;
}
}
TaxCalculator.calculate(50);
new TaxCalculator.calculate(50);
calculate(50);
new TaxCalculator.calculate($50);
1. Reference
2. Code sample
Q89. Which characteristic does not apply to instances of java.util.HashSet=
uses hashcode of objects when inserted
contains unordred elements
contains unique elements
contains sorted elements
Explanation: HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will
remain constant over time.
Reference
import java.util.*;
1324
4231
1234
4321
Q91. What will this code print, assuming it is inside the main method of a class?
System.out.println("hello my friends".split(" ")[0]);
my
hellomyfriends
hello
friends
Q92. You have an instance of type Map<String, Integer> named instruments containing the following
key-value pairs: guitar=1200, cello=3000, and drum=2000. If you add the new key-value pair
cello=4500 to the Map using the put method, how many elements do you have in the Map when you
call instruments.size()?
2
When calling the put method, Java will throw an exception
4
3
Q93. Which class acts as root class for Java Exception hierarchy?
Clonable
Throwable
Object
Serializable
Q95. You have a variable of named employees of type List<Employee> containing multiple entries. The
Employee type has a method getName() that returns the employee name. Which statement properly
extracts a list of employee names?
employees.collect(employee -> employee.getName());
employees.filter(Employee::getName).collect(Collectors.toUnmodifiableList());
employees.stream().map(Employee::getName).collect(Collectors.toList());
employees.stream().collect((e) -> e.getName());
Q96. This code does not compile. What needs to be changed so that it does?
Add a constructor that accepts a String parameter and assigns it to the field shortCode .
Remove the final keyword for the field shortCode .
All enums need to be defined on a single line of code.
Add a setter method for the field shortCode .
Q97. Which language feature ensures that objects implementing the AutoCloseable interface are
closed when it completes?
try-catch-finally
try-finally-close
try-with-resources
try-catch-close
class Car {
public void accelerate() {}
}
class Lambo extends Car {
public void accelerate(int speedLimit) {}
public void accelerate() {}
}
neither
both
overloading
overriding
Q100. Which choice is the best data type for working with money in Java?
float
String
double
BigDecimal
Reference
Q102. What language feature allows types to be parameters on classes, interfaces, and methods in
order to reuse the same code for different data types?
Regular Expressions
Reflection
Generics
Concurrency
raspberry
strawberry
blueberry
rasp
forestSpecies.put("Amazon", 30000);
forestSpecies.put("Congo", 10000);
forestSpecies.put("Daintree", 15000);
forestSpecies.put("Amazon", 40000);
3
4
2
When calling the put method, Java will throw an exception
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Main {
interface MyInterface {
int foo(int x);
}
10
20
null
An error will occur when compiling.
Q109. Which statement must be inserted on line 1 to print the value true?
1:
2: Optional<String> opt = Optional.of(val);
3: System.out.println(opt.isPresent());
Q110. What will this code print, assuming it is inside the main method of a class?
false
true
true
true
true
false
false
false
list1.remove(list2);
System.out.println(list1);
[Two]
[One, Two, Three]
[One, Three]
Two
Q112. Which code checks whether the characters in two Strings,named time and money , are the
same?
if(time <> money){}
if(time.equals(money)){}
if(time == money){}
if(time = money){}
Q113. An _ is a serious issue thrown by the JVM that the JVM is unlikely to recover from. An _ is an
unexpected event that an application may be able to deal with in order to continue execution.
exception,assertion
AbnormalException, AccidentalException
error, exception
exception, error
class Unicorn {
_____ Unicorn(){}
}
static
protected
public
void
List[] myLists = {
new ArrayList<>(),
new LinkedList<>(),
new Stack<>(),
new Vector<>(),
};
composition
generics
polymorphism
encapsulation
System.out.println(a == b);
System.out.println(b == c);
true; false
false; false
false; true
true; true
Explanation: == operator compares the object reference. String a = "bikini"; String b = "bikini"; would result in True. Here new
creates a new object, so false. Use equals() method to compare the content.
Q117. What keyword is added to a method declaration to ensure that two threads do not
simultaneously execute it on the same object instance?
native
volatile
synchronized
lock
Function<Integer, Boolean>
Function<String>
Function<Integer, String>
Function<Integer>
Explaination, Reference
import java.util.HashMap;
pantry.put("Apples", 3);
pantry.put("Oranges", 2);
System.out.println(pantry.get("Apples"));
}
}
6
3
4
7
Explanation
Function<String, String>
Stream<String>
String<String, String>
Map<String, String>
Explanation, Reference
Q121. Which is the correct return type for the processFunction method?
Integer
String
Consumer
Function<Integer, String>
Explanation
Q122. What function could you use to replace slashes for dashes in a list of dates?
Explanation: replaceAll method for any List only accepts UnaryOperator to pass every single element into it then put the result into
the List again.
Explanation
Q124. How do you create and run a Thread for this class?
import java.util.date;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
Reference
D
int total = numbers.stream()
.filter(x -> x % 2 == 0)
.mapToInt(x -> x * x)
.sum();
Explanation: The given code in the question will give you the output 20 as total
Q126. Which is not one of the standard input/output streams provided by java.lang.System?
print
out
err
in
Q127. The compiler is complaining about this assignment of the variable pickle to the variable jar.
How woulld you fix this?
double pickle = 2;
int jar = pickle;
Q128. What value should x have to make this loop execute 10 times?
10
3
1
0
Q129. The _ runs compiled Java code, while the _ compiles Java files.
IDE; JRE
JDK; IDE
JRE; JDK
JDK; JRE
Reference
Reference
Q131. What values for x and y will cause this code to print "btc"?
int x = 0; int y = 2;
int x = 1; int y = 3;
int x = 0; int y = 3;
int x = 1; int y = 3;
Q132. Which keyword would you add to make this method the entry point of the program?
exception
args
static
String
Reference
Q133. You have a list of Bunny objects that you want to sort by weight using Collections.sort. What
modification would you make to the Bunny class?
Implement the comparable interface by overriding the compareTo method.
Add the keyword default to the weight variable.
Override the equals method inside the Bunny class.
Implement Sortable and override the sortBy method.
Reference
Reference
int yearsMarried = 2;
switch (yearsMarried) {
case 1:
System.out.println("paper");
case 2:
System.out.println("cotton");
case 3:
System.out.println("leather");
default:
System.out.println("I don't gotta buy gifts for nobody!");
}
cotton
cotton
leather
cotton
leather
I don't gotta buy gifts for nobody!
cotton
I don't gotta buy gifts for nobody!
Doggie::fetch
condensed invocation
static references
method references
bad code
Q137. What is the difference between the wait() and sleep methods?
Only Threads can wait, but any Object can be put to sleep.
A wait can be woken up by another Thread calling notify whereas a sleep cannot.
When things go wrong, sleep throws an IllegalMonitorStateException whereas wait throws an InterruptedException.
Sleep allows for multi-threading whereas wait does not.
Q140. Which data structure would you choose to associate the amount of rainfall with each month?
Vector
LinkedList
Map
Queue
Q143. When you pass an object reference as an argument to a method call what gets passed?
a reference to a copy
a copy of the reference
the object itself
the original reference
Q144. Which choice demonstrates a valid way to create a reference to a static function of another
class?
Function<Integer, Integer> funcReference = MyClass::myFunction;
Function<Integer, Integer> funcReference = MyClass.myFunction;
Function<Integer, Integer> funcReference = MyClass().myFunction();
Function<Integer, Integer> funcReference = MyClass::myFunction();
Explanation: After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the
thread is initially executed.
[Explanation](Final classes are created so the methods implemented by that class cannot be overridden. It can't be inherited. These
classes are declared final.)
Q150. Which method can be used to find the highest value of x and y?
Math.largest(x,y)
Math.maxNum(x,y)
Math.max(x,y)
Math.maximum(x,y)
1: class Main {
7: int result = 0;
8:
9: result += entry.getValue();
10: }
class Car {
String color = "blue";
}
public Lambo() {
System.out.println(super.color);
System.out.println(this.color);
System.out.println(color);
}
}
blue
white
white
blue
white
blue
white
white
white
white
white
blue
Q156. Which command will run a FrogSounds app that someone emailed to you as
a jar?
jar FrogSounds.java
javac FrogSounds.exe
jar cf FrogSounds.jar
java -jar FrogSounds.jar
class variable_scope {
public static void main(String args[])
{
int x;
x = 5;
{
int y = 6;
System.out.print(x + " " + y);
}
System.out.println(x + " " + y);
}
}
Compilation Error
Runtime Error
5656
565
Q159. Subclasses of an abstract class are created using the keyword _____.
extends
abstracts
interfaces
implements
class Unicorn {
_____ Unicorn(){}
}
public
static
protected
void
Explaination : A constructor cannot have a return type (not even a void return type).
System.out::println
Doggie::fetch
method references
bad code
condensed invocation
static references
Reference
import java.util.Formatter;
public class Course {
public static void main(String[] args) {
Formatter data = new Formatter();
data.format("course %s", "java ");
System.out.println(data);
data.format("tutorial %s", "Merit campus");
System.out.println(data);
}
}
course java
tutorial Merit campus
course java
course java tutorial Merit campus
Compilation Error
Runtime Error