Java

Given the string "strawberries" saved in a variable called fruit, what would `fruit.substring(2, 5)` return?

**Reasoning:** The substring method is accepting two arguments.

1.

rawb

2.

raw

3.

awb

4.

traw

5.

undefined

6.

undefined

7.

undefined

8.

undefined

9.

undefined

Q 1 / 120

Java

How can you achieve runtime polymorphism in Java?

1.

method overloading

2.

method overrunning

3.

method overriding

4.

method calling

Q 2 / 120

Java

Given the following definitions, which of these expression will **NOT** evaluate to true?

`boolean b1 = true, b2 = false; int i1 = 1, i2 = 2;`

1.

`(i1 | i2) == 3`

2.

`i2 && b1`

3.

`b1 || !b2`

4.

`(i1 ^ i2) < 4`

Q 3 / 120

Java

What is the output of this code?

java 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: }

1.

It will not compile because of line 4.

2.

It will not compile because of line 3.

3.

123

4.

1234

Q 4 / 120

Java

Which of the following can replace the CODE SNIPPET to make the code below print "Hello World"?

java interface Interface1 { static void print() { System.out.print("Hello"); } } interface Interface2 { static void print() { System.out.print("World!"); } }

1.

`super1.print(); super2.print();`

2.

`this.print();`

3.

`super.print();`

4.

`Interface1.print(); Interface2.print();`

Q 5 / 120

Java

What does the following code print?

java String str = "abcde"; str.trim(); str.toUpperCase(); str.substring(3, 4); System.out.println(str);

1.

CD

2.

CDE

3.

D

4.

"abcde"

Q 6 / 120

Java

What is the result of this code?

java 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(); } } }

1.

It will show a stack trace with a runtime exception.

2.

"java.lang.Exception"

3.

It will run and throw an exception.

4.

It will not compile.

Q 7 / 120

Java

Which class can compile given these declarations?

java interface One { default void method() { System.out.println("One"); } } interface Two { default void method () { System.out.println("One"); } } java class Three implements One, Two { public void method() { super.One.method(); } } java class Three implements One, Two { public void method() { One.method(); } } java class Three implements One, Two { } java class Three implements One, Two { public void method() { One.super.method(); } }

1.

A

2.

B

3.

C

4.

D

Q 8 / 120

Java

What is the output of this code?

java 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); } }

1.

The code does not compile.

2.

truefalse

3.

truetrue

4.

falsetrue

Q 9 / 120

Java

Given the following two classes, what will be the output of the Main class?

java 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; } } java 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.`

1.

Lines 1 and 2 generate compiler errors due to class name conflicts.

2.

"-123"

3.

It will throw an exception on line 5.

4.

"123"

Q 10 / 120

Java

What is the result of this code?

java 1: class MainClass { 2: final String message(){ 3: return "Hello!"; 4: } 5: } 6: class Main extends MainClass { 7: public static void main(String[] args) { 8: System.out.println(message()); 9: } 10: String message(){ 11: return "World!"; 12: } 13: } **Explanation:** Compilation error at line 10 because of final methods cannot be overridden, and here message() is a final method, and also note that Non-static method message() cannot be referenced from a static context.

1.

It will not compile because of line 10.

2.

"Hello!"

3.

It will not compile because of line 2.

4.

"World!"

Q 11 / 120

Java

Given this code, which command will output "2"?

java class Main { public static void main(String[] args) { System.out.println(args[2]); } }

1.

`java Main 1 2 "3 4" 5`

2.

`java Main 1 "2" "2" 5`

3.

`java Main.class 1 "2" 2 5`

4.

`java Main 1 "2" "3 4" 5`

Q 12 / 120

Java

What is the output of this code?

java class Main { public static void main(String[] args){ int a = 123451234512345; System.out.println(a); } } **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.

1.

"123451234512345"

2.

Nothing - this will not compile.

3.

a negative integer value

4.

"12345100000"

Q 13 / 120

Java

What is the output of this code?

java 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); } }

1.

The code does not compile.

2.

A runtime exception is thrown.

3.

"world!!world"

4.

"world!world!"

Q 14 / 120

Java

How do you write a foreach loop that will iterate over ArrayList<Pencil>pencilCase?

1.

`for (Pencil pencil : pencilCase) {}`

2.

`for (pencilCase.next()) {}`

3.

`for (Pencil pencil : pencilCase.iterator()) {}`

4.

`for (pencil in pencilCase) {}`

Q 15 / 120

Java

What does this code print?

java System.out.print("apple".compareTo("banana"));

1.

`0`

2.

positive number

3.

negative number

4.

compilation error

Q 16 / 120

Java

You have an ArrayList of names that you want to sort alphabetically. Which approach would **NOT** work?

1.

`names.sort(Comparator.comparing(String::toString))`

2.

`Collections.sort(names)`

3.

`names.sort(List.DESCENDING)`

4.

`names.stream().sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList())`

Q 17 / 120

Java

By implementing encapsulation, you cannot directly access the class's _ properties unless you are writing code inside the class itself.

1.

private

2.

protected

3.

no-modifier

4.

public

Q 18 / 120

Java

Which is the most up-to-date way to instantiate the current date?

**Explanation**: LocalDate is the newest class added in java 8

1.

`new SimpleDateFormat("yyyy-MM-dd").format(new Date())`

2.

`new Date(System.currentTimeMillis())`

3.

`LocalDate.now()`

4.

`Calendar.getInstance().getTime()`

Q 19 / 120

Java

Fill in the blank to create a piece of code that will tell whether `int0` is divisible by `5`:

`boolean isDivisibleBy5 = _____`

1.

`int0 / 5 ? true: false`

2.

`int0 % 5 == 0`

3.

`int0 % 5 != 5`

4.

`Math.isDivisible(int0, 5)`

Q 20 / 120

Java

How many times will this code print "Hello World!"?

java class Main { public static void main(String[] args){ for (int i=0; i<10; i=i++){ i+=1; System.out.println("Hello World!"); } } } **Explanation**: Observe the loop increment. It's not an increment, it's an assignment(post).

1.

10 times

2.

9 times

3.

5 times

4.

infinite number of times

Q 21 / 120

Java

The runtime system starts your program by calling which function first?

1.

print

2.

iterative

3.

hello

4.

main

Q 22 / 120

Java

What code would you use in Constructor A to call Constructor B?

java public class Jedi { /* Constructor A */ Jedi(String name, String species){} /* Constructor B */ Jedi(String name, String species, boolean followsTheDarkSide){} } **Note:** This code won't compile, possibly broken code sample.

1.

Jedi(name, species, false)

2.

new Jedi(name, species, false)

3.

this(name, species, false)

4.

super(name, species, false)

Q 23 / 120

Java

Which statement is **NOT** true?

1.

An anonymous class may specify an abstract base class as its base type.

2.

An anonymous class does not require a zero-argument constructor.

3.

An anonymous class may specify an interface as its base type.

4.

An anonymous class may specify both an abstract class and interface as base types.

Q 24 / 120

Java

What will this program print out to the console when executed?

java import java.util.LinkedList; public class Main { public static void main(String[] args){ LinkedList<Integer> list = new LinkedList<>(); list.add(5); list.add(1); list.add(10); System.out.println(list); } }

1.

[5, 1, 10]

2.

[10, 5, 1]

3.

[1, 5, 10]

4.

[10, 1, 5]

Q 25 / 120

Java

What is the output of this code?

java class Main { public static void main(String[] args){ String message = "Hello"; for (int i = 0; i<message.length(); i++){ System.out.print(message.charAt(i+1)); } } }

1.

"Hello"

2.

A runtime exception is thrown.

3.

The code does not compile.

4.

"ello"

Q 26 / 120

Java

Object-oriented programming is a style of programming where you organize your program around _ rather than _ and data rather than logic.

1.

functions; actions

2.

objects; actions

3.

actions; functions

4.

actions; objects

Q 27 / 120

Java

What statement returns true if "nifty" is of type String?

1.

`"nifty".getType().equals("String")`

2.

`"nifty".getType() == String`

3.

`"nifty".getClass().getSimpleName() == "String"`

4.

`"nifty" instanceof String`

Q 28 / 120

Java

What is the output of this code?

java 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); } }

1.

A runtime exception is thrown.

2.

3false

3.

2true

4.

3true

Q 29 / 120

Java

What is the result of this code?

java 1: class Main { 2: Object message(){ 3: return "Hello!"; 4: } 5: public static void main(String[] args) { 6: System.out.print(new Main().message()); 7: System.out.print(new Main2().message()); 8: } 9: } 10: class Main2 extends Main { 11: String message(){ 12: return "World!"; 13: } 14: }

1.

It will not compile because of line 7.

2.

Hello!Hello!

3.

Hello!World!

4.

It will not compile because of line 11.

Q 30 / 120

Java

What method can be used to create a new instance of an object?

1.

another instance

2.

field

3.

constructor

4.

private method

Q 31 / 120

Java

Which is the most reliable expression for testing whether the values of two string variables are the same?

1.

string1 == string2

2.

string1 = string2

3.

string1.matches(string2)

4.

string1.equals(string2)

Q 32 / 120

Java

Which letters will print when this code is run?

java public static void main(String[] args) { try { System.out.println("A"); badMethod(); System.out.println("B"); } catch (Exception ex) { System.out.println("C"); } finally { System.out.println("D"); } } public static void badMethod() { throw new Error(); } **Explanation**: `Error` is not inherited from `Exception`

1.

A, B, and D

2.

A, C, and D

3.

C and D

4.

A and D

Q 33 / 120

Java

What is the output of this code?

java 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!"); } }

1.

It will throw a runtime exception.

2.

It will not compile.

3.

It will print "Hello World!" three times.

4.

It will run forever.

Q 34 / 120

Java

What is the output of this code?

java 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)); } } **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.)

1.

`[abc, 0, 2, 10]`

2.

The code does not compile.

3.

`[abc, 2, 10, 0]`

4.

`[0, 10, 2, abc]`

Q 35 / 120

Java

What is the output of this code?

java 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 += " "; } }

1.

Hello World!

2.

HelloHelloWorld!

3.

Hello Hello World!

4.

Hello HelloWorld!

Q 36 / 120

Java

What is displayed when this code is compiled and executed?

java public class Main { public static void main(String[] args) { int x = 5; x = 10; System.out.println(x); } }

1.

x

2.

null

3.

10

4.

5

Q 37 / 120

Java

Which approach cannot be used to iterate over a List named _theList_?

java for (int i = 0; i < theList.size(); i++) { System.out.println(theList.get(i)); } java for (Object object : theList) { System.out.println(object); } java Iterator it = theList.iterator(); for (it.hasNext()) { System.out.println(it.next()); } java theList.forEach(System.out::println); **Explanation:** `for (it.hasNext())` should be `while (it.hasNext())`.

1.

A

2.

B

3.

C

4.

D

Q 38 / 120

Java

What method signature will work with this code?

`boolean healthyOrNot = isHealthy("avocado");`

1.

public void isHealthy(String avocado)

2.

boolean isHealthy(String string)

3.

public isHealthy("avocado")

4.

private String isHealthy(String food)

Q 39 / 120

Java

Which are valid keywords in a Java module descriptor (module-info.java)?

1.

provides, employs

2.

imports, exports

3.

consumes, supplies

4.

requires, exports

Q 40 / 120

Java

Which type of variable keeps a constant value once it is assigned?

1.

non-static

2.

static

3.

final

4.

private

Q 41 / 120

Java

How does the keyword `volatile` affect how a variable is handled?

1.

It will be read by only one thread at a time.

2.

It will be stored on the hard drive.

3.

It will never be cached by the CPU.

4.

It will be preferentially garbage collected.

Q 42 / 120

Java

What is the result of this code?

java char smooch = 'x'; System.out.println((int) smooch);

1.

an alphanumeric character

2.

a negative number

3.

a positive number

4.

a ClassCastException

Q 43 / 120

Java

You get a NullPointerException. What is the most likely cause?

1.

A file that needs to be opened cannot be found.

2.

A network connection has been lost in the middle of communications.

3.

Your code has used up all available memory.

4.

The object you are using has not been instantiated.

Q 44 / 120

Java

How would you fix this code so that it compiles?

java public class Nosey { int age; public static void main(String[] args) { System.out.println("Your age is: " + age); } }

1.

Make age static.

2.

Make age global.

3.

Make age public.

4.

Initialize age to a number.

Q 45 / 120

Java

Add a Duck called "Waddles" to the ArrayList **ducks**.

java public class Duck { private String name; Duck(String name) {} } `ducks.add(waddles);` `ducks.add(waddles);`

1.

`Duck waddles = new Duck();`

2.

`Duck duck = new Duck("Waddles");`

3.

`ducks.add(new Duck("Waddles"));`

4.

`ducks.add(new Waddles());`

Q 46 / 120

Java

If you encounter `UnsupportedClassVersionError` it means the code was `___` on a newer version of Java than the JRE `___` it.

1.

executed; interpreting

2.

executed; compiling

3.

compiled; executing

4.

compiled, translating

Q 47 / 120

Java

Given this class, how would you make the code compile?

java public class TheClass { private final int x; } java public TheClass() { x += 77; } java public TheClass() { x = null; } java public TheClass() { x = 77; } java private void setX(int x) { this.x = x; } public TheClass() { setX(77); } **Explanation:** `final` class members are allowed to be assigned only in three places: declaration, constructor or an instance-initializer block.

1.

A

2.

B

3.

C

4.

D

Q 48 / 120

Java

How many times f will be printed?

java public class Solution { public static void main(String[] args) { for (int i = 44; i > 40; i--) { System.out.println("f"); } } }

1.

4

2.

3

3.

5

4.

A Runtime exception will be thrown

Q 49 / 120

Java

Which statements about `abstract` classes are true?

1. They can be instantiated. 2. They allow member variables and methods to be inherited by subclasses. 3. They can contain constructors.

1.

1, 2, and 3

2.

only 3

3.

2 and 3

4.

only 2

Q 50 / 120

Java

Which keyword lets you call the constructor of a parent class?

1.

parent

2.

super

3.

this

4.

new

Q 51 / 120

Java

What is the result of this code?

java 1: int a = 1; 2: int b = 0; 3: int c = a/b; 4: System.out.println(c);

1.

It will throw an ArithmeticException.

2.

It will run and output 0.

3.

It will not compile because of line 3.

4.

It will run and output infinity.

Q 52 / 120

Java

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?

1.

Add a static import.

2.

Declare local copies of the constant in your code.

3.

This cannot be done. You must always qualify references to static members with the class form which they came from.

4.

Put the static members in an interface and inherit from that interface.

Q 53 / 120

Java

Which keyword lets you use an interface?

1.

extends

2.

implements

3.

inherits

4.

import

Q 54 / 120

Java

Why are ArrayLists better than arrays?

1.

You don't have to decide the size of an ArrayList when you first make it.

2.

You can put more items into an ArrayList than into an array.

3.

ArrayLists can hold more kinds of objects than arrays.

4.

You don't have to decide the type of an ArrayList when you first make it.

Q 55 / 120

Java

Declare a variable that holds the first four digits of Π

**Reasoning:** java public class TestReal { public static void main (String[] argv) { double pi = 3.14159265; //accuracy up to 15 digits float pi2 = 3.141F; //accuracy up to 6-7 digits System.out.println ("Pi=" + pi); System.out.println ("Pi2=" + pi2); } } 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.

1.

int pi = 3.141;

2.

decimal pi = 3.141;

3.

double pi = 3.141;

4.

float pi = 3.141;

Q 56 / 120

Java

Use the magic power to cast a spell

java public class MagicPower { void castSpell(String spell) {} } `magicPower.castSpell();`

1.

`new MagicPower().castSpell("expecto patronum")`

2.

`MagicPower magicPower = new MagicPower();`

3.

`MagicPower.castSpell("expelliarmus");`

4.

`new MagicPower.castSpell();`

Q 57 / 120

Java

What language construct serves as a blueprint containing an object's properties and functionality?

1.

constructor

2.

instance

3.

class

4.

method

Q 58 / 120

Java

What does this code print?

java public static void main(String[] args) { int x=5,y=10; swapsies(x,y); System.out.println(x+" "+y); } static void swapsies(int a, int b) { int temp=a; a=b; b=temp; }

1.

10 10

2.

5 10

3.

10 5

4.

5 5

Q 59 / 120

Java

What is the result of this code?

java try { System.out.println("Hello World"); } catch (Exception e) { System.out.println("e"); } catch (ArithmeticException e) { System.out.println("e"); } finally { System.out.println("!"); }

1.

Hello World

2.

It will not compile because the second catch statement is unreachable

3.

Hello World!

4.

It will throw runtime exception

Q 60 / 120

Java

Which is not a java keyword

**Explanation:** `native` is a part of JNI interface

1.

finally

2.

native

3.

interface

4.

unsigned

Q 61 / 120

Java

Which operator would you use to find the remainder after division?

1.

`%`

2.

`//`

3.

`/`

4.

`DIV`

Q 62 / 120

Java

Which choice is a disadvantage of inheritance?

1.

Overridden methods of the parent class cannot be reused.

2.

Responsibilities are not evenly distributed between parent and child classes.

3.

Classes related by inheritance are tightly coupled to each other.

4.

The internal state of the parent class is accessible to its children.

Q 63 / 120

Java

Declare and initialize an array of 10 ints.

1.

`Array<Integer> numbers = new Array<Integer>(10);`

2.

`Array[int

3.

`int[

4.

`int numbers[

Q 64 / 120

Java

Refactor this event handler to a lambda expression:

java groucyButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Press me one more time.."); } });

1.

`groucyButton.addActionListener(ActionListener listener -> System.out.println("Press me one more time..."));`

2.

`groucyButton.addActionListener((event) -> System.out.println("Press me one more time..."));`

3.

`groucyButton.addActionListener(new ActionListener(ActionEvent e) {() -> System.out.println("Press me one more time...");});`

4.

`groucyButton.addActionListener(() -> System.out.println("Press me one more time..."));`

Q 65 / 120

Java

Which functional interfaces does Java provide to serve as data types for lambda expressions?

1.

Observer, Observable

2.

Collector, Builder

3.

Filter, Map, Reduce

4.

Consumer, Predicate, Supplier

Q 66 / 120

Java

What is a valid use of the hashCode() method?

1.

encrypting user passwords

2.

deciding if two instances of a class are equal

3.

enabling HashMap to find matches faster

4.

moving objects from a List to a HashMap

Q 67 / 120

Java

What kind of relationship does "extends" denote?

1.

uses-a

2.

is-a

3.

has-a

4.

was-a

Q 68 / 120

Java

How do you force an object to be garbage collected?

1.

Set object to null and call Runtime.gc()

2.

Set object to null and call System.gc()

3.

Set object to null and call Runtime.getRuntime().runFinalization()

4.

There is no way to force an object to be garbage collected

Q 69 / 120

Java

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.

1.

static factory method; singleton; strategy pattern

2.

strategy pattern; static factory method; singleton

3.

creation pattern; singleton; prototype pattern

4.

singleton; strategy pattern; static factory method

Q 70 / 120

Java

Using Java's Reflection API, you can use _ to get the name of a class and _ to retrieve an array of its methods.

1.

this.getClass().getSimpleName(); this.getClass().getDeclaredMethods()

2.

this.getName(); this.getMethods()

3.

Reflection.getName(this); Reflection.getMethods(this)

4.

Reflection.getClass(this).getName(); Reflection.getClass(this).getMethods()

Q 71 / 120

Java

Which is not a valid lambda expression?

1.

`a -> false;`

2.

`(a) -> false;`

3.

`String a -> false;`

4.

`(String a) -> false;`

Q 72 / 120

Java

Which access modifier makes variables and methods visible only in the class where they are declared?

1.

public

2.

protected

3.

nonmodifier

4.

private

Q 73 / 120

Java

What type of variable can be assigned to only once?

1.

private

2.

non-static

3.

final

4.

static

Q 74 / 120

Java

How would you convert a String to an Int?

1.

`"21".intValue()`

2.

`String.toInt("21")`

3.

`Integer.parseInt("21")`

4.

`String.valueOf("21")`

Q 75 / 120

Java

What method should be added to the Duck class to print the name Moby?

java public class Duck { private String name; Duck(String name) { this.name = name; } public static void main(String[] args) { System.out.println(new Duck("Moby")); } }

1.

`public String toString() { return name; } `

2.

`public void println() { System.out.println(name); } `

3.

`String toString() { return this.name; } `

4.

`public void toString() { System.out.println(this.name); } `

Q 76 / 120

Java

Which operator is used to concatenate Strings in Java

1.

`+`

2.

`&`

3.

`.`

4.

`-`

Q 77 / 120

Java

How many times does this loop print "exterminate"?

java for (int i = 44; i > 40; i--) { System.out.println("exterminate"); }

1.

two

2.

four

3.

three

4.

five

Q 78 / 120

Java

What is the value of myCharacter after line 3 is run?

java 1: public class Main { 2: public static void main (String[] args) { 3: char myCharacter = "piper".charAt(3); 4: } 5: }

1.

p

2.

r

3.

e

4.

i

Q 79 / 120

Java

When should you use a static method?

1.

when your method is related to the object's characteristics

2.

when you want your method to be available independently of class instances

3.

when your method uses an object's instance variable

4.

when your method is dependent on the specific instance that calls it

Q 80 / 120

Java

What phrase indicates that a function receives a copy of each argument passed to it rather than a reference to the objects themselves?

1.

pass by reference

2.

pass by occurrence

3.

pass by value

4.

API call

Q 81 / 120

Java

In Java, what is the scope of a method's argument or parameter?

1.

inside the method

2.

both inside and outside the method

3.

neither inside nor outside the method

4.

outside the method

Q 82 / 120

Java

What is the output of this code?

java public class Main { public static void main (String[] args) { int[] sampleNumbers = {8, 5, 3, 1}; System.out.println(sampleNumbers[2]); } }

1.

5

2.

8

3.

1

4.

3

Q 83 / 120

Java

Which change will make this code compile successfully?

java 1: public class Main { 2: String MESSAGE ="Hello!"; 3: static void print(){ 4: System.out.println(message); 5: } 6: void print2(){} 7: } **Explanation**: Changing line 2 to `public static final String message` raises the error `message not initialized in the default constructor`

1.

Change line 2 to `public static final String message`

2.

Change line 6 to `public void print2(){}`

3.

Remove the body of the `print2` method and add a semicolon.

4.

Remove the body of the `print` method.

Q 84 / 120

Java

What is the output of this code?

java import java.util.*; class Main { public static void main(String[] args) { String[] array = new String[]{"A", "B", "C"}; List<String> list1 = Arrays.asList(array); List<String> list2 = new ArrayList<>(Arrays.asList(array)); List<String> list3 = new ArrayList<>(Arrays.asList("A", new String("B"), "C")); System.out.print(list1.equals(list2)); System.out.print(list1.equals(list3)); } }

1.

falsefalse

2.

truetrue

3.

falsetrue

4.

truefalse

Q 85 / 120

Java

Which code snippet is valid?

1.

`ArrayList<String> words = new ArrayList<String>(){"Hello", "World"};`

2.

`ArrayList words = Arrays.asList("Hello", "World");`

3.

`ArrayList<String> words = {"Hello", "World"};`

4.

`ArrayList<String> words = new ArrayList<>(Arrays.asList("Hello", "World"));`

Q 86 / 120

Java

What is the output of this code?

java class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("hello"); sb.deleteCharAt(0).insert(0, "H")." World!"; System.out.println(sb); } }

1.

A runtime exception is thrown.

2.

"HelloWorld!"

3.

"hello"

4.

????

Q 87 / 120

Java

How would you use the TaxCalculator to determine the amount of tax on $50?

java class TaxCalculator { static calculate(total) { return total * .05; } } **Note:** This code won't compile, broken code sample

1.

TaxCalculator.calculate(50);

2.

new TaxCalculator.calculate(50);

3.

calculate(50);

4.

new TaxCalculator.calculate($50);

Q 88 / 120

Java

What is the output of this code?

java public class Main { public static void main(String[] args) { HashMap<String, Integer> pantry = new HashMap<>(); pantry.put("Apples", 3); pantry.put("Oranges", 2); int currentApples = pantry.get("Apples"); pantry.put("Apples", currentApples + 4); System.out.println(pantry.get("Apples")); } }

1.

3

2.

4

3.

6

4.

7

Q 89 / 120

Java

Which characteristic does not apply to instances of java.util.HashSet=

**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.

1.

uses hashcode of objects when inserted

2.

contains unordred elements

3.

contains unique elements

4.

contains sorted elements

Q 90 / 120

Java

What is the output?

java import java.util.*; public class Main { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<>(); queue.add(4); queue.add(3); queue.add(2); queue.add(1); while (queue.isEmpty() == false) { System.out.printf("%d", queue.remove()); } } }

1.

1 3 2 4

2.

4 2 3 1

3.

1 2 3 4

4.

4 3 2 1

Q 91 / 120

Java

What will this code print, assuming it is inside the main method of a class?

`System.out.println("hello my friends".split(" ")[0]);`

1.

my

2.

hellomyfriends

3.

hello

4.

friends

Q 92 / 120

Java

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()?

1.

2

2.

When calling the put method, Java will throw an exception

3.

4

4.

3

Q 93 / 120

Java

Which class acts as root class for Java Exception hierarchy?

1.

Clonable

2.

Throwable

3.

Object

4.

Serializable

Q 94 / 120

Java

Which class does not implement the java.util.Collection interface?

**Explanation**: HashMap class implements Map interface.

1.

java.util.Vector

2.

java.util.ArrayList

3.

java.util.HashSet

4.

java.util.HashMap

Q 95 / 120

Java

You have a variable of named `employees` of type `List<Employee>` containing multiple entries. The `Employee` type has a method `getName()` that returns te employee name. Which statement properly extracts a list of employee names?

1.

`employees.collect(employee -> employee.getName());`

2.

`employees.filter(Employee::getName).collect(Collectors.toUnmodifiableList());`

3.

`employees.stream().map(Employee::getName).collect(Collectors.toList());`

4.

`employees.stream().collect((e) -> e.getName());`

Q 96 / 120

Java

What is the correct return type for the `processFunction` method:

____ processFunction(Integer number, Function<Integer, String> lambda) { return lambda.apply(number); }

1.

Function<Integer, String>

2.

Integer

3.

String

4.

Consumer

Q 97 / 120

Java

This code does not compile. What needs to be changed so that it does?

public enum Direction { EAST("E"), WEST("W"), NORTH("N"), SOUTH("S"); private final String shortCode; public String getShortCode() { return shortCode; } }

1.

Add a constructor that accepts a `String` parameter and assigns it to the field `shortCode`.

2.

Remove the `final` keyword for the field `shortCode`.

3.

All enums need to be defined on a single line of code.

4.

Add a setter method for the field `shortCode`.

Q 98 / 120

Java

Which language feature ensures that objects implementing the `AutoCloseable` interface are closed when it completes?

1.

try-catch-finally

2.

try-finally-close

3.

try-with-resources

4.

try-catch-close

Q 99 / 120

Java

What code should go in line 3?

java class Main { public static void main(String[] args) { array[0] = new int[]{1, 2, 3}; array[1] = new int[]{4, 5, 6}; array[2] = new int[]{7, 8, 9}; for (int i = 0; i < 3; i++) System.out.print(array[i][1]); //prints 258 } }

1.

`int[][

2.

`int[][

3.

`int[][

4.

`int[][

Q 100 / 120

Java

Is this an example of method overloading or overriding?

java class Car { public void accelerate() {} } class Lambo extends Car { public void accelerate(int speedLimit) {} public void accelerate() {} }

1.

neither

2.

both

3.

overloading

4.

overriding

Q 101 / 120

Java

Which choice is the best data type for working with money in Java?

1.

float

2.

String

3.

double

4.

BigDecimal

Q 102 / 120

Java

Which statement about constructors is not ture?

1.

A class can have multiple constructors with a different parameter list.

2.

You can call another constructor with `this` or `super`.

3.

A constructor does not define a return value.

4.

Every class must explicitly define a constructor without parameters.

Q 103 / 120

Java

What language feature allows types to be parameters on classes, interfaces, and methods in order to reuse the same code for different data types?

1.

Regular Expressions

2.

Reflection

3.

Generics

4.

Concurrency

Q 104 / 120

Java

What will be printed?

java public class Berries{ String berry = "blue"; public static void main( String[] args ) { new Berries().juicy( "straw" ); } void juicy(String berry){ this.berry = "rasp"; System.out.println(berry + "berry"); } }

1.

raspberry

2.

strawberry

3.

blueberry

4.

rasp

Q 105 / 120

Java

What is the value of `forestCount` after this code executes?

java Map<String, Integer> forestSpecies = new HashMap<>(); forestSpecies.put("Amazon", 30000); forestSpecies.put("Congo", 10000); forestSpecies.put("Daintree", 15000); forestSpecies.put("Amazon", 40000); int forestCount = forestSpecies.size();

1.

3

2.

4

3.

2

4.

When calling the put method, Java will throw an exception

Q 106 / 120

Java

What is a problem with this code?

java import java.util.ArrayList; import java.util.Arrays; import java.util.List; class Main { public static void main( String[] args ) { List<String> list = new ArrayList<String>( Arrays.asList( "a", "b", "c" ) ); for( String value :list ){ if( value.equals( "a" ) ) { list.remove( value ); } } System.out.println(list); // outputs [b,c] } }

1.

String should be compared using == method instead of equals.

2.

Modifying a collection while iterating through it can throw a ConcurrentModificationException.

3.

The List interface does not allow an argument of type String to be passed to the remove method.

4.

ArrayList does not implement the List interface.

Q 107 / 120

Java

How do you convert this method into a lambda expression?

java public int square(int x){ return x * x; }

1.

`Function<Integer, Integer> squareLambda = (int x) -> { x * x };`

2.

`Function<Integer, Integer> squareLambda = () -> { return x * x };`

3.

`Function<Integer, Integer> squareLambda = x -> x * x;`

4.

`Function<Integer, Integer> squareLambda = x -> return x * x;`

Q 108 / 120

Java

Which choice is a valid implementation of this interface?

java interface MyInterface { int foo(int x); } java public class MyClass implements MyInterface { // .... public void foo(int x){ System.out.println(x); } } java public class MyClass implements MyInterface { // .... public double foo(int x){ return x * 100; } } java public class MyClass implements MyInterface { // .... public int foo(int x){ return x * 100; } } java public class MyClass implements MyInterface { // .... public int foo(){ return 100; } }

1.

A

2.

B

3.

C

4.

D

Q 109 / 120

Java

What is the result of this program?

java interface Foo{ int x = 10; } public class Main{ public static void main( String[] args ) { Foo.x = 20; System.out.println(Foo.x); } }

1.

10

2.

20

3.

null

4.

An error will occur when compiling.

Q 110 / 120

Java

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());

1.

`Integer val = 15;`

2.

`String val = "Sam";`

3.

`String val = null;`

4.

`Optional<String> val = Optional.empty();`

Q 111 / 120

Java

What will this code print, assuming it is inside the main method of a class?

java System.out.println(true && false || true); System.out.println(false || false && true);

1.

false </br> true

2.

true </br> true

3.

true </br> false

4.

false </br> false

Q 112 / 120

Java

What will this code print?

java List<String> list1 = new ArrayList<>(); list1.add( "One" ); list1.add( "Two" ); list1.add( "Three" ); List<String> list2 = new ArrayList<>(); list2.add( "Two" ); list1.remove( list2 ); System.out.println(list1);

1.

`[Two]`

2.

`[One, Two, Three]`

3.

`[One, Three]`

4.

`Two`

Q 113 / 120

Java

Which code checks whether the characters in two Strings,named `time` and `money`, are the same?

1.

`if(time <> money){}`

2.

`if(time.equals(money)){}`

3.

`if(time == money){}`

4.

`if(time = money){}`

Q 114 / 120

Java

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.

1.

exception,assertion

2.

AbnormalException, AccidentalException

3.

error, exception

4.

exception, error

Q 115 / 120

Java

Which keyword would not be allowed here?

java class Unicorn { _____ Unicorn(){} }

1.

static

2.

protected

3.

public

4.

void

Q 116 / 120

Java

Which OOP concept is this code an example of?

java List[] myLists = { new ArrayList<>(), new LinkedList<>(), new Stack<>(), new Vector<>(), }; for (List list : myLists){ list.clear(); } **Explanation:** switch between different implementations of the `List` interface

1.

composition

2.

generics

3.

polymorphism

4.

encapsulation

Q 117 / 120

Java

What does this code print?

java String a = "bikini"; String b = new String("bikini"); String c = new String("bikini"); System.out.println(a == b); System.out.println(b == c); **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.

1.

true; false

2.

false; false

3.

false; true

4.

true; true

Q 118 / 120

Java

Which is the problem with this code?

java class Main { public static void main(String[] args) { List<String> list = new ArrayList<String>(Arrays.asList("a","b","c")); for (String value : list) { if (value.equals("a")){ list.remove(value); } } System.out.println(list); //outputs [b,c] } }

1.

ArrayList does not implement the `List` interface.

2.

The `List` interface does not allow an argument of type String to be passed to the remove method.

3.

Strings should be compared using `==` instead of `equals`.

4.

Modifying a collection while iterating through it can throw a ConcurrentModificationException

Q 119 / 120

Java

What keyword is added to a method declaration to ensure that two threads do not simultaneously execute it on the same object instance?

1.

native

2.

volatile

3.

synchronized

4.

lock

Q 120 / 120