linkedin-skill-assessments-quizzes

Java

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

Q2. How can you achieve runtime polymorphism in Java?

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

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

Q4. 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: }

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

Q6. What does the following code print?

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

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

Q8. 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");
    }
}
class Three implements One, Two {
    public void method() {
        super.One.method();
    }
}
class Three implements One, Two {
    public void method() {
        One.method();
    }
}
class Three implements One, Two {
}
class Three implements One, Two {
    public void method() {
        One.super.method();
    }
}

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

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

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

is Type-Import-on-Demand Declarations, which never causes any other declaration to be shadowed.

Q11. 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: }

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.

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

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

Q13. What is the output of this code?

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.

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

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

Q16. What does this code print?

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

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

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

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

Explanation: LocalDate is the newest class added in java 8

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

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?

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

Q24. Which statement is NOT true?

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

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

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

Q28. What statement returns true if “nifty” is of type String?

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

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

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

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

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

Explanation: Error is not inherited from Exception

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

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

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

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

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

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

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

Explanation: for (it.hasNext()) should be while (it.hasNext()).

Q39. What method signature will work with this code?

boolean healthyOrNot = isHealthy("avocado");

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

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

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

Q43. What is the result of this code?

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

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

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

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

public class Duck {
	private String name;
	Duck(String name) {}
}

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

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

public class TheClass {
    private final int x;
}
public TheClass() {
    x += 77;
}
public TheClass() {
    x = null;
}
public TheClass() {
    x = 77;
}
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.

Q49. 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");
        }
    }
}

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

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

Q52. 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);

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?

Q54. Which keyword lets you use an interface?

Q55. Why are ArrayLists better than arrays?

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

Reasoning:

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.

Q57. Use the magic power to cast a spell

public class MagicPower {
    void castSpell(String spell) {}
}

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

Q59. 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;
}

Q60. 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("!");
}

Q61. Which is not a java keyword

Explanation: native is a part of JNI interface

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

Reference

Q63. Which choice is a disadvantage of inheritance?

Reference

Q64. Declare and initialize an array of 10 ints.

Q65. 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..");
    }
});

Reference

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

Reference

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

Reference

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

Reference

Q69. How do you 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.

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

Q72. Which is not a valid lambda expression?

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

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

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

Q76. 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"));
    }
}

Q77. Which operator is used to concatenate Strings in Java

Reference

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

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

Q79. 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: }

Q80. When should you use a static method?

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

Q82. In Java, what is the scope of a method’s argument or parameter?

Q83. 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]);
  }
}

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

Explanation: Changing line 2 to public static final String message raises the error message not initialized in the default constructor

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

Q86. Which code snippet is valid?

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

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

class TaxCalculator {
  static calculate(total) {
    return total * .05;
  }
}

Note: This code won’t compile, broken code sample

Reference

Code sample

Q89. 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"));
    }
}

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

Reference

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

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

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

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

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

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

Explanation: HashMap class implements Map interface.

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

Q97. What is the correct return type for the processFunction method:

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

Q98. 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;
    }
}

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

Q100. 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
    }
}

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

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

Q103. Which statement about constructors is not ture?

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

Q105. 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");
    }
}

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

Q107. 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]
    }
}

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

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

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

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

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

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

Q112. 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);

Q113. 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);

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

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

Q116. Which keyword would not be allowed here?

class Unicorn {
    _____ Unicorn(){}
}

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

Explanation: switch between different implementations of the List interface

Q118. 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);

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.

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

Java Documentation: Synchronized methods

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

_____ oddOrEven = x -> {
    return x % 2 == 0 ? "even" : "odd";
};

Explaination, Reference

Q121. 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);

Explanation, Reference

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

Explanation: replaceAll method for any List only accepts UnaryOperator to pass every single element into it then put the result into the List again.

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

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

Reference

Q125. What keyword would not be allowed here?

class Unicorn {

    ______ Unicorn(){}
}

Q126. 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;
}
int total = numbers.stream()
                        .transform(x -> x * x)
                        .filter(x -> x % 2 == 0)
                        .sum ();
int total = numbers.stream()
                        .filter(x -> x % 2 == 0)
                        .collect(Collectors.toInt());
int total = numbers.stream()
                        .mapToInt (x -> {if (x % 2 == 0) return x * x;})
                        .sum();
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

numbers                         // Input `List<Integer>` > [1, 2, 3, 4] <br>
    .stream()                   // Converts input into `Stream<Integer>` <br>
    .filter(x -> x % 2 == 0)    // Filter even numbers and return `Stream<Integer>` > [2, 4] <br>
    .mapToInt(x -> x * x)       // Square the number, converts `Integer` to an `int`, and returns `IntStream` > [4, 16] <br>
    .sum()                      // Returns the sum as `int` > 20