Java LinkedIn Skill Assessment Answer

Here, We see Java LinkedIn Skill Assessment Answer. This assessment test consists of 15-20 MCQs to demonstrate your knowledge of your selected skills. MCQs come from different topics – Java Control Flow, Core API, Functional Programming, Fundamentals, and Object-Oriented Programming.

List of all LinkedIn Skills Assessment Answer

Java LinkedIn Skill Assessment Answer

Java LinkedIn Skill Assessment Answer

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

  •  rawb
  •  raw
  •  awb
  •  traw

Q2. How can you achieve runtime polymorphism in Java?

  •  method overloading
  •  method overrunning
  •  method overriding
  •  method calling

Q3. Given the following definitions, which of these expressions will NOT be considered true?

boolean b1 = true, b2 = false; int i1 = 1, i2 = 2;Code language: JavaScript (javascript)
  •  (i1 | i2) == 3
  •  i2 && b1
  •  b1 || !b2
  •  (i1 ^ i2) < 4

Reasoning: i2 && b1 are not allowed between int and boolean.

Q4. What is the output of this code?

classMain {
  publicstaticvoidmain(String[] args) {
    int array[] = {1, 2, 3, 4};
    for (inti=0; i < array.size(); i++) {
       System.out.print(array[i]);
    }
  }
}Code language: PHP (php)
  •  It will not compile because of line 4.
  •  It will not compile because of line 3.
  •  123
  •  1234

Q5. Which of the following can replace the CODE SNIPPET to make the code below print “Hello World”?

interfaceInterface1 {
    staticvoidprint() {
        System.out.print("Hello");
    }
}

interfaceInterface2 {
    staticvoidprint() {
        System.out.print("World!");
    }
}Code language: PHP (php)
  •  super1.print(); super2.print();
  •  this.print();
  •  super.print();
  •  Interface1.print(); Interface2.print();

Reference

Q6. What does the following code print?

Stringstr="abcde";
str.trim();
str.toUpperCase();
str.substring(3, 4);
System.out.println(str);
Code language: JavaScript (javascript)
  •  CD
  •  CDE
  •  D
  •  “abcde”

Q7. What is the result of this code?

classMain {
    publicstaticvoidmain(String[] args){
        System.out.println(print(1));
    }
    static Exception print(int i){
        if (i>0) {
            returnnewException();
        } else {
            thrownewRuntimeException();
        }
    }
}
Code language: PHP (php)
  •  It will show a stack trace with a runtime exception.
  •  “java.lang.Exception”
  •  It will run and throw an exception.
  •  It will not compile.

Q8. Which class can compile given these declarations?

interfaceOne {
    defaultvoidmethod() {
        System.out.println("One");
    }
}

interfaceTwo {
    defaultvoidmethod() {
        System.out.println("One");
    }
}
Code language: JavaScript (javascript)
  •  A
classThreeimplementsOne, Two {
    publicvoidmethod() {
        super.One.method();
    }
}
Code language: JavaScript (javascript)
  •  B
classThreeimplementsOne, Two {
    publicvoidmethod() {
        One.method();
    }
}
  •  C
classThreeimplementsOne, Two {
}
Code language: CSS (css)
  •  D
classThreeimplementsOne, Two {
    publicvoidmethod() {
        One.super.method();
    }
}

Q9. What is the output of this code?

classMain {
    publicstaticvoidmain(String[] args) {
        Listlist=newArrayList();
        list.add("hello");
        list.add(2);
        System.out.print(list.get(0) instanceof Object);
        System.out.print(list.get(1) instanceof Integer);
    }
}
Code language: PHP (php)
  •  The code does not compile.
  •  truefalse
  •  truetrue
  •  falsetrue

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

package mypackage;
publicclassMath {
    publicstaticintabs(int num){
        return num < 0 ? -num : num;
    }
}
package mypackage.elementary;
publicclassMath {
    publicstaticintabs(int num) {
        return -num;
    }
}
Code language: JavaScript (javascript)
import mypackage.Math;
import mypackage.elementary.*;

classMain {
    publicstaticvoidmain(String args[]){
        System.out.println(Math.abs(123));
    }
}
Code language: JavaScript (javascript)
  •  Lines 1 and 2 generate compiler errors due to class name conflicts.
  •  “-123”
  •  It will throw an exception on line 5.
  •  “123”

Q11. What is the result of this code?

classMainClass {
    final String message() {
        return"Hello!";
    }
}

classMainextendsMainClass {
    publicstaticvoidmain(String[] args) {
        System.out.println(message());
    }

     String message() {
         return"World!";
     }
 }
Code language: JavaScript (javascript)
  •  It will not compile because of line 10.
  •  “Hello!”
  •  It will not compile because of line 2.
  •  “World!”

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

classMain {
    publicstaticvoidmain(String[] args) {
        System.out.println(args[2]);
    }
}
Code language: JavaScript (javascript)
  •  java Main 1 2 “3 4” 5
  •  java Main 1 “2” “2” 5
  •  java Main.class 1 “2” 2 5
  •  java Main 1 “2” “3 4” 5

Q13. What is the output of this code?

classMain {
    publicstaticvoidmain(String[] args){
        inta=123451234512345;
        System.out.println(a);
    }
}
Code language: JavaScript (javascript)
  •  “123451234512345”
  •  Nothing – this will not compile.
  •  a negative integer value
  •  “12345100000”

Q14. What is the output of this code?

classMain {
    publicstaticvoidmain(String[] args) {
        Stringmessage="Hello world!";
        StringnewMessage= message.substring(6, 12)
            + message.substring(12, 6);
        System.out.println(newMessage);
    }
}
Code language: JavaScript (javascript)
  •  The code does not compile.
  •  A runtime exception is thrown.
  •  “world!!world”
  •  “world!world!”

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

  •  for (Pencil pencil : pencilCase) {}
  •  for (pencilCase.next()) {}
  •  for (Pencil pencil : pencilCase.iterator()) {}
  •  for (pencil in pencilCase) {}

Q16. What does this code print?

System.out.print("apple".compareTo("banana"));
Code language: CSS (css)
  •  0
  •  positive number
  •  negative number
  •  compilation error

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

  •  names.sort(Comparator.comparing(String::toString))
  •  Collections.sort(names)
  •  names.sort(List.DESCENDING)
  •  names.stream().sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList())

Reference

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

  •  private
  •  protected
  •  no-modifier
  •  public

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

  •  new SimpleDateFormat(“yyyy-MM-dd”).format(new Date())
  •  new Date(System.currentTimeMillis())
  •  LocalDate.now()
  •  Calendar.getInstance().getTime()

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

boolean isDivisibleBy5 = _____

  •  int0 / 5 ? true: false
  •  int0 % 5 == 0
  •  int0 % 5 != 5
  •  Math.isDivisible(int0, 5)

Q21. How many times will this code print “Hello World!”?

classMain {
    publicstaticvoidmain(String[] args){
        for (int i=0; i<10; i=i++){
            i+=1;
            System.out.println("Hello World!");
        }
    }
}
Code language: HTML, XML (xml)
  •  10 times
  •  9 times
  •  5 times
  •  infinite number of times

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

  •  print
  •  iterative
  •  hello
  •  main

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

publicclassJedi {
  <em>/* Constructor A */</em>
  Jedi(String name, String species){}

  <em>/* Constructor B */</em>
  Jedi(String name, String species, boolean followsTheDarkSide){}
}
Code language: HTML, XML (xml)
  •  Jedi(name, species, false)
  •  new Jedi(name, species, false)
  •  this(name, species, false)
  •  super(name, species, false)

Reference

Q24. “An anonymous class requires a zero-argument constructor.” that’s not true?

  •  An anonymous class may specify an abstract base class as its base type.
  •  An anonymous class does not require a zero-argument constructor.
  •  An anonymous class may specify an interface as its base type.
  •  An anonymous class may specify both an abstract class and interface as base types.

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

import java.util.LinkedList;

publicclassMain {
    publicstaticvoidmain(String[] args){
        LinkedList<Integer> list = newLinkedList<>();
        list.add(5);
        list.add(1);
        list.add(10);
        System.out.println(list);
    }
}
Code language: PHP (php)
  •  [5, 1, 10]
  •  [10, 5, 1]
  •  [1, 5, 10]
  •  [10, 1, 5]

Q26. What is the output of this code?

classMain {
    publicstaticvoidmain(String[] args){
       Stringmessage="Hello";
       for (inti=0; i<message.length(); i++){
          System.out.print(message.charAt(i+1));
       }
    }
}
Code language: JavaScript (javascript)
  •  “Hello”
  •  A runtime exception is thrown.
  •  The code does not compile.
  •  “ello”

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

  •  functions; actions
  •  objects; actions
  •  actions; functions
  •  actions; objects

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

  •  “nifty”.getType().equals(“String”)
  •  “nifty”.getType() == String
  •  “nifty”.getClass().getSimpleName() == “String”
  •  “nifty” instanceof String

Q29. What is the output of this code?

import java.util.*;
classMain {
    publicstaticvoidmain(String[] args) {
        List<Boolean> list = newArrayList<>();
        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);
    }
}
Code language: PHP (php)
  •  A runtime exception is thrown.
  •  3false
  •  2true
  •  3true

Q30. What is the result of this code?

classMain {
    Object message() {
        return"Hello!";
    }
    publicstaticvoidmain(String[] args) {
        System.out.print(newMain().message());
        System.out.print(newMain2().message());
    }
}
classMain2extendsMain {
    String message() {
        return"World!";
    }
}
Code language: JavaScript (javascript)
  •  It will not compile because of line 7.
  •  Hello!Hello!
  •  Hello!World!
  •  It will not compile because of line 11.

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

  •  another instance
  •  field
  •  constructor
  •  private method

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

  •  string1 == string2
  •  string1 = string2
  •  string1.matches(string2)
  •  string1.equals(string2)

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

publicstaticvoidmain(String[] args) {
    try {
        System.out.println("A");
        badMethod();
        System.out.println("B");
    } catch (Exception ex) {
        System.out.println("C");
    } finally {
        System.out.println("D");
    }
}
publicstaticvoidbadMethod() {
    thrownewError();
}
Code language: JavaScript (javascript)
  •  A, B, and D
  •  A, C, and D
  •  C and D
  •  A and D

Explanation: Error is not inherited from Exception.

Q34. What is the output of this code?

classMain {
    staticintcount=0;
    publicstaticvoidmain(String[] args) {
        if (count < 3) {
            count++;
            main(null);
        } else {
            return;
        }
        System.out.println("Hello World!");
    }
}
Code language: JavaScript (javascript)
  •  It will throw a runtime exception.
  •  It will not compile.
  •  It will print “Hello World!” three times.
  •  It will run forever.

Q35. What is the output of this code?

import java.util.*;
classMain {
    publicstaticvoidmain(String[] args) {
        String[] array = {"abc", "2", "10", "0"};
        List<String> list = Arrays.asList(array);
        Collections.sort(list);
        System.out.println(Arrays.toString(array));
    }
}
Code language: PHP (php)
  •  [abc, 0, 2, 10]
  •  The code does not compile.
  •  [abc, 2, 10, 0]
  •  [0, 10, 2, abc]

Explanation: The java.util.Arrays.asList(T... a) returns a fixed-size list backed by the specified array. (Changes to the returned list “write through” to the array.)

Q36. What is the output of this code?

classMain {
    publicstaticvoidmain(String[] args) {
        Stringmessage="Hello";
        print(message);
        message += "World!";
        print(message);
    }
    staticvoidprint(String message) {
        System.out.print(message);
        message += " ";
    }
}
Code language: PHP (php)
  •  Hello World!
  •  HelloHelloWorld!
  •  Hello Hello World!
  •  Hello HelloWorld!

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

publicclassMain {
    publicstaticvoidmain(String[] args) {
        intx=5;
        x = 10;
        System.out.println(x);
    }
}
Code language: JavaScript (javascript)
  •  x
  •  null
  •  10
  •  5

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

  •  A
for (inti=0; i < theList.size(); i++) {
    System.out.println(theList.get(i));
}
  •  B
for (Object object : theList) {
    System.out.println(object);
}
Code language: JavaScript (javascript)
  •  C
Iteratorit= theList.iterator();
for (it.hasNext()) {
    System.out.println(it.next());
}
  •  D
theList.forEach(System.out::println);
Code language: CSS (css)

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

Q39. What method signature will work with this code?

boolean healthyOrNot = isHealthy("avocado");Code language: JavaScript (javascript)
  •  public void isHealthy(String avocado)
  •  boolean isHealthy(String string)
  •  public isHealthy(“avocado”)
  •  private String isHealthy(String food)

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

  •  provides, employs
  •  imports, exports
  •  consumes, supplies
  •  requires, exports

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

  •  non-static
  •  static
  •  final
  •  private

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

  •  It will be read by only one thread at a time.
  •  It will be stored on the hard drive.
  •  It will never be cached by the CPU.
  •  It will be preferentially garbage collected.

Q43. What is the result of this code?

charsmooch='x';
System.out.println((int) smooch);
Code language: JavaScript (javascript)
  •  an alphanumeric character
  •  a negative number
  •  a positive number
  •  a ClassCastException

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

  •  A file that needs to be opened cannot be found.
  •  A network connection has been lost in the middle of communications.
  •  Your code has used up all available memory.
  •  The object you are using has not been instantiated.

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

publicclassNosey {
    int age;
    publicstaticvoidmain(String[] args) {
        System.out.println("Your age is: " + age);
    }
}
Code language: JavaScript (javascript)
  •  Make age static.
  •  Make age global.
  •  Make age public.
  •  Initialize age to a number.

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

publicclassDuck {
    private String name;
    Duck(String name) {}
}
Code language: JavaScript (javascript)
  •  Duck waddles = new Duck(); ducks.add(waddles);
  •  Duck duck = new Duck(“Waddles”); ducks.add(waddles);
  •  ducks.add(new Duck(“Waddles”));
  •  ducks.add(new Waddles());

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

  •  executed; interpreting
  •  executed; compiling
  •  compiled; executing
  •  compiled, translating

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

publicclassTheClass {
    privatefinalint x;
}
  •  A
publicTheClass() {
    x += 77;
}
  •  B
publicTheClass() {
    x = null;
}
Code language: JavaScript (javascript)
  •  C
publicTheClass() {
    x = 77;
}
  •  D
privatevoidsetX(int x) {
    this.x = x;
}
publicTheClass() {
    setX(77);
}
Code language: JavaScript (javascript)

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?

publicclassSolution {
    publicstaticvoidmain(String[] args) {
        for (inti=44; i > 40; i--) {
            System.out.println("f");
        }
    }
}
Code language: JavaScript (javascript)
  •  4
  •  3
  •  5
  •  A Runtime exception will be thrown

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.
  •  1, 2, and 3
  •  only 3
  •  2 and 3
  •  only 2

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

  •  parent
  •  super
  •  this
  •  new

Q52. What is the result of this code?

1: inta=1;
  2: intb=0;
  3: intc= a/b;
  4: System.out.println(c);
  •  It will throw an ArithmeticException.
  •  It will run and output 0.
  •  It will not compile because of line 3.
  •  It will run and output infinity.

Q53. Normally, to access a static member of a class such as Math.PI, you would need to specify the class “Math”. What would be the best way to allow you to use simply “PI” in your code?

  •  Add a static import.
  •  Declare local copies of the constant in your code.
  •  This cannot be done. You must always qualify references to static members with the class from which they came from.
  •  Put the static members in an interface and inherit from that interface.

Q54. Which keyword lets you use an interface?

  •  extends
  •  implements
  •  inherits
  •  Import

Q55. Why are ArrayLists better than arrays?

  •  You don’t have to decide the size of an ArrayList when you first make it.
  •  You can put more items into an ArrayList than into an array.
  •  ArrayLists can hold more kinds of objects than arrays.
  •  You don’t have to decide the type of an ArrayList when you first make it.

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

  •  int pi = 3.141;
  •  decimal pi = 3.141;
  •  double pi = 3.141;
  •  float pi = 3.141;

Reasoning:

publicclassTestReal {
    publicstaticvoidmain(String[] argv)
    {
      doublepi=3.14159265;       <em>//accuracy up to 15 digits</em>floatpi2=3.141F;           <em>//accuracy up to 6-7 digits</em>

      System.out.println ("Pi=" + pi);
      System.out.println ("Pi2=" + pi2);
    }
  }
Code language: JavaScript (javascript)
The default Java type which Java will be used for a float variable will be double.
So, even if you declare any variable as float, what the compiler has to do is 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.
Code language: JavaScript (javascript)

Q57. Use the magic power to cast a spell

publicclassMagicPower {
    voidcastSpell(String spell) {}
}
Code language: JavaScript (javascript)
  •  new MagicPower().castSpell(“expecto patronum”);
  •  MagicPower magicPower = new MagicPower(); magicPower.castSpell();
  •  MagicPower.castSpell(“expelliarmus”);
  •  new MagicPower.castSpell();

Reference

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

  •  constructor
  •  instance
  •  class
  •  method

Q59. What does this code print?

publicstaticvoidmain(String[] args) {
    int x=5,y=10;
    swapsies(x,y);
    System.out.println(x+" "+y);
}

staticvoidswapsies(int a, int b) {
    int temp=a;
    a=b;
    b=temp;
}
Code language: JavaScript (javascript)
  •  10 10
  •  5 10
  •  10 5
  •  5 5

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("!");
}
Code language: PHP (php)
  •  Hello World
  •  It will not compile because the second catch statement is unreachable
  •  Hello World!
  •  It will throw a runtime exception

Q61. Which is not a Java keyword

  •  finally
  •  native
  •  interface
  •  unsigned

Explanation: native is a part of the JNI interface.

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

  •  %
  •  //
  •  /
  •  DIV

Reference

Q63. Which choice is a disadvantage of inheritance?

  •  Overridden methods of the parent class cannot be reused.
  •  Responsibilities are not evenly distributed between parent and child classes.
  •  Classes related by inheritance are tightly coupled to each other.
  •  The internal state of the parent class is accessible to its children.

Reference

Q64. How would you declare and initialize an array of 10 ints?

  •  Array<Integer> numbers = new Array<Integer>(10);
  •  Array[int] numbers = new Array[int](10);
  •  int[] numbers = new int[10];
  •  int numbers[] = int[10];

Q65. Refactor this event handler to a lambda expression:

groucyButton.addActionListener(newActionListener() {
    @OverridepublicvoidactionPerformed(ActionEvent e) {
        System.out.println("Press me one more time..");
    }
});
Code language: JavaScript (javascript)
  •  groucyButton.addActionListener(ActionListener listener -> System.out.println(“Press me one more time…”));
  •  groucyButton.addActionListener((event) -> System.out.println(“Press me one more time…”));
  •  groucyButton.addActionListener(new ActionListener(ActionEvent e) {() -> System.out.println(“Press me one more time…”);});
  •  groucyButton.addActionListener(() -> System.out.println(“Press me one more time…”));

Reference

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

  •  Observer, Observable
  •  Collector, Builder
  •  Filter, Map, Reduce
  •  Consumer, Predicate, Supplier

Reference

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

  •  encrypting user passwords
  •  deciding if two instances of a class are equal
  •  enabling HashMap to find matches faster
  •  moving objects from a List to a HashMap

Reference

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

  •  uses-a
  •  is-a
  •  has-a
  •  was-a

Reference

Q69. How do you force an object to be garbage collected?

  •  Set object to null and call Runtime.gc()
  •  Set object to null and call System.gc()
  •  Set object to null and call Runtime.getRuntime().runFinalization()
  •  There is no way to force an object to be garbage-collected

Reference

Q70. Java programmers commonly use design patterns. Some examples are the _, which helps create instances of a class, the _, which ensures that only one instance of a class can be created; and the _, which allows for a group of algorithms to be interchangeable.

  •  static factory method; singleton; strategy pattern
  •  strategy pattern; static factory method; singleton
  •  creation pattern; singleton; prototype pattern
  •  singleton; strategy pattern; static factory method

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

  •  this.getClass().getSimpleName(); this.getClass().getDeclaredMethods()
  •  this.getName(); this.getMethods()
  •  Reflection.getName(this); Reflection.getMethods(this)
  •  Reflection.getClass(this).getName(); Reflection.getClass(this).getMethods()

Q72. Which is not a valid lambda expression?

  •  a -> false;
  •  (a) -> false;
  •  String a -> false;
  •  (String a) -> false;

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

  •  public
  •  protected
  •  nonmodifier
  •  private

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

  •  private
  •  non-static
  •  final
  •  static

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

  •  “21”.intValue()
  •  String.toInt(“21”)
  •  Integer.parseInt(“21”)
  •  String.valueOf(“21”)

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

publicclassDuck {
    private String name;

    Duck(String name) {
        this.name = name;
    }

    publicstaticvoidmain(String[] args) {
        System.out.println(newDuck("Moby"));
    }
}
Code language: JavaScript (javascript)
  •  public String toString() { return name; }
  •  public void println() { System.out.println(name); }
  •  String toString() { return this.name; }
  •  public void toString() { System.out.println(this.name); }

Q77. Which operator is used to concatenate Strings in Java

  •  +
  •  &
  •  .
  •  –

Reference

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

for (inti=44; i > 40; i--) {
    System.out.println("exterminate");
}
Code language: JavaScript (javascript)
  •  two
  •  four
  •  three
  •  five

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

publicclassMain {
  publicstaticvoidmain(String[] args) {
    charmyCharacter="piper".charAt(3);
  }
}
Code language: JavaScript (javascript)
  •  p
  •  r
  •  e
  •  i

Q80. When should you use a static method?

  •  when your method is related to the object’s characteristics
  •  when you want your method to be available independently of class instances
  •  when your method uses an object’s instance variable
  •  when your method is dependent on the specific instance that calls it

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

  •  pass by reference
  •  pass by occurrence
  •  pass by value
  •  API call

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

  •  inside the method
  •  both inside and outside the method
  •  neither inside nor outside the method
  •  outside the method

Q83. What is the output of this code?

publicclassMain {
  publicstaticvoidmain(String[] args) {
    int[] sampleNumbers = {8, 5, 3, 1};
    System.out.println(sampleNumbers[2]);
  }
}
Code language: JavaScript (javascript)
  •  5
  •  8
  •  1
  •  3

Q84. Which change will make this code compile successfully?

publicclassMain {
  StringMESSAGE="Hello!";
  staticvoidprint(){
    System.out.println(message);
  }
  voidprint2(){}
}
Code language: JavaScript (javascript)
  •  Change line 2 to public static final String message
  •  Change line 6 to public void print2(){}
  •  Remove the body of the print2 method and add a semicolon.
  •  Remove the body of the print method.

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.*;
classMain {
  publicstaticvoidmain(String[] args) {
    String[] array = newString[]{"A", "B", "C"};
    List<String> list1 = Arrays.asList(array);
    List<String> list2 = newArrayList<>(Arrays.asList(array));
    List<String> list3 = newArrayList<>(Arrays.asList("A", newString("B"), "C"));
    System.out.print(list1.equals(list2));
    System.out.print(list1.equals(list3));
  }
}
Code language: PHP (php)
  •  falsefalse
  •  truetrue
  •  falsetrue
  •  truefalse

Q86. Which code snippet is valid?

  •  ArrayList<String> words = new ArrayList<String>(){“Hello”, “World”};
  •  ArrayList words = Arrays.asList(“Hello”, “World”);
  •  ArrayList<String> words = {“Hello”, “World”};
  •  ArrayList<String> words = new ArrayList<>(Arrays.asList(“Hello”, “World”));

Q87. What is the output of this code?

classMain {
  publicstaticvoidmain(String[] args) {
    StringBuildersb=newStringBuilder("hello");
    sb.deleteCharAt(0).insert(0, "H").append(" World!");
    System.out.println(sb);
  }
}
Code language: JavaScript (javascript)
  •  It will not compile.
  •  “Hello World!”
  •  “hello”
  •  ???? The code effectively converts the initial “hello” into “HelloWorld!” by deleting the first character, inserting “H” at the beginning, and appending ” World!” to the end.

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

classTaxCalculator {
  staticcalculate(total) {
    return total * .05;
  }
}
Code language: JavaScript (javascript)
  •  TaxCalculator.calculate(50);
  •  new TaxCalculator.calculate(50);
  •  calculate(50);
  •  new TaxCalculator.calculate($50);

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

  1. Reference
  2. Code sample

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

  •  uses hashcode of objects when inserted
  •  contains unordred elements
  •  contains unique elements
  •  contains sorted elements

Explanation: HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

Reference

Q90. What is the output?

import java.util.*;

publicclassMain {
    publicstaticvoidmain(String[] args)
    {
        PriorityQueue<Integer> queue = newPriorityQueue<>();
        queue.add(4);
        queue.add(3);
        queue.add(2);
        queue.add(1);

        while (queue.isEmpty() == false) {
            System.out.printf("%d", queue.remove());
        }
    }
}
Code language: JavaScript (javascript)
  •  1 3 2 4
  •  4 2 3 1
  •  1 2 3 4
  •  4 3 2 1

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

System.out.println("hello my friends".split(" ")[0]);Code language: CSS (css)
  •  my
  •  hellomyfriends
  •  hello
  •  friends

Q92. You have an instance of type Map<String, Integer> named instruments containing the following key-value pairs: guitar=1200, cello=3000, and drum=2000. If you add the new key-value pair cello=4500 to the Map using the put method, how many elements do you have in the Map when you call instruments.size()?

  •  2
  •  When calling the put method, Java will throw an exception
  •  4
  •  3

Q93. Which class acts as the root class for the Java Exception hierarchy?

  •  Clonable
  •  Throwable
  •  Object
  •  Serializable

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

  •  java.util.Vector
  •  java.util.ArrayList
  •  java.util.HashSet
  •  java.util.HashMap

Explanation: HashMap class implements Map interface.

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

  •  employees.collect(employee -> employee.getName());
  •  employees.filter(Employee::getName).collect(Collectors.toUnmodifiableList());
  •  employees.stream().map(Employee::getName).collect(Collectors.toList());
  •  employees.stream().collect((e) -> e.getName());

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

publicenumDirection {
    EAST("E"),
    WEST("W"),
    NORTH("N"),
    SOUTH("S");

    privatefinal String shortCode;

    public String getShortCode() {
        return shortCode;
    }
}
Code language: JavaScript (javascript)
  •  Add a constructor that accepts a String parameter and assigns it to the field shortCode.
  •  Remove the final keyword for the field shortCode.
  •  All enums need to be defined on a single line of code.
  •  Add a setter method for the field shortCode.

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

  •  try-catch-finally
  •  try-finally-close
  •  try-with-resources
  •  try-catch-close

Q98. What code should go in line 3?

classMain {
    publicstaticvoidmain(String[] args) {
        array[0] = newint[]{1, 2, 3};
        array[1] = newint[]{4, 5, 6};
        array[2] = newint[]{7, 8, 9};
        for (inti=0; i < 3; i++)
            System.out.print(array[i][1]); <em>//prints 258</em>
    }
 }
Code language: PHP (php)
  •  int[][] array = new int[][];
  •  int[][] array = new int[3][3];
  •  int[][] array = new int[2][2];
  •  int[][] array = [][];

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

classCar {
    publicvoidaccelerate() {}
}
classLamboextendsCar {
    publicvoidaccelerate(int speedLimit) {}
    publicvoidaccelerate() {}
}
  •  neither
  •  both
  •  overloading
  •  overriding

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

  •  float
  •  String
  •  double
  •  BigDecimal

Reference

Q101. Which statement about constructors is not true?

  •  A class can have multiple constructors with a different parameter list.
  •  You can call another constructor with this or super.
  •  A constructor does not define a return value.
  •  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?

  •  Regular Expressions
  •  Reflection
  •  Generics
  •  Concurrency

Q103. What will be printed?

publicclassBerries{

    Stringberry="blue";

    publicstaticvoidmain(String[] args) {
        newBerries().juicy("straw");
    }
    voidjuicy(String berry){
        this.berry = "rasp";
        System.out.println(berry + "berry");
    }
}
Code language: JavaScript (javascript)
  •  raspberry
  •  strawberry
  •  blueberry
  •  rasp

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

Map<String, Integer> forestSpecies = newHashMap<>();

forestSpecies.put("Amazon", 30000);
forestSpecies.put("Congo", 10000);
forestSpecies.put("Daintree", 15000);
forestSpecies.put("Amazon", 40000);

intforestCount= forestSpecies.size();
Code language: JavaScript (javascript)
  •  3
  •  4
  •  2
  •  When calling the put method, Java will throw an exception

Q105. What is the problem with this code?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


classMain {

    publicstaticvoidmain(String[] args) {
        List<String> list = newArrayList<String>(Arrays.asList("a", "b", "c"));
        for(String value :list) {
            if(value.equals("a")) {
                list.remove(value);
            }
        }
        System.out.println(list); <em>// outputs [b,c]</em>
    }
}
Code language: JavaScript (javascript)
  •  String should be compared using == method instead of equals.
  •  Modifying a collection while iterating through it can throw a ConcurrentModificationException.
  •  The List interface does not allow an argument of type String to be passed to the remove method.
  •  ArrayList does not implement the List interface.

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

publicintsquare(int x) {
    return x * x;
}
Code language: JavaScript (javascript)
  •  Function<Integer, Integer> squareLambda = (int x) -> { x * x };
  •  Function<Integer, Integer> squareLambda = () -> { return x * x };
  •  Function<Integer, Integer> squareLambda = x -> x * x;
  •  Function<Integer, Integer> squareLambda = x -> return x * x;

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

interfaceMyInterface {
    intfoo(int x);
}
  •  A
publicclassMyClassimplementsMyInterface {
    <em>// ....</em>publicvoidfoo(int x){
        System.out.println(x);
    }
}
Code language: HTML, XML (xml)
  •  B
publicclassMyClassimplementsMyInterface {
    <em>// ....</em>publicdoublefoo(int x){
        return x * 100;
    }
}
Code language: HTML, XML (xml)
  •  C
publicclassMyClassimplementsMyInterface {
    <em>// ....</em>publicintfoo(int x){
        return x * 100;
    }
}Code language: HTML, XML (xml)
  •  D
publicclassMyClassimplementsMyInterface {
    <em>// ....</em>publicintfoo(){
        return100;
    }
}
Code language: HTML, XML (xml)

Q108. What is the result of this program?

interfaceFoo {
    intx=10;
}

publicclassMain{

    publicstaticvoidmain(String[] args) {
        Foo.x = 20;
        System.out.println(Foo.x);
    }
}
Code language: JavaScript (javascript)
  •  10
  •  20
  •  null
  •  An error will occur when compiling.

Q109. Which statement must be inserted on line 1 to print the value true?

1:
2: Optional<String> opt = Optional.of(val);
3: System.out.println(opt.isPresent());
Code language: HTML, XML (xml)
  •  Integer val = 15;
  •  String val = “Sam”;
  •  String val = null;
  •  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);
Code language: JavaScript (javascript)
  •  false
    true
  •  true
    true
  •  true
    false
  •  false
    false

Q111. What will this code print?

List<String> list1 = newArrayList<>();
list1.add("One");
list1.add("Two");
list1.add("Three");

List<String> list2 = newArrayList<>();
list2.add("Two");

list1.remove(list2);
System.out.println(list1);
Code language: JavaScript (javascript)
  •  [Two]
  •  [One, Two, Three]
  •  [One, Three]
  •  Two

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

  •  if(time <> money){}
  •  if(time.equals(money)){}
  •  if(time == money){}
  •  if(time = money){}

Q113. An _ is a serious issue thrown by the JVM that the JVM is unlikely to recover from. An _ is an unexpected event that an application may be able to deal with to continue execution.

  •  exception, assertion
  •  AbnormalException, AccidentalException
  •  error, exception
  •  exception, error

Q114. Which keyword would not be allowed here?

classUnicorn {
    _____ Unicorn(){}
}
  •  static
  •  protected
  •  public
  •  void

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

List[] myLists = {
    newArrayList<>(),
    newLinkedList<>(),
    newStack<>(),
    newVector<>(),
};

for (List list : myLists){
    list.clear();
}
Code language: HTML, XML (xml)
  •  composition
  •  generics
  •  polymorphism
  •  encapsulation

Explanation: Switch between different implementations of the List interface.

Q116. What does this code print?

Stringa="bikini";
Stringb=newString("bikini");
Stringc=newString("bikini");

System.out.println(a == b);
System.out.println(b == c);
Code language: JavaScript (javascript)
  •  true; false
  •  false; false
  •  false; true
  •  true; true

Explanation: == operator compares the object reference. String a = "bikini"; String b = "bikini"; would result in True. Here new creates a new object, so false. Use equals() method to compare the content.

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

  •  native
  •  volatile
  •  synchronized
  •  lock

Reference

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

_____oddOrEven= x -> {
    return x % 2 == 0 ? "even" : "odd";
};
Code language: JavaScript (javascript)
  •  Function<Integer, Boolean>
  •  Function<String>
  •  Function<Integer, String>
  •  Function<Integer>

ExplanationReference

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

import java.util.HashMap;

publicclassMain {
    publicstaticvoidmain(String[] args) {
        HashMap<String, Integer> pantry = newHashMap<>();

        pantry.put("Apples", 3);
        pantry.put("Oranges", 2);

        intcurrentApples= pantry.get("Apples");
        pantry.put("Apples", currentApples + 4);

        System.out.println(pantry.get("Apples"));
    }
}
Code language: JavaScript (javascript)
  •  6
  •  3
  •  4
  •  7

Explanation

Q120. What variable type should be declared for capitalization?

List<String> songTitles = Arrays.asList("humble", "element", "dna");
_______ capitalize = (str) -> str.toUpperCase();
songTitles.stream().map(capitalize).forEach(System.out::println);
Code language: PHP (php)
  •  Function<String, String>
  •  Stream<String>
  •  String<String, String>
  •  Map<String, String>

ExplanationReference

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

_____ processFunction(Integer number, Function<Integer, String> lambda) {
    return lambda.apply(number);
}
Code language: JavaScript (javascript)
  •  Integer
  •  String
  •  Consumer
  •  Function<Integer, String>

Explanation

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

List<String> dates = newArrayList<String>();
<em>// missing code</em>
dates.replaceAll(replaceSlashes);
Code language: HTML, XML (xml)
  •  UnaryOperator<String> replaceSlashes = date -> date.replace(“/”, “-“);
  •  Function<String, String> replaceSlashes = dates -> dates.replace(“-“, “/”);
  •  Map<String, String> replaceSlashes = dates.replace(“/”, “-“);
  •  Consumer<Date> replaceSlashes = date -> date.replace(“/”, “-“);

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?

  •  Object
  •  Main
  •  Java
  •  Class

Explanation

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

import java.util.date;

publicclassCurrentDateRunnableimplementsRunnable {
    @Overridepublicvoidrun() {
        while (true) {
            System.out.println("Current date: " + newDate());

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                thrownewRuntimeException(e);
            }
        }
    }
}
Code language: JavaScript (javascript)
  •  Thread thread = new Thread(new CurrentDateRunnable()); thread.start();
  •  new Thread(new CurrentDateRunnable()).join();
  •  new CurrentDateRunnable().run();
  •  new CurrentDateRunnable().start();

Reference

Q125. Which expression is a functional equivalent?

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

for (Integer x : numbers) {
    if (x % 2 == 0)
    total += x * x;
}
Code language: PHP (php)
  •  A
inttotal= numbers.stream()
                        .transform(x -> x * x)
                        .filter(x -> x % 2 == 0)
                        .sum ();
  •  B
inttotal= numbers.stream()
                        .filter(x -> x % 2 == 0)
                        .collect(Collectors.toInt());
  •  C
inttotal= numbers.stream()
                        .mapToInt (x -> {if (x % 2 == 0) return x * x;})
                        .sum();
Code language: JavaScript (javascript)
  •  D
inttotal= 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                         <em>// Input `List<Integer>` > [1, 2, 3, 4]</em>
    .stream()                   <em>// Converts input into `Stream<Integer>`</em>
    .filter(x -> x % 2 == 0)    <em>// Filter even numbers and return `Stream<Integer>` > [2, 4]</em>
    .mapToInt(x -> x * x)       <em>// Square the number, converts `Integer` to an `int`, and returns `IntStream` > [4, 16]</em>
    .sum()                      <em>// Returns the sum as `int` > 20</em>Code language: HTML, XML (xml)

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

  •  print
  •  out
  •  err
  •  in

Reference

Q127. The compiler is complaining about this assignment of the variable pickle to the variable jar. How would you fix this?

doublepickle=2;
intjar= pickle;
  •  Use the method toInt() to convert the pickle before assigning it to the jar.
  •  Cast pickle to an int before assigning it to the jar.
  •  Make the pickle into a double by adding + “.0”
  •  Use the new keyword to create a new Integer from Pickle before assigning it to the jar.

Reference

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

for(int i=0; i<30; i+=x) {}
Code language: HTML, XML (xml)
  •  10
  •  3
  •  1
  •  0

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

  •  IDE; JRE
  •  JDK; IDE
  •  JRE; JDK
  •  JDK; JRE

Reference

Q130. Which packages are part of Java Standard Edition

  •  java.net
  •  java.util
  •  java.lang
  •  All above

Reference

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

Stringbuy="bitcoin";
System.out.println(buy.substring(x, x+1) + buy.substring(y, y+2))
Code language: JavaScript (javascript)
  •  int x = 0; int y = 2;
  •  int x = 1; int y = 3;
  •  int x = 0; int y = 3;
  •  int x = 1; int y = 3;

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

publicclassMain {
    publicstaticvoidmain(String[] args) {
        <em>// Your program logic here</em>
    }
}
Code language: HTML, XML (xml)
  •  exception
  •  args
  •  static
  •  String

Reference To make the main method the entry point of the program in Java, we need to use the static keyword. So, the correct answer is: static The main method must be declared as public static void main(String[] args) to serve as the entry point for a Java program

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?

<em>//This is how the original bunny class looks</em>classBunny{
    String name;
    int weight;

    Bunny(String name){
        this.name = name;
    }
    publicstaticvoidmain(String args[]){
        Bunnybunny=newBunny("Bunny 1");
    }
}

Code language: JavaScript (javascript)
  •  Implement the Comparable interface by overriding the compareTo method.
  •  Add the keyword default to the weight variable.
  •  Override the equals method inside the Bunny class.
  •  Implement Sortable and override the sortBy method.

Reference

Q134. Identify the incorrect Java feature.

  •  Object-oriented
  •  Use of pointers
  •  Dynamic
  •  Architectural neural

Reference

Q135. What is the output of this code?

intyearsMarried=2;
switch (yearsMarried) {
   case1:
      System.out.println("paper");
   case2:
      System.out.println("cotton");
   case3:
      System.out.println("leather");
   default:
      System.out.println("I don't gotta buy gifts for nobody!");
}
Code language: JavaScript (javascript)
  •  cotton
  •  cotton
    leather
  •  cotton
    leather
    I don’t gotta buy gifts for nobody!
  •  cotton
    I don’t gotta buy gifts for nobody!

Reference

Q136. What language features do these expressions demonstrate?

System.out::println
Doggie::fetch
Code language: CSS (css)
  •  condensed invocation
  •  static references
  •  method references
  •  bad code

Reference

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

  •  Only Threads can wait, but any Object can be put to sleep.
  •  A waiter can be woken up by another Thread calling notification whereas a sleeper cannot.
  •  When things go wrong, sleep throws an IllegalMonitorStateException whereas wait throws an InterruptedException.
  •  Sleep allows for multi-threading whereas wait does not.

Reference

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

  •  enum Cats (SPHYNX, SIAMESE, BENGAL);
  •  enum Cats (“sphynx”, “siamese”, “bengal”);
  •  enum Cats {SPHYNX, SIAMESE, BENGAL}
  •  enum Cats {“sphynx”,”siamese”,”bengal}

Q139. What happens when this code is run?

List<String> horses = newArrayList<String>();
horses.add (" Sea Biscuit ");
System.out.println(horses.get(1).trim());
Code language: JavaScript (javascript)
  •  “Sea Biscuit” will be printed.
  •  ” Sea Biscuit ” will be printed.
  •  An IndexOutOfBoundsException will be thrown.
  •  A NullPointerException will be thrown.

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

  •  Vector
  •  LinkedList
  •  Map
  •  Queue

Explanation:

from @yktsang01 in #3915 thread

Map because the map is a key/value pair without creating new classes/objects. So can store the rainfall per month like Map<java.time.Month, Double>. The other options will most likely need some new class to be meaningful:

publicclassRainfall {
    private java.time.Month month;
    privatedouble rainfall;
}
Vector<Rainfall>
LinkedList<Rainfall>
Queue<Rainfall>
Code language: HTML, XML (xml)

Q141. Among the following which contains date information?

  •  java.sql timestamp
  •  java.io time
  •  java.io.timestamp
  •  java.sql.time

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

  •  32 and 64
  •  32 and 32
  •  64 and 64
  •  64 and 32

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

  •  a reference to a copy
  •  a copy of the reference
  •  the object itself
  •  the original reference

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

  •  Function<Integer, Integer> funcReference = MyClass::myFunction;
  •  Function<Integer, Integer> funcReference = MyClass()::myFunction();
  •  Function<Integer, Integer> funcReference = MyClass().myFunction;
  •  Function<Integer, Integer> funcReference = MyClass.myFunction();

Q145. What is UNICODE?

  •  Unicode is used for the external representation of words and strings
  •  Unicode is used for the internal representation of characters and strings
  •  Unicode is used for external representation of characters and strings
  •  Unicode is used for the internal representation of words and strings

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

  •  User thread
  •  Daemon thread
  •  Both
  •  None of these

Q147. What is HashMap and Map?

  •  HashMap is Interface and map is a class that implements that
  •  HashMap is a class and map is an interface that implements that
  •  Map is a class and Hashmap is an interface that implements that
  •  Map is Interface and Hashmap is the class that implements that

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

  •  JVM invokes the thread’s run() method when the thread is initially executed.
  •  Main application running the thread.
  •  start() method of the thread class.
  •  None of the above.

Explanation: After a thread is started, via its start() method of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.

Q149. What is true about a final class?

  •  class declared final is a final class.
  •  Final classes are created so the methods implemented by that class cannot be overridden.
  •  It can’t be inherited.
  •  All of the above.

Explanation: Final classes are created so the methods implemented by that class cannot be overridden. It can’t be inherited. These classes are declared final.

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

  •  Math.largest(x,y)
  •  Math.maxNum(x,y)
  •  Math.max(x,y)
  •  Math.maximum(x,y)

Q151. void accept(T t) is a method of which Java functional interface?

  •  Consumer
  •  Producer
  •  Both
  •  None

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

  •  Predicate
  •  Interface
  •  Class
  •  Methods

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

  •  Class
  •  Interface
  •  Predicate
  •  Function

Q154. What code is needed at line 8?

1: classMain {
2:      publicstaticvoidmain(String[] args) {
3:          Map<String, Integer> map = newHashMap<>();
4:          map.put("a", 1);
5:          map.put("b", 2);
6:          map.put("c", 3);
7:          intresult=0;
8:
9:              result += entry.getValue();
10:         }
11:         System.out.println(result); <em>// outputs 6</em>12:     }
13: }
Code language: JavaScript (javascript)
  •  for(MapEntry<String, Integer> entry: map.entrySet()) {
  •  for(String entry: map) {
  •  for(Integer entry: map.values()) {
  •  for(Entry<String, Integer> entry: map.entrySet()) {

Q155. What will print when Lambo is instantiated?

classCar {
    Stringcolor="blue";
}

classLamboextendsCar {
    Stringcolor="white";

    publicLambo() {
        System.out.println(super.color);
        System.out.println(this.color);
        System.out.println(color);
    }
}
Code language: JavaScript (javascript)
  •  blue white white
  •  blue white blue
  •  white white white
  •  white white blue

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

  •  jar FrogSounds.java
  •  javac FrogSounds.exe
  •  jar cf FrogSounds.jar
  •  java -jar FrogSounds.jar

Q157. What is the default value of a short variable?

  •  0
  •  0.0
  •  null
  •  undefined

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

classvariable_scope {
    publicstaticvoidmain(String args[]) {
        int x;
        x = 5;
        {
            inty=6;
            System.out.print(x + " " + y);
        }
        System.out.println(x + " " + y);
    }
}
Code language: JavaScript (javascript)
  •  Compilation Error
  •  Runtime Error
  •  5 6 5 6
  •  5 6 5

Explanation: The scope of variable Y is limited.

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

  •  extends
  •  abstracts
  •  interfaces
  •  implements

Reference

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

import java.util.Formatter;
publicclassCourse {
    publicstaticvoidmain(String[] args) {
        Formatterdata=newFormatter();
        data.format("course %s", "java ");
        System.out.println(data);
        data.format("tutorial %s", "Merit campus");
        System.out.println(data);
    }
}
Code language: JavaScript (javascript)
  •  course java tutorial Merit campus
  •  course java course java tutorial Merit campus
  •  Compilation Error
  •  Runtime Error

Q161. Calculate the time complexity of the following program.

voidprintUnorderedPairs(int[] arrayA, int[] arrayB){
    for(inti=0; i < arrayA.length; i++){
        for(intj=0; j < arrayB.length; j++){
            if(arrayA[i] < arrayB[j]){
                System.out.println(arrayA[i] + "," + arrayB[j]);
            }
        }
    }
 }
Code language: JavaScript (javascript)
  •  O(N*N)
  •  O(1)
  •  O(AB)
  •  O(A*B)

Q162. What do these expressions evaluate?

1. true && false
2. true && false || true
Code language: JavaScript (javascript)
  •  1. false 2. true
  •  1. false 2. false
  •  1. true 2. false
  •  1. true 2. true

Reference //check page number 47 and example number 4.:-}

Q163. What allows the programmer to destroy an object x?

  •  1. x.delete()
  •  2. x.finalize()
  •  3. Runtime.getRuntime().gc()
  •  4. Only the garbage collection system can destroy an object.

Reference //No, the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection

Q164. How many objects are eligible for garbage collection till flag

publicclassTest
{
    publicstaticvoidmain(String [] args)
    {
        Testobj1=newTest();
        Testobj2= m1(obj1);
        Testobj4=newTest();
        obj2 = obj4;               <em>//Flag</em>
        doComplexStuff();
    }
    static Test m1(Test mx)
    {
        mx = newTest();
        return mx;
    }
}

Code language: JavaScript (javascript)
  •  1. 0
  •  2. 1
  •  3. 2
  •  4. 4

Reference // question no 5.

Q165. Which interface definition allows this code to compile

intlength=5;
Squaresquare= x -> x*x;
inta= square.calculate(length);
  •  A
@FunctionalInterfacepublicinterfaceSquare {
    voidcalculate(int x);
}
Code language: CSS (css)
  •  B
@FunctionalInterfacepublicinterfaceSquare {
    intcalculate(int x);
}Code language: CSS (css)
  •  C
@FunctionalInterfacepublicinterfaceSquare {
    intcalculate(int... x);
}
Code language: CSS (css)
  •  D
@FunctionalInterfacepublicinterfaceSquare {
    voidcalculate(int x, int y);
}
Code language: CSS (css)

Reference

Q166. Which of the following represents the time complexity of an algorithm?

  •  O(N*N)
  •  O(1)
  •  O(A+B)
  •  O(A*B)

Reasoning: The answer option ‘O(AB)’ should be corrected to ‘O(A*B)’ to accurately represent the time complexity.

  • O(N*N): This represents a quadratic time complexity, where the running time grows with the square of the input size.
  • O(1): This represents constant time complexity, indicating that the algorithm’s running time doesn’t depend on the input size.
  • O(A+B): This represents linear time complexity, indicating that the running time scales linearly with the sum of values A and B.
  • O(A*B): This represents quadratic time complexity, indicating that the running time scales quadratically with the product of values A and B.

The original answer option 'O(AB)' is incorrect as it does not properly represent a known time complexity notation. The correct notation should be 'O(A*B)' to indicate quadratic time complexity.

Reference

Q167. Calculate the space complexity of the following program.

voidcreateArray(int n) {
    int[] arr = newint[n];
    for (inti=0; i < n; i++) {
        arr[i] = i * 2;
    }
}
Code language: HTML, XML (xml)
  •  O(1)
  •  O(N)
  •  O(N^2)
  •  O(log(N))

//In this program, an array of size n is created. The space complexity is determined by the size of the dynamic array, which is n. Therefore, the space complexity is O(N).

Q167. What will be the output of the following Java code?

import java.util.*;
    publicclassgenericstack <E>
    {
        Stack <E> stk = newStack <E>();
    publicvoidpush(E obj)
        {
            stk.push(obj);
    }
    public E pop()
        {
            Eobj= stk.pop();
        return obj;
    }
    }
    classOutput
    {
        publicstaticvoidmain(String args[])
        {
            genericstack <String> gs = newgenericstack<String>();
            gs.push("Hello");
            System.out.println(gs.pop());
        }
    }
Code language: JavaScript (javascript)
  •  H
  •  Hello
  •  Runtime Error
  •  Compilation Error

//In this program, The code defines a generic stack class, pushes the string “Hello” onto the stack, and then pops and prints “Hello,” resulting in the output “Hello.”

Q168. In Java, what is the purpose of the synchronized keyword when used in the context of methods or code blocks?

  •  It is used to specify that a method or code block is asynchronous, allowing multiple threads to execute it concurrently.
  •  It is used to mark a method or code block as thread-safe, ensuring that only one thread can execute it at a time.
  •  It indicates that the method or code block is highly optimized for performance and will run faster than non-synchronized methods.
  •  It is used to prevent a method or code block from being executed by any thread, making it effectively “locked.”

Q169. In Java, which of the following statements about the “transient” modifier is true?

  •  Transient variables cannot be accessed outside their declaring class.
  •  Transient variables are automatically initialized with a default value.
  •  Transient variables are not serialized when an object is serialized.
  •  Transient is a keyword used to define inner classes.

Q170. The following prototype shows that a Cylinder subclass is derived from a superclass called Circle.

  •  Class Circle extends Cylinder.
  •  Class Cylinder derived Circle.
  •  Class Cylinder extends Circle.
  •  Class Circle derived Cylinder.

Q171. What will be the output of the following Java code snippet?

classabc
{
    publicstaticvoidmain(String args[])
    {
        if(args.length>0)
        System.out.println(args.length);
    }
}
Code language: JavaScript (javascript)
  •  The snippet compiles and runs but does not print anything.
  •  The snippet compiles runs, and prints 0.
  •  The snippet compiles runs, and prints 1.
  •  The snippet does not compile.

Q172. Which of these classes allows us to define our own formatting pattern for dates and times?

  •  DefinedDateFormat
  •  SimpleDateFormat
  •  ComplexDateFormat
  •  UsersDateFormatRead

Reference

Q173.What kind of relationship does extend denote?

  •  is-a
  •  has-a
  •  was-a
  •  uses-a
Scroll to Top