Java LinkedIn Skill Assessment Answer

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

  1. rawb
  2. raw✔️
  3. awb
  4. traw

Q2. How can you achieve runtime polymorphism in Java?

  1. method overloading
  2. method overrunning
  3. method overriding✔️
  4. method calling

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

Q5. What is the output of this code?

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

Q6. 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!");
    }
}
  1. super1.print(); super2.print();
  2. this.print();
  3. super.print();
  4. Interface1.print(); Interface2.print();✔️

Q7. What does the following code print?

String str = "abcde";
str.trim();
str.toUpperCase();
str.substring(3, 4);
System.out.println(str);
  1. CD
  2. CDE
  3. D
  4. abcde✔️

Q8. What is the result of this code?

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.

Q9. Which class can compile given these declarations?

interface One {
    default void method() {
        System.out.println("One");
    }
}

interface Two {
    default void method () {
        System.out.println("One");
    }
}
  1. A
class Three implements One, Two {
    public void method() {
        super.One.method();
    }
}
  1. B
class Three implements One, Two {
    public void method() {
        One.method();
    }
}
  1. C
class Three implements One, Two {
}
  1. D✔️
class Three implements One, Two {
    public void method() {
        One.super.method();
    }
}

Q10. What is the output of this code?

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

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

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));
    }
}
  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”✔️

Q12. What is the result of this code?

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: }
  1. It will not compile because of line 10.✔️
  2. “Hello!”
  3. It will not compile because of line 2.
  4. “World!”

Q13. Given this code, which command will output “2”?

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

Q14. What is the output of this code?

class Main {
    public static void main(String[] args){
        int a = 123451234512345;
        System.out.println(a);
    }
}
  1. “123451234512345”
  2. Nothing – this will not compile.✔️
  3. a negative integer value
  4. “12345100000”

Q15. What is the output of this code?

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!”

Q16. 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) {}

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

Q19. What does this code print?

System.out.print(“apple”.compareTo(“banana”));

  1. 0
  2. positive number
  3. negative number✔️
  4. compilation error

Q20. 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())

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

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

  1. new SimpleDateFormat(“yyyy-MM-dd”).format(new Date())
  2. new Date(System.currentTimeMillis())
  3. LocalDate.now()✔️
  4. Calendar.getInstance().getTime()

Q23. 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)

Q24. 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!");
        }
    }
}
  1. 10 times✔️
  2. 9 times
  3. 5 times
  4. infinite number of times

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

  1. print
  2. iterative
  3. hello
  4. main✔️

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

public class Jedi {
  /* Constructor A */
  Jedi(String name, String species){}

  /* Constructor B */
  Jedi(String name, String species, boolean followsTheDarkSide){}
  }
  1. Jedi(name, species, false)
  2. new Jedi(name, species, false)
  3. this(name, species, false)✔️
  4. super(name, species, false)

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

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

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]

Q29. What is the output of this code?

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”

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

Q31. 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✔️

Q32. What is the output of this code?

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✔️

Q33. What is the result of this code?

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.

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

  1. another instance
  2. field
  3. constructor✔️
  4. private method

Q35. 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)✔️

Q36. Which letters will print when this code is run?

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();
}
  1. A, B, and D
  2. A, C, and D
  3. C and D
  4. A and D✔️

Q37. What is the output of this code?

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.

Q38. What is the output of this code?

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));
	}
}
  1. [abc, 0, 2, 10]
  2. The code does not compile.
  3. [abc, 2, 10, 0]
  4. [0, 10, 2, abc]✔️

Q39. What is the output of this code?

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!

Q40. What is displayed when this code is compiled and executed?

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

Q41. Which approach cannot be used to iterate over a List named theList?

  1. A
for (int i = 0; i < theList.size(); i++) {
    System.out.println(theList.get(i));
}
  1. B
for (Object object : theList) {
    System.out.println(object);
}
  1. C✔️
Iterator it = theList.iterator();
for (it.hasNext()) {
    System.out.println(it.next());
}
  1. D
theList.forEach(System.out::println);

Q42. 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)

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

  1. provides, employs
  2. imports, exports
  3. consumes, supplies
  4. requires, exports✔️

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

  1. non-static
  2. static
  3. final✔️
  4. private

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

Q46. What is the result of this code?

char smooch = 'x';
System.out.println((int) smooch);
  1. an alphanumeric character
  2. a negative number
  3. a positive number✔️
  4. a ClassCastException

Q47. 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.✔️

Q48. How would you fix this code so that it compiles?

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.

Q49. Add a Duck called “Waddles” to the ArrayList ducks.

public class Duck {
	private String name;
	Duck(String name) {}
}
  1. Duck waddles = new Duck(); ducks.add(waddles);
  2. Duck duck = new Duck(“Waddles”); ducks.add(waddles);
  3. ducks.add(new Duck(“Waddles”));✔️
  4. ducks.add(new Waddles());

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

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

public class TheClass {
    private final int x;
}
  1. A
public TheClass() {
    x += 77;
}
  1. B
public TheClass() {
    x = null;
}
  1. C✔️
public TheClass() {
    x = 77;
}
  1. D
private void setX(int x) {
    this.x = x;
}
public TheClass() {
    setX(77);
}

Q52. How many times f will be printed?

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

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

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

  1. parent
  2. super✔️
  3. this
  4. new

Q55. What is the result of this code?

  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.

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

Q57. Which keyword lets you use an interface?

  1. extends
  2. implements✔️
  3. inherits
  4. import

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

Q59. Declare a variable that holds the first four digits of Π

  1. int pi = 3.141;
  2. decimal pi = 3.141;
  3. double pi = 3.141;✔️
  4. float pi = 3.141;

Q60. Use the magic power to cast a spell

public class MagicPower {
    void castSpell(String spell) {}
}
  1. new MagicPower().castSpell(“expecto patronum”)✔️
  2. MagicPower magicPower = new MagicPower(); magicPower.castSpell();
  3. MagicPower.castSpell(“expelliarmus”);
  4. new MagicPower.castSpell();

Q61. What language construct serves as a blueprint containing an object’s properties and functionality?

  1. constructor
  2. instance
  3. class✔️
  4. method

Q62. What does this code print?

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

Q63. What is the result of this code?

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

Q64. What is not a java keyword

  1. finally
  2. native
  3. interface
  4. unsigned✔️

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

  1. %✔️
  2. //
  3. /
  4. DIV

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

Q67. Declare and initialize an array of 10 ints.

  1. Array<Integer> numbers = new Array<Integer>(10);
  2. Array[int] numbers = new Arrayint;
  3. int[] numbers = new int[10];✔️
  4. int numbers[] = int[10];

Q68. Refactor this event handler to a lambda expression:

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…”));

Q69. 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✔️

Q70. What kind of relationship does “extends” denote?

  1. uses-a
  2. is-a✔️
  3. has-a
  4. was-a

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

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

Q73. 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()

Q74. Which is not a valid lambda expression?

  1. a -> false;
  2. (a) -> false;
  3. String a -> false;✔️
  4. (String a) -> false;

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

  1. public
  2. protected
  3. nonmodifier
  4. private✔️

Q76. What type of variable can be assigned to only once?

  1. private
  2. non-static
  3. final✔️
  4. static

Q77. How would you convert a String to an Int?

  1. “21”.intValue()
  2. String.toInt(“21”)
  3. Integer.parseInt(“21”)✔️
  4. String.valueOf(“21”)

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

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

Q79. Which operator is used to concatenate Strings in Java

  1. +✔️
  2. &
  3. .
  4. -

Q80. How many times does this loop print “exterminate”?

for (int i = 44; i > 40; i--) {
    System.out.println("exterminate");
}
  1. two
  2. four✔️
  3. three
  4. five

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

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

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

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

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

Q85. What is the output of this code?

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✔️

Q86. Which change will make this code compile successfully?

1: public class Main {
2:   String MESSAGE ="Hello!";
3:   static void print(){
4:     System.out.println(message);
5:   }
6:   void print2(){}
7: }
  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.✔️

Q87. What is the output of this code?

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

Q88. 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”));✔️

Q89. What is the output of this code?

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

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

public class Jedi {
  /* Constructor A */
  Jedi(String name, String species){}

  /* Constructor B */
  Jedi(String name, String species, boolean followsTheDarkSide){}
  }
  1. Jedi(name, species, false)
  2. new Jedi(name, species, false)
  3. this(name, species, false)✔️
  4. super(name, species, false)

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

1: public class Main {
2:   public static void main (String[] args) {
3:     char myCharacter = "piper".chatAt(3);
4:   }
5: }
  1. p
  2. i
  3. r
  4. e✔️

Q92. What is the output of this code?

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 run forever.
  2. it will print “Hello World!” three times.✔️
  3. it will not compile.
  4. it will throw a runtime exception.

Q93. What is the output of this code?

 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✔️

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

  1. uses hashcode of objects when inserted
  2. contains unordred elements✔️
  3. contains unique elements
  4. contains sorted elements

Q95. What is the output?

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

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

class TaxCalculator {
  static calculate(total) {
    return total * .05;
  }
}
  1. TaxCalculator.calculate(50);✔️
  2. new TaxCalculator.calculate(50);
  3. calculate(50);
  4. new TaxCalculator.calculate($50);

Code sample

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

Q98. What code should go in line 3?

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[][] array = new int[][];
  2. int[][] array = new int[3][3];✔️
  3. int[][] array = new int[2][2];
  4. int[][] array = [][];

Q99. Is this an example of method overloading or overriding?

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

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

  1. float
  2. String
  3. double
  4. BigDecimal✔️

Reference

Q101. 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.✔️

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?

  1. Regular Expressions
  2. Reflection
  3. Generics✔️
  4. Concurrency

Q103. What will be printed?

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

Q104. What is the value of forestCount after this code executes?

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

Q105. What is a problem with this code?

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.

Q106. How do you convert this method into a lambda expression?

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;

Q107. Which choice is a valid implementation of this interface?

interface MyInterface {
    int foo(int x);
}
  1. A
public class MyClass implements MyInterface {
    // ....
    public void foo(int x){
        System.out.println(x);
    }
}
  1. B
public class MyClass implements MyInterface {
    // ....
    public double foo(int x){
        return x * 100;
    }
}
  1. C✔️
public class MyClass implements MyInterface {
    // ....
    public int foo(int x){
        return x * 100;
    }
}
  1. D
public class MyClass implements MyInterface {
    // ....
    public int foo(){
        return 100;
    }
}

Q108. What is the result of this program?

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.✔️

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());
  1. Integer val = 15;
  2. String val = “Sam”;✔️
  3. String val = null;
  4. Optional<String> val = Optional.empty();

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

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

Q111. What will this code print?

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

Q112. 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){}

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.

  1. exception,assertion
  2. AbnormalException, AccidentalException
  3. error, exception✔️
  4. exception, error

Q114. Which keyword would not be allowed here?

class Unicorn {
    _____ Unicorn(){}
}
  1. static✔️
  2. protected
  3. public
  4. void

Q115. Which OOP concept is this code an example of?

List[] myLists = {
    new ArrayList<>(),
    new LinkedList<>(),
    new Stack<>(),
    new Vector<>(),
};

for (List list : myLists){
    list.clear();
}
  1. composition
  2. generics
  3. polymorphism✔️
  4. encapsulation

Q116. What does this code print?

String a = "bikini";
String b = new String("bikini");
String c = new String("bikini");

System.out.println(a == b);
System.out.println(b == c);
  1. true; false
  2. false; false✔️
  3. false; true
  4. true; true

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

Java Documentation: Synchronized methods

Q118. Which is a valid type for this lambda function?

_____ oddOrEven = x -> {
    return x % 2 == 0 ? "even" : "odd";
};
  1. Function<Integer, Boolean>
  2. Function<String>
  3. Function<Integer, String>✔️
  4. Function<Integer>

Explaination

Q119. What is displayed when this code is compiled and executed?

import java.util.HashMap;

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. 6
  2. 3
  3. 4
  4. 7✔️

Explanation

Q120. What variable type should be declared for capitalize?

List<String> songTitles = Arrays.asList("humble", "element", "dna");
_______ capitalize = (str) -> str.toUpperCase();
songTitles.stream().map(capitalize).forEach(System.out::println);
  1. Function<String, String>✔️
  2. Stream<String>
  3. String<String, String>
  4. Map<String, String>

Q121. Which is the correct return type for the processFunction method?

_____ processFunction(Integer number, Function<Integer, String> lambda) {
        return lambda.apply(number);
    }
  1. Integer
  2. String✔️
  3. Consumer
  4. Function<Integer, String>

Q122. What function could you use to replace slashes for dashes in a list of dates?

List<String> dates = new ArrayList<String>();
// missing code
dates.replaceAll(replaceSlashes);
  1. UnaryOperator<String> replaceSlashes = date -> date.replace(“/”, “-“);✔️
  2. Function<String, String> replaceSlashes = dates -> dates.replace(“-“, “/”);
  3. Map<String, String> replaceSlashes = dates.replace(“/”, “-“);
  4. Consumer<Date> replaceSlashes = date -> date.replace(“/”, “-“);

Q123. From which class do all other classes implicitly extend?

  1. Object✔️
  2. Main
  3. Java
  4. Class

Explanation

Q124. How do you create and run a Thread for this class?

import java.util.date;

public class CurrentDateRunnable implements Runnable {
    @Override
    public void run () {
        while (true) {
            System.out.println("Current date: " + new Date());

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
  1. Thread thread = new Thread(new CurrentDateRunnable()); thread.start();✔️
  2. new Thread(new CurrentDateRunnable()).join();
  3. new CurrentDateRunnable().run();
  4. new CurrentDateRunnable().start();

Q125. Which expression is a functional equivalent?

List<Integer> numbers = List.of(1,2,3,4);
int total = 0;

for (Integer x : numbers) {
    if (x % 2 == 0)
    total += x * x;
}
  1. A
int total = numbers.stream()
                        .transform(x -> x * x)
                        .filter(x -> x % 2 == 0)
                        .sum ();
  1. B
int total = numbers.stream()
                        .filter(x -> x % 2 == 0)
                        .collect(Collectors.toInt());
  1. C
int total = numbers.stream()
                        .mapToInt (x -> {if (x % 2 == 0) return x * x;})
                        .sum();
  1. D✔️
int total = numbers.stream()
                        .filter(x -> x % 2 == 0)
                        .mapToInt(x -> x * x)
                        .sum();

Q126. Which is not one of the standard input/output streams provided by java.lang.System?

  1. print✔️
  2. out
  3. err
  4. 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;
  1. Use the method toInt() to convert pickle before assigning it to jar.
  2. Cast pickle to an int before assigning it to jar.✔️
  3. Make pickle into a double by adding + “.0”
  4. Use the new keyword to create a new Integer from pickle before assigning it to jar.

Q128. What value should x have to make this loop execute 10 times?

for(int i=0; i<30; i+=x) {}

  1. 10
  2. 3✔️
  3. 1
  4. 0

Q129. The __ runs compiled Java code, while the __ compiles Java files.

  1. IDE; JRE
  2. JDK; IDE
  3. JRE; JDK✔️
  4. JDK; JRE

Reference

Q130. Which packages are part of Java Standard Edition

  1. java.net
  2. java.util
  3. java.lang
  4. All above✔️

Reference

Q131. What values for x and y will cause this code to print “btc”?

String buy = "bitcoin";
System.out.println(buy.substring(x, x+1) + buy.substring(y, y+2))
  1. int x = 0; int y = 2;✔️
  2. int x = 1; int y = 3;
  3. int x = 0; int y = 3;
  4. int x = 1; int y = 3;

Q132. Which keyword would you add to make this method the entry point of the program?

  1. exception
  2. args
  3. static✔️
  4. String

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?

  1. Implement the comparable interface by overriding the compareTo method.✔️
  2. Add the keyword default to the weight variable.
  3. Override the equals method inside the Bunny class.
  4. Implement Sortable and override the sortBy method.

Q134. Identify the incorrect Java feature.

  1. Object oriented
  2. Use of pointers✔️
  3. Dynamic
  4. Architectural neural

Q135. What is the output of this code?

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!");
}
  1. cotton
  2. cotton <br> leather
  3. cotton <br> leather <br> I don’t gotta buy gifts for nobody!✔️
  4. cotton <br> I don’t gotta buy gifts for nobody!

Q136. What language feature do these expressions demonstrate?

System.out::println
Doggie::fetch
  1. condensed invocation
  2. static references
  3. method references✔️
  4. bad code

Q137. What is the difference between the wait() and sleep methods?

  1. Only Threads can wait, but any Object can be put to sleep.
  2. A wait can be woken up by another Thread calling notify whereas a sleep cannot.
  3. When things go wrong, sleep throws an IllegalMonitorStateException whereas wait throws an InterruptedException.✔️
  4. Sleep allows for multi-threading whereas wait does not.

Q138. Which is the right way to declare an enumeration of cats?

  1. enum Cats (SPHYNX, SIAMESE, BENGAL);
  2. enum Cats (“sphynx”, “siamese”, “bengal”);
  3. enum Cats {SPHYNX, SIAMESE, BENGAL}✔️
  4. enum Cats {“sphynx”,”siamese”,”bengal}

Q139. What happens when this code is run?

List<String> horses = new ArrayList<String>();
horses.add (" Sea Biscuit ");
System.out.println(horses.get(1).trim());
  1. “Sea Biscuit” will be printed.
  2. ” Sea Biscuit ” will be printed.
  3. An IndexOutOfBoundsException will be thrown.✔️
  4. A NullPointerException will be thrown.

Q140. Which data structure would you choose to associate the amount of rainfall with each month?

  1. Vector
  2. LinkedList
  3. Map✔️
  4. Queue

Q141. Among the following which contains date information.

  1. java.sql timestamp✔️
  2. java.io time
  3. java.io.timestamp
  4. java.sql.time

Q142. What is the size of float and double in java?

  1. 32 and 64✔️
  2. 32 and 32
  3. 64 and 64
  4. 64 and 32

Q143. When you pass an object reference as an argument to a method call what gets passed?

  1. a reference to a copy
  2. a copy of the reference
  3. the object itself
  4. the original reference✔️

Q144. Which choice demonstrates a valid way to create a reference to a static function of another class?

  1. Function<Integer, Integer> funcReference = MyClass::myFunction;✔️
  2. Function<Integer, Integer> funcReference = MyClass.myFunction;
  3. Function<Integer, Integer> funcReference = MyClass().myFunction();
  4. Function<Integer, Integer> funcReference = MyClass::myFunction();

Q145. What is UNICODE?

  1. Unicode is used for external representation of words and strings
  2. Unicode is used for internal representation of characters and strings
  3. Unicode is used for external representation of characters and strings✔️
  4. Unicode is used for internal representation of words and strings

Q146. What kind of thread is the Garbage collector thread?

  1. User thread
  2. Daemon thread✔️
  3. Both
  4. None of these

Q147. What is HashMap and Map?

  1. HashMap is Interface and map is class that implements that
  2. HashMap is class and map is interface that implements that
  3. Map is class and Hashmap is interface that implements that
  4. Map is Interface and Hashmap is class that implements that✔️

Q148. What invokes a thread’s run() method?

  1. JVM invokes the thread’s run() method when the thread is initially executed.✔️
  2. Main application running the thread.
  3. start() method of the thread class.
  4. None of the above.

Q149. What is true about a final class?

  1. class declared final is a final class.
  2. Final classes are created so the methods implemented by that class cannot be overriddden.
  3. It can’t be inherited.
  4. All of the above.✔️

Q150. Which method can be used to find the highest value of x and y?

  1. Math.largest(x,y)
  2. Math.maxNum(x,y)
  3. Math.max(x,y)✔️
  4. Math.maximum(x,y)

Q151. What do these statments evaluate to?

    1. false 2. true
    1. false 2. false
    1. true 2. true
  1. 1. true 2. false✔️

Q152. Which of these does Stream filter() operates on?

  1. Predicate✔️
  2. Interface
  3. Class
  4. Methods

Q153. Which of these does Stream map() operates on?

  1. Class
  2. Interface
  3. Predicate
  4. Function✔️

Q154. What code is needed at line 8?

1: class Main {

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

3:          Map<String, Integer> map = new HashMap<>();
4:          map.put("a", 1);
5:          map.put("b", 2);
6:          map.put("c", 3);

7:          int result = 0;

8:
9:              result += entry.getValue();
10:         }

11:         System.out.println(result); // outputs 6
12:     }
13: }
  1. for(MapEntry<String, Integer> entry: map.entrySet()) {
  2. for(String entry: map) {
  3. for(Integer entry: map.values()) {
  4. for(Entry<String, Integer> entry: map.entrySet()) {✔️

Q155. What will print when Lambo is instantiated?

class Car {
    String color = "blue";
}

class Lambo extends Car {
    String color = "white";

    public Lambo() {
        System.out.println(super.color);
        System.out.println(this.color);
        System.out.println(color);
    }
}
  1. blue white white✔️
  2. blue white blue
  3. white white white
  4. white white blue

Q156. Which command will run a FrogSounds app that someone emailed to you as a jar?

  1. jar FrogSounds.java
  2. javac FrogSounds.exe
  3. jar cf FrogSounds.jar
  4. java -jar FrogSounds.jar✔️

Q157. What is the default value of short variable?

  1. 0✔️
  2. 0.0
  3. null
  4. undefined

Q158. What will be the output of the following Java program?

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);
        }
}
  1. Compilation Error✔️
  2. Runtime Error
  3. 5 6 5 6
  4. 5 6 5

Q159. Subclasses of an abstract class are created using the keyword __.

  1. extends✔️
  2. abstracts
  3. interfaces
  4. implements

Reference See An Abstract Class Example

Q160. What language feature do these expressions demonstrate?

System.out::println
Doggie::fetch
  1. method references✔️
  2. bad code
  3. condensed invocation
  4. static references

Reference

Q161. What will be the output of the following program?

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);
    }
}
  1. course java tutorial Merit campus
  2. course java course java tutorial Merit campus✔️
  3. Compilation Error
  4. Runtime Error

Q162. Calculate the time complexity of the following program.

 void printUnorderedPairs(int[] arrayA, int[] arrayB){
    for(int i = 0; i < arrayA.length; i++){
        for(int  j = 0; j < arrayB.length; j++){
            if(arrayA[i] < arrayB[j]){
                System.out.println(arrayA[i] + "," + arrayB[j]);
            }
        }
    }
 }
  1. O(N*N)
  2. O(1)
  3. O(AB)✔️
  4. O(A*B)

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

Q164. 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✔️

Q165. Which class acts as root class for Java Exception hierarchy?

  1. Clonable
  2. Throwable✔️
  3. Object
  4. Serializable

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

  1. java.util.Vector
  2. java.util.ArrayList
  3. java.util.HashSet
  4. java.util.HashMap✔️

Q167. 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?

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

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

Q169. void accept(T t) is method of -?

  1. Consumer✔️
  2. Producer
  3. Both
  4. None

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top