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. The first argument being the index to start(includes that char at 2) and the second the index of the string to end the substring(excludes the char at 5). Strings in Java are like arrays of chars. Therefore the method will return “raw” as those are the chars in indexes 2,3, and 4. You can also take the ending index and subtract the beginning index from it, to determine how many chars will be included in the substring (5-2=3).

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 can you use to create new instances in Java?

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

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

Q7. What does the following code print?

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

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

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

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

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

Explanation: The answer is “123”. The abs() method evaluates to the one inside mypackage.Math class.

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

Explanation: Non-static method message() cannot be referenced from a static context.

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

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

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

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);
    }
}
String m = "Hello world!";
String n = m.substring(6,12) + m.substring(12,6);
System.out.println(n);

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

Q17. Fill in the blanks?

Q18. What code would you use to tell if “schwifty” is of type String?

Q19. What does this code print?

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

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

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

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

Explanation: LocalDate is newest class added in java 8

Q23. Fill in the blank to create a piece of code that will tell wether int0 is divisible by 5:

boolean isDivisibleBy5 = _____

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

Reason : Observe the loop increment. It’s not an increment, it’s an assignment(post).

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

Q26. What is the result of this code?

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

Q27. Which statement is NOT true?

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

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

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

Q31. What statement returns true if “nifty” is of type 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);
	}
}

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

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

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

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

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

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

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

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

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

Q42. What method signature will work with this code?

boolean healthyOrNot = isHealthy("avocado");

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

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

Q45. How does the keyword _volatile_ affect how a variable is handled?

Q46. What is the result of this code?

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

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

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

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

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

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

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

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

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.

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

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

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?

Q57. Which keyword lets you use an interface?

Q58. Why are ArrayLists better than arrays?

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

Reasoning:

public class TestReal {
    public static void main (String[] argv)
    {
      double pi = 3.14159265;       //accuaracy upto 15 digits
      float pi2 = 3.141F;                //accuracy upto 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.

Q60. Use the magic power to cast a spell

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

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

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

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

Q64. What is not a java keyword

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

Reference

Q66. Which choice is a disadvantage of inheritance?

Reference

Q67. Declare and initialize an array of 10 ints.

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

Reference

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

Reference

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

Reference

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

Reference

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

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

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

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

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

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

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

Q79. Which operator is used to concatenate Strings in Java

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

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

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

Q82. When should you use a static method?

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

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

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

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

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

Q88. Which code snippet is valid?

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