30 Senior Java Developer Interview Questions

If you are looking to attend an interview for the role of a Senior Java Developer then these Interview Questions with a mix of theory and coding might help you gain some knowledge. Take a quick glance at them to make sure you have not missed any important questions. 

1. What is the difference between compile-time polymorphism and runtime polymorphism?

Ans. The following table lists the differences between compile-time and runtime polymorphism:

Compile-time polymorphism Runtime polymorphism
Also known as static polymorphism Also known as dynamic polymorphism
Achieved through method overloading (Allowing a class to have multiple methods with the same name but different number/type of arguments) Achieved through method overriding (Allowing a subclass to have a method with the same name and type signature as a superclass)
The call to the overloaded method is resolved at compile-time The call to the overridden method is resolved at runtime  

2. What is encapsulation? Explain with a code sample

Ans. Encapsulation simply means keeping the data of a class hidden from the outside world. This is achieved by creating a class that has private fields and public getter/setter methods.

The following class is an example of encapsulation:

public class House {

            private int numRooms;

            private String location;

            public int getNumRooms() {

                 return numRooms;

            }

            public void setNumRooms(int numRooms) {

                 this.numRooms = numRooms;

            }

            public String getLocation() {

                 return location;

            }

            public void setLocation(String location) {

                 this.location = location;

            }

}

This code defines a class called House. It has two fields called numRooms and location, both are private and so cannot be accessed directly outside the class. Both fields have getter and setter methods which can be used by code outside the class.

3. What makes the Java platform independent?

Ans. Other programming languages like C, C++ are compiled into platform-specific binary files with .exe extension. So, the binary file for one operating system does not work on other operating systems. Unlike these languages, Java gets compiled into bytecode. Bytecode is executed within a Java Virtual Machine (JVM) and the same bytecode works on all operating systems. So, Java is platform-independent.

4. What is literal? Give some examples of literals

Ans. A literal is nothing but a constant value that can be assigned to a variable. Literals can be classified according to their data type. The following are some examples of literals:

  • 10,20 – These are all Integer literals since they correspond to Integer values
  • 26.45,31.89 – These are all floating-point literals since they represent floating-point (decimal) values.
  • ‘A’, ‘b’, ‘%’ – These are character literals since they hold an individual character. Character literals need to be enclosed in single quotes
  • “Java”, “Test” – These are String literals since they hold String values. String literals need to be enclosed in double-quotes.

5. Explain why the Java main method is static

Ans. A static method can be invoked directly via the class name and does not need an object of the class to be created. The Java main method is invoked by the JVM as soon as a Java program is executed. Hence, the JVM should be able to invoke the main method even before creating an object of the class. Hence the main method is static.

6. Explain the difference between the abstract and final keywords

Ans. The following table lists the differences between the abstract and final keywords:

Abstract final
Can be specified with a class or method. Cannot be specified with a field Can be specified with a field, method or class.
When specified with a method, indicates that the method is abstract. So, a subclass needs to provide an implementation for the abstract method or be declared as abstract itself When specified with a method, indicates that the method cannot be overridden. So, if a subclass tries to provide an implementation for the final method a compilation error occurs
When specified with a class, indicates that the class is abstract. So, a subclass needs to provide an implementation for the abstract methods within the class or must be declared as abstract itself When specified with a class, indicates that the class cannot be extended. So, if some code tries to create a subclass of a final class, a compilation error occurs.
An abstract class cannot be instantiated A final class can be instantiated

7. Is the following code valid? Explain your answer

Ans.

short s = 10; // 1

s = s + 10; // 2

The code above is not valid and causes a compilation error at Line 2. This is because Line 2 adds the value 10 to the short variable s. By default, the literal 10 is treated to be of type int and so Line 2 produces a result of type int but tries to assign it to a variable of type short. This code can be fixed either by changing the data type of s to int or by explicitly casting the result of s+10 to int as follows:

s = (short)(s + 10);

8. What is a two-dimensional array? Give some examples of two-dimensional arrays

Ans. A two-dimensional array is nothing but an array having two dimensions. In other words, it is an array of arrays, that is each array within a two-dimensional array is an array itself. The following are some examples of two-dimensional arrays:

       int array1[][] = new int[3][6];

      double array2[][] = new double[2][5];

array1 is a two-dimensional integer array having dimensions 3,6. array2 is a two-dimensional double array having dimensions 2,5.

9. Explain the difference between the prefix and postfix increment operator with a code sample

Ans. Both the prefix and postfix form of the increment operator increments its operand by 1. However, when used in a statement, the prefix operator first performs the increment operation and then the assignment while the postfix operator first performs the assignment and then the increment operation.

The following code sample demonstrates this:

       int n1=10;

      int n2=++n1;

The code above first causes n1 to be incremented and then assigned to n2, so n2 has the value 11.

Now consider the following code:

       int n1=10;

int n2=n1++;

The code above first causes n2 to be assigned with the value of n1 and then n1 is incremented, so n2 has the value 10.

10. What will be the output of the following code? Explain your answer

       int num1 = 17;

      int num2 = 25;

      int num3 = num1 & num2;

System.out.println(num3);

Ans.

The code above prints the following output:

17

The code above uses the bitwise AND (&) operator on num1 and num2. The & operator performs a bitwise AND operation on the binary representations of its operands. So, it returns 1 only if both the bits are 1. So, the above operation can be represented in binary form as below:

00010001 (17)

00011001 (25)

————–

00010001 (17)

11. Explain the break and continue statements

Ans. Both the break and continue statements are control statements that can be used to transfer control to a different part of a program. Both can be used within a loop. When a break statement is encountered within a loop, it causes the loop to be terminated and control is transferred to the first statement outside the loop. When a continue statement is encountered within a loop, it causes the current iteration of the loop to be skipped and control is transferred to the top of the loop. The loop then continues for the next iteration.

12. What will be the output of the following code? Explain your answer

String taskStatus = "IN_PROGRESS";

      switch (taskStatus) {

           case "ASSIGNED":

                 System.out.println("Task is assigned");

           case "IN_PROGRESS":

                 System.out.println("Task is in progress");

           case "COMPLETED":

                 System.out.println("Task is completed");

}

Ans.

The code above uses a switch statement that matches the value of the taskStatus variable with the value in each case statement. Since taskStatus matches the second case statement, it executes the code in this case statement and the code in the subsequent case statements. So, the code above prints the following output:

Task is in progress

Task is completed

13. What is the use of the new keyword?

Ans. The new keyword is used along with a constructor to create a new Java object. It has the following syntax:

Class1 ob = new Class1();

The line above creates an object called ob of the type Class1. The new keyword is followed by the class name that is Class1. This allocates memory for the object ob, that is the instance fields of ob.

14. Is the following code valid? Explain your answer

       Integer num = Integer.valueOf(“100”);

Ans. Yes, the code above is valid. It creates an Integer object corresponding to the value 100. An integer is a wrapper class corresponding to the int data type. Integer class has a static method called valueOf that can accept as a parameter a string and return the Integer value corresponding to the String. In case an invalid Integer is specified within the valueOf method, it throws an Exception.

15. Explain the different types of Inheritance supported by Java

Ans. Java supports the following types of inheritance:

  1. Single Inheritance – Occurs when a class has only one subclass
  2. Multi-level Inheritance – Occurs when there is a chain of inheritance. That is, a subclass, in turn, has a subclass
  3. Hierarchical Inheritance – Occurs when a class has multiple subclasses

16. Identify the error in the following code snippet and explain how it can be fixed

public class House {

}

public class RowHouse extends House {

            public static void main(String[] args) {

                 House h1 = new RowHouse();//1

                 RowHouse h2 = new House(); //2

            }

}

Ans. This code creates a class called House which has a subclass called RowHouse. Line 1 declares a House variable h1 and assigns it a RowHouse object. This is valid since a subclass object can be assigned to a superclass variable. Line 2 declares a RowHouse object h2 and assigns it a House object. This is invalid and causes a compilation error since a superclass object cannot be assigned to a variable of a subclass type. So, in order to fix this error, Line 2 needs to be removed from the code.

17. Explain the differences between static and default interface methods

Ans. The following table lists the differences between static and default interface methods:

Default Static
Has the keyword ‘default’ specified in the method declaration Has the keyword ‘static’ specified in the method declaration
Can be overridden by an implementing class Cannot be overridden by an implementing class
Can be invoked via an object of the implementing class Can only be invoked via the interface name

18. Identify the error in the code below and explain how you can fix it

public interface First {

           public void firstMethod();

}

public interface Second {

           public void secondMethod();

}

public class House implements First,Second{

           public void firstMethod() {

                 System.out.println("First Method");

           }

}

Ans. The code above will cause a compilation error in the class House. Since the House class implements the interfaces First and Second, it needs to provide code for all the methods in both interfaces. However, in this case, the House class only has code for firstMethod from the interface First. In order to fix the code, it needs to include code for secondMethod from the interface Second. So, the House class needs to be fixed as follows:

public class House implements First,Second{

           public void firstMethod() {

                 System.out.println("First Method");

           }

           public void secondMethod() {

                 //code here

           }

}

19. What are access specifiers in Java? List all of Java’s access specifiers

Ans.

Java’s access specifiers help to control where an instance field/method of a class is accessible. Java has the following access specifiers:

  1. Private – Specified by the private keyword. A private member is accessible only in the class where it is declared
  2. Default – When a class member does not have an explicit access specifier, it is said to have a default access. A default member is accessible only in other classes within the same package
  3. Protected – Specified by the protected keyword. A protected member is accessible in other classes within the same package and in sub-classes that are outside the package
  4. Public – Specified by the public keyword. A public member Is accessible from anywhere.

20. Explain the difference between the add and offer methods on the Queue interface

Ans. Both the add and the offer methods can be used to add an element to a Queue. However, there are some differences between the two as listed in the table below:

add offer
Method on the java.util.Collection interface Method on the java.util.Queue interface
Throws an exception if it is not possible to add the specified element into the Queue Returns false if it is not possible to add the specified element into the Queue

21. Explain with a code sample how you can swap two elements in a List

Ans.

The java.util.Collections class has a method called swap. It can be used to swap two elements in a List. The following code demonstrates this:

       List<String> animals = Arrays.asList(“Lion”,”Elephant”,”Tiger”,”Zebra”);

      Collections.swap(animals, 1, 2); //swaps elements at position 1,2

This code causes the elements at position 1,2 to be swapped, so “Tiger” is moved to position 1 and “Elephant” is moved to position 2

22. Explain the difference between a checked and unchecked exception

Ans.

The following table lists the differences between a checked and unchecked exception:

Checked Exception Unchecked Exception
Checked by the compiler. So, if you write code that can throw a checked exception, the compiler causes an error unless the exception is handled or declared in the throws clause Is not checked by the compiler. So, if you write code that can throw an unchecked exception, the compiler does not cause an error
All subclasses of java.lang.Exception except java.lang.RuntimeException are unchecked exceptions All subclasses of java.lang.RuntimeException are unchecked exceptions

23. Explain the throw and throws keywords in Java

Ans.

The throw keyword can be specified within any block of code. It can be used to explicitly throw an exception (both in-built as well as a custom exception). It is followed by an Exception object. The throws keyword is specified in a method declaration. It indicates that the method is capable of throwing an exception but does not handle it and that the code that invokes the method needs to handle the exception. It is followed by the exception class name.

24. Explain how you can check if a String contains another String

Ans.

The String class has several methods that can be used to check if a String contains another String. These are as follows:

  1. boolean contains(String str) – Accepts as parameter a String and returns a boolean value which indicates whether the String contains the specified String or not
  2. int indexOf(String str) – Accepts as parameter a String and returns the position of its first occurrence if present, otherwise returns -1.
  3. int lastIndexOf(String str) – Accepts as parameter a String and returns the position of its last occurrence if present, otherwise returns -1.

25. What is the difference between the capacity and length methods on the StringBuffer class?

Ans.

The capacity method on the StringBuffer class returns the capacity of the StringBuffer that is the number of characters that the StringBuffer is capable of holding. The length method on the StringBuffer class returns the actual length of the StringBuffer, that is the actual number of characters in the StringBuffer.

26. What will be the output of the following code? Explain

       File file = new File(“C:/test”);

file.mkdir();

Ans.

The code above creates a File object corresponding to the C:/test path and then invokes the mkdir() method on this File object. This method creates a directory corresponding to the specified path. So, once the code above executes, a directory called “test” will be created in c:/

27. Explain with a code sample how you can delete a file from the file system

Ans. The file class has a method called delete. This can be used to delete a file from the file system. The following code demonstrates this:

       File file1=new File(“C:/test.txt”);

file1.delete();

This code first creates a file object corresponding to “C:/test.txt” and then invokes the delete method on this file object. This causes the “C:/test.txt” file to be deleted from the file system.

28. Explain what modifications need to be made to the code below so that it prints “MyThread”

public class MyThread extends Thread{

           public void run() {

               System.out.println(Thread.currentThread().getName());

           }

           public static void main(String[] args) {

                 MyThread t = new MyThread();

                 t.start();

           }

}

Ans. The code above creates a Thread class called MyThread. The run method invokes the Thread.currentThread().getName()which prints the name of the current thread. So in order for the code to print “MyThread”, the name of the thread should be set to “MyThread”. For this you can do either of the following:

  1. Add Thread.currentThread().setName(“MyThread”)in the run method
  2. Add t.setName(“MyThread”)in the main method before invoking t.start();

29. What will be the output of the following code? Explain

Map<Character,String> animals = Map.of('A',"Lion",'B',"Elephant",'C',"Tiger");

String animal = animals.getOrDefault('D', "Giraffe");

Ans.

The code above uses the getOrDefault method on the animal map. This returns the value corresponding to the specified key if the key is present in the Map or the specified default value. Since there is no value corresponding to the key ‘D’, it returns the value “Giraffe”. So, the following is the output of the code listed above:

Giraffe

30. Explain what is garbage collection

Ans.

Java supports a process known as garbage collection whereby the memory allocated to objects that are no longer used is freed up automatically. When a Java program is executed, the JVM allocates memory to the objects/variables created in the code. For example, the JVM may allocate memory to some objects declared within a method. Once the method terminates, those objects are no longer required. So, the garbage collector frees up the memory allocated to the objects within the method. The JVM periodically runs the garbage collector in the background.

Salary: As per Payscale, The salary of a senior java developer in India is about ₹993,328 Per Annum. 

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Subscribe to get IQ's , Tutorials & Courses