• Articles
  • Tutorials
  • Interview Questions

Top 200+ Java Interview Questions and Answers in 2024

Expert-created Java interview questions and answers can help you prepare for your next Java interview. Learn about Java's advantages, inheritance, classes, enumerations, iterators, JSON, abstract classes, transient and volatile variables, HTTP tunneling, hibernate, and more. Get started with Intellipaat's Java training today and excel in your career!

Did You Know

  1. Did you know that before Java was positioned as a web language, it had been developed for digital cable TV and set-top boxes? For these reasons, features like applets and AWT were added in the first place.
  2. James Gosling, the creator of Java, apparently brainstormed the name while enjoying Peet’s Coffee. Originally named “Oak,” after a tree outside his window, he had to change the name due to trademark issues. That’s when he settled on “Java,” a choice that stuck and became legendary in the programming realm.

Top Java Interview Questions and Answers

CTA

Java is a popular programming language that is used by millions of developers around the world. There are many job opportunities available for Java developers, and the demand for Java skills is only increasing. In this blog post, we will discuss the top Java interview questions that you are likely to face.

Watch this Java Interview Questions video:

Youtube subscribe

Basic Java Interview Questions for Freshers

1. What do you understand by Java?

  • Java is an object-oriented computer language.
  • It is a high-level programming language developed by James Gosling in Sun Microsystems in the year 1995.
  • Java is a fast, secure, and reliable language used for many games, devices, and applications.

Go through this Java Tutorial to get a better understanding of the concept!

2. Compare between Java and Python.

Criteria Java Python
Ease of use Good Excellent
Speed of coding Average Excellent
Data types Static typed Dynamically typed
Data Science and Machine Learning applications Average Excellent

3. Outline the major Java features.

The major features of Java programming language are explained below:

Java Features

  • Object-oriented: Java is based on object-oriented programming where the class and methods describe the state and behavior of an object.
  • Portable: A Java program gets converted into Java bytecodes that can be executed on any platform without any dependency.
  • Platform independent: Java works on the ‘write once, run anywhere’ principle as it supports multiple platforms like Windows, Linux, Mac, Sun Solaris, etc.
  • Robust: Java has strong memory management as there are no pointer allocations. It has an automatic garbage collection that prohibits memory leaks.
  • Interpreted: As mentioned, Java compiler converts the codes into Java bytecodes which are then interpreted and executed by Java Interpreter.

Become a master of Java by enrolling in this online Java Course!

Get 100% Hike!

Master Most in Demand Skills Now !

4. What do you mean by an object?

An object consists of methods and classes that depict its state and perform operations. A Java program contains a lot of objects instructing each other their jobs. This concept is part of core Java.

Check out the list of Hibernate Interview Questions to prepare for upcoming interviews.

5. Distinguish between StringBuffer and StringBuilder in Java programming.

StringBuffer StringBuilder
StringBuffer methods are synchronized. StringBuilder is non-synchronized.
The storage area is heap and modified easily. Storage is heap-based and can be modified.
StringBuffer is thread-safe. StringBuilder is fast as it is not thread-safe.
The performance is very slow. The performance is very fast.

Go through this tutorial to get a better understanding of Java String!

6. Differentiate between JDK, JRE, and JVM.

  • JVM stands for Java Virtual Machine which provides the runtime environment for Java bytecodes to be executed.
  • JRE (Java Runtime Environment) includes the sets of files required by JVM during runtime.
  • JDK (Java Development Kit) consists of JRE along with the development tools required to write and execute a program.

Get a clear idea of why to get certified in Java!

7. Define inheritance.

Java includes the feature of inheritance which is an object-oriented programming concept. Inheritance lets a derived class inherit the methods of a base class.

8. Explain method overloading.

When a Java program contains more than one method with the same name but with different properties, then it is called method overloading.

Check our guide on Spring boot interview questions which is specifically developed for boot frameworks.

9. Compare overloading with overriding.

Overloading refers to the case of having two methods of the same name but different properties; whereas, overriding occurs when there are two methods of the same name and properties, but one is in the child class and the other is in the parent class.

Read this tutorial to get a clear understanding of Java!

10. Explain the creation of a thread-safe singleton in Java using double-checked locking.

Singleton is created with the double-checked locking as before Java 5 acts as a broker and it’s been possible to have multiple instances of singleton when multiple threads create an instance of the singleton at the same time. Java 5 made it easy to create thread-safe singleton using Enum. Using a volatile variable is essential for the same.

11. What is a class in Java?

Java encapsulates codes in various classes that define new data types. These new data types are used to create objects.

12. Differentiate between an ArrayList and a Vector.

ArrayList Vector
An ArrayList is not synchronized. A vector is synchronized.
An ArrayList is fast. A vector is slow as it is thread-safe.
If an element is inserted into an ArrayList, it increases its array size by 50 percent. A vector defaults to doubling the size of its array.
An ArrayList does not define the increment size. A vector defines the increment size.
An ArrayList can only use Iterator for traversing. Except for hashtable, a vector are the only other class that uses both Enumeration and Iterator.

13. Mention the difference between Iterator and Enumeration.

Iterator Enumeration
Iterator is an interface found in the java.util package. Enumeration is an object that generates elements one at a time.
Uses three methods to interface:

  1. hasNext()
  2. next()
  3. remove()
Uses two methods:

  1. hasMoreElements()
  2. nextElement()
Iterators allow removing elements from the given collection during the iteration with well-defined semantics. It is used for passing through a collection, usually of unknown size.
Iterator method names have been improved. The traversing of elements can only be done once per creation.

14. Explain the difference between the inner class and the subclass.

Inner Class Subclass
An inner class is a class that is nested within another class. A subclass is a class that inherits from another class called the superclass.
It provides access rights for the class, which is nesting it, which can access all variables and methods defined in the outer class. It provides access to all public and protected methods and fields of its superclass.

15. Can we execute any code, even before the main method? Explain.

Yes, we can execute any code, even before the main method. We will be using a static block of code in the class when creating the objects at load time of the class. Any statements within this static block of code will get executed at once while loading the class, even before the creation of objects in the main method.

Prepare yourself for Java certification with our comprehensive online Java Training!

16. How can we restrict inheritance for a class?

We can restrict inheritance for a class by the following steps:

  1. By using the final keyword
  2. If we make all methods final, then we cannot override that
  3. By using private constructors
  4. By using the Javadoc comment (” // “)

17. Java doesn't support multiple inheritance. Why?

Java doesn’t support multiple inheritance because we cannot use different methods in one class; it creates an ambiguity.
Example:

class Intellipaat1
{
void test()
{
system.out.println("test() method");
}
}class Intellipaat2
{
void test()
{
system.out.println("test() method");
}
}Multiple inheritance
class C extends Intellipaat1, Intellipaat2
{
     /* Code */
}

Intellipaat1 and Intellipaat2 test() methods are inheriting to class C. So, which test() method class C will take?

As Intellipaat1 and Intellipaat2 class test () methods are different, here we would face ambiguity.

18. Are constructors inherited? Can a subclass call the parent's class constructor?

We cannot inherit a constructor. We create an instance of a subclass using a constructor of one of its superclasses. Because overriding the superclass constructor is not our wish as if we override a superclass constructor, then we will destroy the encapsulation abilities of the language.

Check out this insightful tutorial to learn more about Java Constructors!

19. Define JSON.

The expansion of JSON is ‘JavaScript Object Notation.’ It is a much lighter and readable alternative to XML. It is independent and easily parse-able in all programming languages. It is primarily used for client–server and server–server communication.

20. What are the advantages of JSON over XML?

The advantages of JSON over XML are:

  1.  JSON is lighter and faster than XML.
  2.  It is easily understandable.
  3.  It is easy to parse and convert to objects for information consumption.
  4. JSON supports multiple data types—string, number, array, or Boolean—but XML data are all strings.

21. What is the difference between Java and C++?

Below are the key differences between Java and C++:

Java C++
Java supports both compilers and interpreters Supports only the compiler
Memory management is system controlled Memory management can be accessed by the programmer
Doesn’t support multiple inheritances Support multiple inheritances
Offers limited support for the pointers Fully supports the pointers
Shows heavy dependence on automatic garbage collection, but does not support the destructors The user needs to perform manual management using the new and delete keywords

22. What is JIT Compiler?

The Just-In-Time compiler is an important part of the Java Runtime Environment that optimizes the performance of java based applications at run time. JIT parallelly compiles the bytecodes with similar functionality and reduces the compilation time.

A method in the java program can be called thousands of times at the startup. Therefore, instead of compiling every method, java OpenJ9 records the number of times a method is initiated. If the initiation count crosses a predefined threshold, the JIT compiler gets triggered.

Even learn about Queue in Java.

23. What is Classloader?

It is a part of the Java Runtime Environment which is used to dynamically load the class files into the Java Virtual Machine(JVM). The classloader triggers whenever a java file is executed.

There are three types of classloaders in Java:

  • Bootstrap Classloader: The bootstrap loader is the superclass of extension classloader which loads the standard JDK files from rt.jar and other core classes. The rt.jar file contains all the package classes of java.net, java.lang, java.util, java.io, java.sql, etc.
  • Extension Classloader: The extension classloader is known as the parent of the System classloaders and the child of the Bootstrap classloader. It only loads the files available in the extension classpath, that is ‘ext.dirs/JRE/lib/ext directory. If the file is not available in the mentioned directory the extension classloader will delegate it to the System classloader.
  • System/Application Classloader: It loads the classes of application type available in the environment variable such as -classpath, or -cp command-line option. The application classloader generates a ClassNotFoundException if the class is not available in the application classpath.

24. How does the == operator function in Java?

Java uses the == operator to compare the reference equality of two objects, which means that it determines if the two objects refer to the same memory location.

25. What is polymorphism in Java?

Polymorphism refers to the ability of objects of different classes to be regarded as objects of a common superclass when writing object-oriented programs. This makes it possible for methods from different classes to be applied through one general interface, resulting in flexibility and reuse.

26. What is the purpose of static in Java? Mention an example.

The static keyword in Java is intended to indicate that a certain variable or method belongs to the class and not its instances. For this reason, even without instantiating an object of the class, such a variable or method can be accessed.

public class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }
    public static double square(double num) {
        return num * num;
    }
}

27. What is exception handling in Java?

Exception handling is a way of dealing with runtime errors or unusual situations that may occur during execution in the Java programming language. It involves trapping exceptions with try-catch blocks and managing them gracefully so that no program termination happens or unexpected behavior occurs.

28. What is a try-catch in Java?

A try-catch block in Java is responsible for this. The code that may throw exceptions has to be written inside the try block, and if any exception occurs, catch it and work on it in the corresponding catch block.

29. Differentiate between checked and unchecked.

The compiler checks checked exceptions at compile time, meaning that programmers have to handle such exceptions with try-catch blocks or declare them using the method signature. Unlike checked exceptions, unchecked exceptions are not checked at compile-time, hence they do not require explicit handling by a programmer.

30. What is the meaning of 'final' in Java? Give example

Java uses the final keyword to declare constants, prevent method overriding, and create immutable classes. For example, final int MAX_SIZE = 100; declares a constant MAX_SIZE whose value is 100.

31. Is multithreading part of Java?

Yes, multithreading is part of Java. It provides built-in support for creating and managing threads, thereby enabling multiple tasks to be executed concurrently within one program.

32. What is the purpose of the 'super' keyword in Java?

Super is used in the Java programming language to refer to the superclass of an object being manipulated. It can also be used as a bridge between superclass methods/constructors and subclass methods/constructors. For instance, super.methodName() invokes the method defined by the superclass.

33. What is an abstraction in Java? Give an example.

Java Abstraction is the term in Java, which means encapsulating only the function ability and behavior of methods while not exposing their implementation details to the user. The object design used here focuses on what an object does rather than on how it performs that function. For instance, the List interface in Java is an example of abstraction because it describes general operations for lists without defining how they are implemented by specific list classes such as LinkedList and ArrayList.

Java Developer Interview Questions for Experienced

34. Is an empty .java file name a valid source file name in java?

Yes, we can save a java file with an empty .java file name. You can compile it in the command prompt by ‘javac .java’ and run it by typing ‘java classname’. Here is an example of such a program:

import java.util.*;
class A
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}

After saving the code, you need to open the command prompt and go to the directory where the file is stored. Then, you need to type ‘javac .java’ to compile the program, and ‘java A’ to run the program.

35. What is the difference between Object-oriented and object-based programming language?

Following are the key differences between the object-oriented and object-based programming languages:

Object-oriented programming language Object-based programming language
Object-oriented programming languages support all the features of OOPS, including polymorphism and inheritance Object-based programming language does not support inheritance or polymorphism
Doesn’t support built-in objects Support built-in objects like JavaScript has the window object
Example: C#, C++, Java, Python, etc. JavaScript and Visual Basic are examples of object-based programming language

36. Why is the main method static in Java?

The main method is static in Java because to call the static methods, there is no need for the object. The Java Virtual Machine(JVM) has to create an object to call the non-static main() method, which will result in extra memory allocation.

37. Can we declare the static variables and methods in an abstract class?

Yes, we can declare the static variables and methods in an abstract class by inheriting the abstract class. In java, the static variables and methods can be accessed without creating an object. You can simply extend the abstract class and use the static context as mentioned below:

import java.util.*;
class A
{
    static int x=110;
    static void method1()
    {
        System.out.println("Class A static function called");
    }
    
}

public class prog1 extends A
{
    public static void main(String args[])
    {
        A.method1();
        System.out.println("Value of x="+A.x);
    }
}

The output of the above program will be:
Class A static function called
Value of x=110

38. What is Aggregation?

Aggregation in Java represents Has-A relationship where one class contains the reference of another class. In other words, it refers to a one-way relationship between two classes where the aggregate class has the instance of another class it owns.

For example, in the program below the aggregate class student have a one-way relationship with the class Address. Here each student having an address makes sense, but address having the student doesn’t make any sense. So, instead of inheritance, the aggregation is based on the usage of the classes.

import java.util.*;
class Address
{
    String street, city, state, country;
    public Address(String street, String city, String state, String country)
    {
        this.street=street;
        this.city=city;
        this.state=state;
        this.country=country;
    }
}
public class student
{
    int reg_no;
    String name;
    Address address;
    public student(int id,String name,Address address)
    {
        this.reg_no=id;
        this.name=name;
        this.address=address;
    }
    public void display()
    {
        System.out.println("Student details: ");
        System.out.println("Name: "+name);
        System.out.println("Reg_no: "+reg_no);
        System.out.println("Address: "+address.street+", "+address.city+", "+address.state+", "+address.country);
    }
    public static void main(String args[])
    {
        Address address1=new Address("Paper Mill Road","SRE","UP","India");
        Address address2=new Address("Service Road","BNG","KA","India");
        student ob1=new student(111,"Sam",address1);
        student ob2=new student(112,"Alex",address2);
        ob1.display();
        ob2.display();
    }
}

The output of the above program will be:

Student details: 
Name: Sam
Reg_no: 111
Address: Paper Mill Road, SRE, UP, India

Student details: 
Name: Alex
Reg_no: 112
Address: Service Road, BNG, KA, India

39. What is composition?

If an object contains another object and the contained can’t exist without the existence of that particular object, then it’s known as the composition. In simple words, the composition is a kind of aggregation used to describe the reference between two classes using the reference variable.

For example, a class student contains another class named address. So, if the class address cannot exist without the class student, then there exists a composition between them.

40. Can we overload the main method in Java?

Yes, you can overload the main() method in Java using the concept of method overloading.

Below is an example of main() method overloading:

import java.util.*;
public class main_overloading
{
   public static void main(String args)
   {
       System.out.println("Main with String");
   }
   public static void main(String args[])   
   {
       System.out.println("Main with the String args[]");
   }
   public static void main()
   {
       System.out.println("main without String");
   }
}

The output of the above code will be:

Main with the String args[]

Java Interview Questions for 2 to 3 Years of Experience

41. Explain public static void main(String argos[]) in Java?

The main() method is the entry point for any program in java language. In the expression public static void main(String argos[]), each keyword has significance as mentioned below:

  • Public: It’s an access specifier which is used to specify the accessibility of a method in java. Here, Public means anyone can access the method or the class.
  • static: the static keyword in java identifies the main method as class-based, which means it can be accessed without creating an object/instance. Static methods can b3e directly called by the Java Virtual Machine(JVM), which in turn saves extra memory allocation.
  • void: void is a return type in java, which means the main method will not return any value back.
  • String args[]: String argos[] or String[] args is an array of String objects which stores the command line arguments. Here the argument is an array of types of java. Therefore, it’s passed as the parameter in the main() method.

42. What is the NullPointerException?

The NullPointerException occurs when the user attempts to access or modify the fields of a null object. A null object is an instance defined with null values or without any reference.

43. What is the difference between a constructor and a destructor?

Below is the difference between a constructor and a destructor based on various parameters:

Base of Comparison Constructor Destructor
Purpose A constructor is used to allocate the memory. A destructor is used to deallocate or free up the memory.
Arguments Mayor may not accept the arguments. Destructors don’t accept any arguments.
Declaration class_name(arguments){

}

~class_name(){

};

Calling The constructor is called as soon as the object is created. Called at the time of program termination or when the block is exited.
Order of execution Constructors are executed in successive order, meaning from parent to child class. Destructors are called in the reverse order, meaning from child to parent class.
Overloading Can be overloaded. Cannot be overloaded.

44. Can a Java interface have static methods?

Yes, a Java interface can have static methods, but we cannot override them as they’re static. So, we have to define the static methods in the interface and only perform the calling party in the class.

Below is an example of a static method in Java interface:

import java.util.*;
public interface A
{
    static void staticmethod()
    {
        System.out.println("Static method of interface A called");
    }
    default void display()
    {
        System.out.println("Default function of interface A called");
    }
}

The above interface has a static method and a default method that can be executed without affecting the class that implements it. However, there is no use in creating the static methods in the Java interface as we cannot override the function by redefining it in the main() method.

import java.util.*;
the public class demo implements A
{
    public static void main(String args[])
    {
        demo obj =new demo();
        A.staticmethod();
        obj.display();
    }
}

So, the output of the above program would be:

Static method of interface A called
Default function of interface A called

45. Differentiate between ‘==’ and equals()?

The main difference between ‘==’ and equals() is that ‘==’ is an operator, while equal() is a method in java. The == operator is used for reference or addresses comparison, meaning it checks if both the objects or variables are pointing to the same memory location.

Whereas, equals() method compares the content of two objects or variables. It checks if the value of two objects is the same or not.

import java.util.*;
public class B
{
    public static void main(String args[])
    {
           String str1=new String("Alex");
           String str2=new String("Alex");
           System.out.println("Output given by == operator: "+(str1==str2));
           System.out.println("Output by equals() method: "+(str1.equals(str2)));
    }
}
Output:
Output given by == operator: false
Output by equals() method: true

46. What are JAR files?

Java Archive(JAR) is a file format that aggregates many files into a single file similar in a format similar to a ZIP file. In other words, the JAR is a zipped file comprised of java lass files, metadata, and resources like text, images, audio files, directories, .class files, and more.
Following is the syntax to create a JAR file:

Jar cf file_name input files 

47. What is the difference between method overloading and method overriding in Java? Provide examples to illustrate.

Method overloading is using a single class that has two or more methods with the same name but different parameters. It is solved at compile-time based on the number and types of arguments given. One more instance exists when a subclass provides the specific implementation for some method already defined in its superclass, this is called method overriding, which is used to achieve runtime polymorphism.

For example

class Parent {
    void display() {
        System.out.println("Parent's display method");
    }
}

class Child extends Parent {
    void display() {
        System.out.println("Child's display method");
    }
}

public class Main {
    public static void main(String[ ] args) {
        Parent p = new Parent( );
        p.display( );  // Output: Parent's display method

        Child child = new Child();
        child.display();   // Output: Child's display method
    }
}

48. Explain the concept of encapsulation in Java. How does it help in achieving data hiding and abstraction?

Encapsulation in Java is the act of keeping together data and methods that are part of a class to hide the internal state from direct access. The reason behind this approach is to ensure data integrity and promote abstraction by exposing only essential details of the class’s behavior through public methods.

To achieve data hiding, encapsulation restricts direct access to an object’s internal state, thus ensuring data integrity. By doing this, it makes abstraction possible as it only exposes some critical behaviors about the object via public methods, thereby enabling simpler interaction and decreased complexity.

49. What is the purpose of the final keyword in Java? How is it used in variables, methods, and classes?

The final keyword can be added before a variable declaration, any method header, or preceding the class keyword so as not to allow changing their value, to prevent them from being overridden, or before words like “extends” in order not to let inheritance happen.

public final class Circle {
    private final double PI = 3.14;

    public final void calculateArea(final double radius) {
        final double area = PI * radius * radius;
        System.out.println("Area of circle: " + area);
    }
}

50. Describe the concept of multithreading in Java. How can you create and manage threads in a Java application?

Java multithreading refers to the concurrent execution of multiple threads in one Java program. Threads are lightweight processes capable of running independently and sharing common memory space. There are two ways we can create threads in Java: by extending the Thread class or implementing the Runnable interface.

class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread is running...");
    }
}
public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

51. What is the difference between ArrayList and LinkedList in Java? When would you choose one over the other for storing data?

ArrayList is a dynamic array that stores elements and supports fast random access. It is better suited for element traversal and frequent access. Conversely, LinkedList is a linked list that stores its elements in the form of nodes, making it very suitable for high-speed insertion and deletion operations. Therefore, it can be useful where there are many additions or removals.

If you want fast access and traversal through elements, then use an ArrayList; otherwise, for fast insertion or deletion of elements, use LinkedList.

Java Interview Questions for 4 to 5 Years Experience

52. How many types of constructors are there in the Java programming language?

There are two types of constructors in the Java programming language:

  • Parameterized Constructor: A constructor that accepts arguments or parameters is known as the parameterized constructor. It initializes the instance variables will the values passed while creating an object.

Below is an example of the parameterized constructor:

import java.util.*;
class A
{
int roll_no;
String name;
A()
{
System.out.println("Constructor called");
}

public void fun()
{
System.out.println("Class A function called");
}
}
public class parameterized_constructor
{
public static void main(String args[])
{
A obj=new A();
obj.fun();
System.out.println("The value of instance variables are: ");
System.out.println("Name: "+obj.name);
System.out.println("Roll No: " +obj.roll_no);
}
}
The output of the above program would be:
Constructor called
Class A function called
The value of instance variables are:
Name: null
Roll No: 0
  • Non-parameterized/Default constructor: The constructors with no parameters or arguments are known and non-parameterized constructors. In case you don’t define a constructor of any type, the compiler itself creates a default constructor which will be called when the object is created.

Below is an example of a non-parameterized constructor:

import java.util.*;
class A
{
int roll_no;
String name;
A(int x,String y)
{
this.roll_no=x;
this.name=y;
System.out.println("Constructor called");
}

public void fun()
{
System.out.println("Class A function called");
}
}

public class non_parameterized_constructor
{
public static void main(String args[])
{
A obj=new A(10,"Harry Williams");
System.out.println("The value of instance variables");
System.out.println("Name: "+obj.name);
System.out.println("Roll No: "+obj.roll_no);
}
}

The output of the above program will be:

Constructor called
The value of instance variables
Name: Harry Williams
Roll No: 10

53. What is the purpose of a Default constructor in Java?

If no constructor is available in the class, the java compiler creates a default constructor and assigns the default value to the instance variables.

For example:

import java.util.*;
class A
{
String name;
int id;
void display()
{
System.out.println("Name: "+this.name);
System.out.println("Id: "+this.id);
}

}
public class B
{
public static void main(String args[])
    {
        A object=new A();
        System.out.println("The values of the instance variables are:");
        System.out.println("Name: "+object.name);
        System.out.println("Name: "+object.id);
    }
}
The output of the above program:
The values of the instance variables are:
Name: null
Name: 0

54. What is the use of a copy constructor in Java?

Java does not support a copy constructor, however, you can copy the values of one instance to another by copying the instance variables of one object to another. Below is an example of such a method:

import java.util.*;
class demo
{
    String name;
    int roll_no;
    //constructor to initialize the name and roll number
    demo(int x, String y)
    {
        name=y;
        roll_no=x;
    }
    //constructor to initialize another object variables
    demo(demo ob)
    {
        roll_no=ob.roll_no;
        name=ob.name;
    }
    void display()
    {
        System.out.println("Name: "+name);
        System.out.println("Roll Number:"+roll_no);
    }
}

public class copy_constructor
{
    public static void main(String args[])
    {
        demo obj=new demo(10,"Alice Williams");
        demo obj2=new demo(obj);
        obj.display();
        obj2.display();
    }
}

The output of the following code is:
Name: Alice Williams
Roll Number:10
Name: Alice Williams
Roll Number:10

55. What is the difference between aggregation and composition?

Below are the key differences between aggregation and composition in Java:

Aggregation Composition
The parent class has a one-way relationship with the child class. In composition, the parent class owns the child class
Aggregation is denoted by an empty diamond in UML (Unified Modeling Language) notation Denoted by a filled diamond in the UML notation
Child class has its own life cycle Child class doesn’t have a lifetime
Aggregation is a weak relationship. For example, a bike with an indicator is aggregation Composition is a stronger relationship. For example, a bike with an engine is a composition

56. What is object cloning?

Object cloning means creating the exact copy of an existing object. In java programming, object cloning can be done using the clone() method. To create the object clone, you should implement the java.lang.Cloneable interface, otherwise the clone() method generates a CloneNotSupportException.

The syntax for the clone method is:

protected Object clone() throws CloneNotSupportedException

57. What are various exception handling keywords in Java?

Java language has three exception handling keywords:

  • try: whenever a code segment has a chance of an error or any abnormality, it can be placed inside the try block. In case of any error, the try block will send the exception to the catch block.
  • catch: catch handles the exception generated in the try block. It comes after the try block.
  • final: The final keyword ensures that the segments execute despite the errors and exceptions processed by the try & catch block. The final keyword comes either after the try block or both the try and the catch block.

58. How to manually throw an exception in Java programming?

The programmer has to use the throws keyword to create and throw a manual exception. Below is the program to manually throw a single IOException. If you want to throw:

import java.io.*;
class D
{
    void function1() throws ArithmeticException
    {
        throw new ArithmeticException("Arithmetic or zero value error");
    }
}
    
public class demoException
{
    public static void main(String args[]) throws ArithmeticException
    {
        D obj=new D();
        obj.function1();
        System.out.println("End of the program");
    }
}

The output of the above program will be:

java.lang.ArithmeticException: Arithmetic or zero value error

59. What is a WAR file?

The Eb Archive file contains the files of a web application and reduces the time needed to transfer the files. War files can store java classes, XML, JSP, image, CSS, js, HTML, and JavaServer pages, which can be used to distribute the collection of Java classes, XML files, Java Servlets, Web pages, etc.

Following is the syntax to create a WAR file:

Jar -cvf file_name.war*

These are the Core Java basic interview questions for freshers, let us check out some of the top Java interview questions that come under the intermediate category.

60. Differentiate between this() and super() in Java.

this() super()
Represents the present instance of a class Represents the current instance of the parent class
Calls the default constructor Calls the base class constructor
Used to point to the current class instance Used to point to the instance of the superclass

61. Name the methods of an object class.

  • clone(): This method helps create and return a copy of an object.
  • equals(): This method helps compare.
  • finalize(): It is called by the garbage collector on the object.
  • getClass(): It allows us to return the runtime class of the object.
  • hashCode(): This method helps return a hash code value for the object.
  • toString(): It lets us return a string representation of the object.
  • notify(), notifyAll(), and wait(): These help in synchronizing the activities of the independently running threads in a program.

Read this tutorial to learn more about Java Methods!

62. Define content negotiation.

If we have visited a website to search for information, we will get the information in different languages and in different formats. When a client makes an HTTP request to a server, the client can also specify the media types here. The client can specify what it can accept back from the host, and on the basis of availability the host will return to the client. This is known as content negotiation because the client and the server negotiate on the language and format of the content to be shared.

63. Can we import the same package/class twice? Will the JVM load the package twice at runtime?

A package or class can be inherited multiple times in a program code. JVM and compiler will not create any issue. Moreover, JVM automatically loads the class internally once, regardless of times it is called in the program.

CTA

Watch this Java Tutorial for Beginners video:

Youtube subscribe

64. Define an abstract class.

A class that contains the abstract keyword in its declaration is known as an abstract class. It can have abstract and non-abstract methods (method with a body).

  1.  This class can have public, private, protected, or constants and default variables.
  2.  It needs to be extended and its method needs to be implemented. It cannot be instantiated.
  3.  If a class has at least one abstract method, then the class must be declared abstract.

65. Describe annotations.

  • Java annotation is a tag that symbolizes the metadata associated with class, interface, methods, fields, etc.
  • Annotations do not directly influence operations.
  • The additional information carried by annotations is utilized by Java compiler and JVM.

66. Java doesn't use pointers. Why?

Pointers are susceptible and slightly carelessness in their use which may result in memory problems, and hence Java basically manages their use.

This blog will help you get a better understanding of Mobile Technology for Android and iOS using Java!

67. What is the difference between HashMap and HashTable in Java? When would you choose one over the other for storing key-value pairs?

These two are used to save key/value pairs, but with some differences:

  • HashMap does not have a synchronization feature, making it not thread-safe, while HashTable does. 
  • HashMap allows null keys as well as values, but HashTable does not allow any null key or value.

Generally, HashMap is preferred in non-thread-safe scenarios where performance is important; on the other hand, HashTable is recommended for multi-threaded environments where thread safety is required.

68. Explain the concept of inheritance in Java. How does it promote code reusability and extensibility?

In Java, inheritance is a mechanism where one class (superclass) derives another class (subclass). Properties of the superclass, such as methods and fields, are inherited by the subclass. This enables subclasses to reuse superclass code leading to enhanced code reusability. Additionally, this promotes extensibility by letting subclasses add new functions or override the methods of the superclass.

69. What are the different access modifiers in Java? Describe their visibility scopes and when to use each one.

Public, protected, default (no modifier), and private are four access modifiers in Java.

  • Public: access from anywhere 
  • Protected: access to the same package or other packages (subclasses)
  • Default (no modifier): Only access in the created package. .
  • Private: No one else but the declaring class will be able to obtain it.

Use public if you want your member to be accessed from anywhere, protected when you wish to restrict access to subclasses and classes within the same package, default when you want access at the package level, and private when you only want access within the declaring class.

70. How does Java handle memory management and garbage collection? Explain the role of the JVM in managing memory resources.

Garbage collection is Java’s automatic memory management system. It runs as a process that recovers memory from objects that will never be used again. Memory resources management is done by JVM like allocating memory for objects, garbage collecting unused objects, and optimizing memory usage for performance enhancement. Various types of memory areas are used by JVM such as heap, stack method area, and native method stacks to help keep its memory efficient.

71. What are the advantages and disadvantages of using the synchronized keyword for thread synchronization in Java? Are there any alternative approaches for achieving thread safety?

Benefits of using synchronized:

  • It ensures thread safety by allowing only one thread to run a synchronized block or method at certain times.
  • It is easy to work with and understand.

Drawbacks of using synchronized:

  • This may result in performance overheads due to locking and unlocking of objects.
  • May result in the occurrence of deadlock when used carelessly.

Other ways for achieving thread safety include:

  • Use java.util.concurrent package classes such as ConcurrentHashMap, CopyOnWriteArrayList, etc., and Lock interface implementations for finer-grained control over locking.
  • Use volatile keywords when you use variables that are being read and modified by multiple threads so that they are visible across various threads at all times & also that atomicity is guaranteed.
  • Avoid shared mutable states by using immutable objects and thread-local variables.

Advanced Java Interview Questions for Senior Developers

72. Distinguish between static loading and dynamic class loading.

  • Static loading: In static loading, classes are loaded statically with the operator ‘new.’
  • Dynamic class loading: It is a technique for programmatically invoking the functions of a class loader at runtime. The syntax for this is as follows:
Class.forName (Test className);

73. Struts 1 classes are not thread-safe, whereas Struts 2 classes are thread-safe. Why?

Struts 1 actions are singleton. So, all threads operate on the single action object and hence make it thread-unsafe.

Struts 2 actions are not singleton, and a new action object copy is created each time a new action request is made and hence it is thread-safe.

74. Define JAXP and JAXB.

JAXP: It stands for Java API for XML Processing. This provides a common interface for creating and using DOM, SAX, and XSLT APIs in Java regardless of which vendor’s implementation is actually being used.

JAXP
JAXB: It stands for Java API for XML Binding. This standard defines a system for a script out of Java objects as XML and for creating Java objects from XML structures.

JAXB

Learn more about Java Multithreading from this tutorial!

75. Define an enumeration?

The term “enum” is commonly used to refer to an enumeration. An enumeration represents an interface that encompasses methods facilitating access to the underlying data structure from which the enumeration is derived. It enables a systematic, sequential retrieval of all the elements stored within the collection.

76. How can we find the actual size of an object on the heap?

In the Java programming language, you cannot accurately determine the exact size of an object located in the heap.

77. Which API is provided by Java for operations on a set of objects?

Java offers a comprehensive Collection API that presents a multitude of beneficial methods applicable to a group of objects. Noteworthy classes within the Collection API encompass ArrayList, HashMap, TreeSet, and TreeMap. These classes serve as valuable tools for handling, manipulating, and organizing data structures in Java programs.

78. What’s the base class of all exception classes?

Java.Lang.throwable: It is the superclass of all exception classes, and all exception classes are derived from this base class.

Learn all about arrays from this comprehensive Java tutorial!

79. Why do we use a vector class?

A vector class provides the ability to execute a growable array of objects. A vector proves to be very useful if you don’t know the size of the array in advance or if we need one that can change the size over the lifetime of a program.

80. What is the difference between transient and volatile variables in Java?

Transient: In Java, it is used to specify whether a variable is not being serialized. Serialization is a process of saving an object’s state in Java. When we want to persist the object’s state by default, all instance variables in the object are stored. In some cases, we want to avoid persisting a few variables because we don’t have the necessity to transfer across the network. So, we declare those variables as transient.

If the variable is confirmed as transient, then it will not be persisted. The transient keyword is used with the instance variable that will not participate in the serialization process. We cannot use static with a transient variable as they are part of the instance variable.

Transient Variable

Volatile: The volatile keyword is used with only one variable in Java, and it guarantees that the value of the volatile variable will always be read from the main memory and not from the thread’s local cache; it can be static.

Volatile Variable

81. Why Map interface does not extend the Collection interface in the Java Collections Framework?

The Map interface is not compatible with the Collection interface, because Map requires a key as well as a value, for example, if we want to add a key–value pair, we will use put(Object key, Object value).

There are two parameters required to add an element to HashMap object. In Collection interface, add(Object o) has only one parameter.

The other reasons are: Map supports valueSet, keySet, and other suitable methods that have just different views from the Collection interface.

Read on – What is Hashmap in Java? 

82. Mention the uses of the synchronized block.

We use the synchronized block because:

  • It helps lock an object for every shared resource.
  • The scope of the synchronized block is smaller than the method.

Java Interview Questions for 6 to 7 Years Experience

83. What are the functions of hashCode() method?

The hashCode() method returns a hash code value (an integer number) and also the same integer number if the two keys (by calling the equals() method) are the same.
But sometimes, the two hash code numbers can have different or the same keys.

Hashcode

84. What is the default size of the load factor in the hashing-based collection?

Default size = 0.75
Default capacity = initial capacity * load factor

85. What are the differences between the JSP custom tags and Java beans?

  • Custom tags can manipulate JSP content, but beans cannot.
  • Composite operations can be reduced to a considerably simpler form with custom tags than with beans.
  • Custom tags require reasonably a bit more work to set up than beans do.
  • Custom tags are available only in JSP 1.1 and so on, but beans can be used in all JSP 1.x versions.

86. What are wrapper classes in Java?

Wrapper Classes in Java offers a mechanism to convert the primitive data types into reference or object types and vice-versa. Each primitive data type in Java has a dedicated class known as the wrapper class, which wraps the primitive types into an object of that particular class. Converting primitive data types into objects is known as autoboxing and converting from an object to primitive data types called unboxing.

One of the major applications of wrapper classes is changing the value inside the methods. Java does not support the call by reference, which means changes done inside a method will not change the original value. So, after converting the types into objects, the original values will also change. Also, the wrapper classes help to perform serialization by converting objects into streams.

87. Difference between Stack and Heap Memory in Java?

The key differences between Heap and Stack memory in Java are:

Features Stack Memory Heap Memory
Memory Size Smaller in size. Larger in size.
LifeTime Exists until the end of the thread. Lives from the start till the end of application execution.
Access Objects stored in Stack can’t be accessed by other threads. Globally accessible.
Memory

 Management

Follows LIFO(Last In First Out) order. Dynamic memory allocation.
Scope or Visibility The variables in Stack memory are only visible to the owner thread. Heap memory is visible to all the threads.
Order of Allocation Continuous memory allocation. Random order memory allocation.
Flexibility Less flexible, one cannot alter the allocation memory. Users can alter the allocated memory.
Efficiency Fast access, allocation, and deallocation. Slow access, allocation, and deallocation.

88. What is Polymorphism?

Polymorphism is the ability of an object to get processed in more than one way. It is mainly used when a base/parent class is used to refer to a child/derived class reference. There are two types of polymorphism in Java:

  • Compile-time Polymorphism: Compile-time polymorphism is method overloading where two or more methods have the same name with arguments/parameters and return type.
  • Run-time polymorphism: Runtime polymorphism of the Dynamic Method Dispatch helps the user to resolve the overridden method at runtime rather than compile-time. The overridden method is called the object of a superclass.

89. What do you mean by the interface in Java?

Java interface is a completely abstract class referred to as a collection of abstract methods, static methods, and constants. It acts as a blueprint of a class that groups related methods or functions with empty bodies.

Below is an example of a java interface:

import java.io.*;
public interface x
{
   int p=10;
   void pr();
   default void show()
   {
       System.out.println("A default method in interface");
   }
}
public class impx implements x
{
    public void pr()
    {
        System.out.println("Hello World");

    }
    public static void main(String args[])
    {
        x ob=new impx();
        ob.pr();
        ob.show();
    }  
}

Output:

Hello World
A default method in interface

90. What is the difference between abstract class and interfaces?

Below are the major differences between the abstract class and an interface:

Abstract Class Interface
Can provide complete, default, or only the details in method overriding Doesn’t provide any code, the user can only have the signature of the interface.
Have instance variables. No instance variables.
An abstract class can be public, private, or protected. The interface must be public.

 

An abstract class can have constructors. No constructors are available in the interface.
A class can inherit only a single abstract class. A class can implement one or more interfaces.
Abstract classes are fast. Interfaces are slower as they have to locate the corresponding methods in the class.

91. Explain data encapsulation in Java?

Data encapsulation is a fundamental OOPs concept that wraps the data(variables) and code(methods) as a single unit. These variables and methods can only be accessed through the current class, as they’ll be hidden from others. Encapsulation protects the data from unnecessary modification and can be achieved in two ways:

  • By declaring the variable of a class as private
  • Using public setter and getter methods to view and modify the values

92. What is a servlet in java?

It’s a server-side technology used to create web servers and application servers. We can understand Servlets as the java programs that handle the request from the web servers, process the request, and reverts to the web servers after the response is generated.

Several packages like javax.servlet and javax.servlet.HTTP provides the appropriate interfaces and classes that help the user to create their servlet. All the servlets should implement the javax.servlet.Servlet interface, plus other interfaces and classes like the HttpServlet, Java Servlet API, and more.

The execution of a servlet involves six distinct steps:

  • The clients initiate the request by sending it to the web server or application server.
  • The web server receives the request from the clients.
  • The servlet processes the request, carrying out the necessary computations, and generates the corresponding output.
  • Subsequently, the servlet sends the processed request back to the web server.
  • Finally, the web server dispatches the request to the clients, and the resulting output is displayed on the client’s screen or any other designated device.

93. What is a Request Dispatcher?

The request dispatcher serves as an interface utilized to effectively redirect requests to various resources within the application itself. These resources may include Java Server Pages (JSP), images, HTML files, or other servlets. Moreover, it facilitates the integration of responses from one servlet into another, guaranteeing that the client receives output from both servlets. Additionally, it allows for the seamless forwarding of client requests to the next servlet in the specified sequence.

There are two methods defined in a Requestdispatcher interface:

  • void include(): It includes the content of the resource before sending the response.
  • void forward(): the method forwards the request from one servlet to another resource like the JSP, image, etc on the server.

94. How do cookies work in Servlets?

Cookies are the text files sent by the server and get stored in the client system to keep the information on the local machine and use it for tracking purposes. Java Servlet supports  HTTP cookies through javax.servlet.http.Cookie class that implements cleanable and serializable interfaces.

The server sends a set of cookies to the client computer, for example, name, age, etc. Then, the browser stores the information in the local machine and sends these cookies to the server, if any request is sent to the webserver. This information can then be used to identify the user.

95. What is the difference between ServletContext vs. ServletConfig?

The difference between ServletContext and ServletConfig is as follows:

ServletContext ServletConfig
Common for all the servlets and generally represents the whole web application. represents a single servlet.
Similar to global parameters linked to the whole application. Similar to local parameters associated with a particular servlet.
The ServletContext has an application-wide scope. ServletConfig has the servlet wide scope.
To get the context object, getServletContext() method is used. To get the config object, getServletConfig() is used.
Mainly used to get a MIME type of file or application. Mainly used for specific users or tasks like the shopping card.

96. Explain the thread lifecycle in Java?

There are 5 states in a thread lifecycle and java can be at any one of them. The thread lies in any one of these states:

  • New: The thread lies in the new state after it has been created. It remains in the new state until you start the execution process.
  • Running: At runnable state, the thread is ready to run at any point in time or it might have started running already.
  • Running: The scheduler picks up the thread and changes its state to running, the CPU starts executing the thread in the running state.
  • Waiting: While being ready to execute, another thread might be running in the system. So, the thread goes to the waiting state.
  • Dead: Once the execution of the thread is finished, its state is changed to the dead state, which means it’s not considered active anymore.

97. How to distinguish processes from threads?

Below are the key differences between the processes and threads:

Process Thread
The process is the set of instructions or programs in execution. Thread is a segment or part of a process
Takes more time to execute. Takes less time to execute.
Context switching is slower. Context switching is faster.
Processes are generally isolated. Threads share the memory.
The process is a heavy-weight process. Lightweight process.
One blocked process will not affect the performance of other processes. A blocked thread would block other threads of the same process.
The process consumes fewer more resources. Threads consume fewer resources.

98. Explain the types of Exceptions in Java?

There are two types of Exceptions in Java Programming:

  • Built-in Exception: These exceptions are the exceptions available in the standard package of java lang. They are used for certain errors with specific Exceptions as mentioned below:
    • AriththmeticException: thrown for the errors related to the arithmetic operations.
    • IOException: thrown for failed input-output operations.
    • FileNotFourndException: raised when the file is not accessible or does not exist.
    • ClassNotFoundException: exception is raised when the compiler is unable to found the class definition.
    • InterruptedEException: raised when a thread is interrupted.
    • NoSuchFieldException: raised when a class or method doesn’t have a variable specified.
    • NullPointerException: thrown while referring to the variable or values of a null object.
    • RuntimeException: raised for the errors occurring during the runtime. For example: performing invalid type conversion.
    • IndexOutOfBoundsException: raised when the index of the collection like an array, string, or vector is out of the range or invalid.
  • User-defined Exceptions: User-defined exceptions are the exceptions thrown by the user with custom messages. These are used for cases where the in-built Exception might not be able to define the error.

99. How to write multiple catch statements under a single try block?

Below is the program for multiple catch statements:

import java.util.*;
public class multiple_catch
{
   public static void main(String args[])
   {
       Scanner s=new Scanner(System.in);
       int x,y,z;
       try{
           System.out.println("Enter the elements for division: ");
           x=s.nextInt();
           y=s.nextInt();
           z=x/y;
           System.out.println("Value of z: "+z);
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception occured");
        }
        catch(IllegalArgumentException e)
        {
            System.out.println("Illegal argument");
        }
        catch(Exception e)
        {
            System.out.println("Any Exception in the third block");
        }
        System.out.println("End of the program");
   }
}

The output of the following program in different cases will be:

Case 1: Dividing an integer by zero
Enter the elements for division: 
30
0
Arithmetic Exception occurred
End of the program

 

Case 2: Execution successful
Enter the elements for division: 
15
3
Value of z: 5
End of the program

 

Case 3: Value entered is invalid
Enter the elements for division: 
23
t
Any Exception in the third block
End of the program

100. Difference between the throw and throws keyword?

Following are the key differences between the throw and throws keyword:

Key throw throws
Definition The throw keyword is used to explicitly throw an exception inside a program or a block of code. Throws keyword is used to declare an exception in the method signature that might occur during the compilation or execution of a program.
Type of exception Can throw only unchecked exceptions. Can be used for both checked and unchecked exceptions.
Syntax throw keyword followed by an instance variable. throws keyword followed by the exception class names.
The implementation throw keyword is used to throw only a single exception. throws can be used to throw multiple exceptions.

101. Write the string reversal program without using the in-built function?

There are two ways we can reverse a string in java without using the in-built function:

  • Using the loop and print string backward by one character each time.
  • Use the recursive function and print the string backward.

In the following program, you can see both ways to print the spring in reverse order:

import java.util.*;
public class string_reversal
{
public void method1(String str)
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.print(str.charAt(i));
}
System.out.println();
}
public void reverse(String str)
{
if(str.isEmpty())
{
return;
}
else
reverse(str.substring(1));
System.out.print(str.charAt(0));
}
public static void main(String args[])
{
String str="Intellipaat";
System.out.println("The oroginal string is "+str);
System.out.println("String reversal using the loop: ");
string_reversal obj=new string_reversal();
obj.method1(str);
System.out.println("String reversal using recursion: ");
obj.reverse(str);
}
}

The output of the above program will be:

The oroginal string is Intellipaat
String reversal using the loop:
taapilletnI
String reversal using recursion:
taapilletnI

102. Write a program to print Fibonacci Series using the recursion concept?

import java.util.*;
public class fib
{
    public int fibonacci(int x)
    {
        if(x==0)
        {
            return 0;
        }
        else if(x==1||x==2)
        {
            return 1;
        }
        else
        {
            return (fibonacci(x-2)+fibonacci(x-1));
        }
    }
    public static void main(String args[])
    {
        int t=10;
        fib ob=new fib();
        for(int i=0;i<t;i++)
        {
            System.out.print(ob.fibonacci(i)+" ");
        }
    }
}

The output of the above program is:

0 1 1 2 3 5 8 13 21 34 

That is all in the section of intermediate core Java interview questions. Let’s move on to the next section of advanced Java interview questions for experienced professionals.

103. Explain the expression language in JSP.

The expression language is used in JSP to simplify the accessibility of objects. It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session, etc.

104. What are implicit objects?

Implicit objects, also called pre-defined variables, are created by the JSP engine inside the service method so that it can be accessed directly without being declared explicitly.

105. Define a cookie. What are the differences between a session and a cookie?

A cookie is a small piece of information, which is sent to the browser by a web server. The browser stores the cookies for every web server in a local file. In a future request, the browser sends all stored cookies for that detailed web server.

The difference between cookies and sessions are:

  •  A session works regardless of the settings on the client browser. The client may have selected to disable cookies.
  •  Sessions and cookies also differ in storing the amount of information. The HTTP session is able to store any Java object, while a cookie can only store String objects.

106. What is HTTP Tunneling?

HTTP tunneling refers to encapsulating the private network data/information and transmitting it through a public network. Instead of sending data as a packet, tunneling encrypts the data and encapsulates it in a connection. This process allows the outside clients to collect all the data sent by the client-side Object Request Broker (ORB) that needs to be sent to the server-side ORB. HTTP tunneling masks other protocol requests as HTTP requests.

HTTP Tunneling

107. What is the function of the IOC container in spring?

The IOC container is responsible for:

  • Creating an instance
  • Configuring the instance
  •  Assembling the dependencies

108. What is lazy loading in hibernate?

Lazy loading is a kind of setting that decides whether to load the child entities along with the parent entities or not. When enabling this feature, the associated entities will be loaded only when they are requested directly. The default value of this setting is ‘true’ which stops the child entities from loading.

109. How can we fetch records using Spring JdbcTemplate?

We can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:

  1.  ResultSetExtractor
  2.  RowMapper

110. Which is the front controller class of Spring MVC?

The Dispatcher Servlet class works as the front controller in Spring MVC.

111. What are the states of an object in hibernate?

The states of an object in hibernate are:

  1. Transient: The objects that are just created having no primary key are in a transient state. Here the objects are associated with any session.
  2. Persistent: When the session of an object is just opened and its instance is just saved or retrieved, it is said to be in a persistent state.
  3. Detached: When the session of an object is closed, it is said to be in a detached state.

112. How to make an immutable class in hibernate?

If we mark a class as mutable=”false”, the class will be treated as an immutable class. The default value of mutable is “true”.

113. What is hash-collision in a HashTable? How is it handled in Java?

In HashTable, if two different keys have the same hash value, then it leads to hash-collision. A bucket of type linked list is used to hold the different keys of the same hash value.

114. Write a syntax to convert a given collection to a SynchronizedCollection.

The following will convert a given collection to a synchronized collection:

Collections.synchronizedCollection(Collection collectionObj)

115. Write a code to make the Collections read-only.

We can make the Collections read-only by using the following lines code:

General : Collections.unmodifiableCollection(Collection c)Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)

116. What is meant by binding in RMI?

Binding is the process of associating or registering a name for a remote object, which can be used as a further, in order to look up that remote object. A remote object can be associated with a name using the bind/rebind methods of the Naming class.

Binding in RMI

117. What is the concept of method chaining in Java?

Method chaining in programming is when multiple method calls are used together with each call on the object returned by the previous one. This allows you to write code that is brief and easy to read. Method chaining is achieved by designing methods to return the object itself (this) after operating.

118. What is the 'this' keyword in Java? Explain with usage.

The ‘this’ keyword in Java refers to the currently created instance of a class. It is employed to distinguish between instance variables and parameters that have identical names, and also to invoke instance methods or constructors.

Example:

class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value; // "this" is used to refer to the instance variable
    }

    public void printValue() {
        System.out.println("Value: " + this.value); // "this" is optional here
    }
}

119. What is a runnable and callable interface in Java?

Runnable: The Runnable interface in Java represents a task that can be executed concurrently by a thread. It contains a single abstract method run() which is called by the thread when it starts executing the task.

Callable: A Callable interface is similar to Runnable; however, it returns a value and can throw checked exceptions. It’s a functional interface containing only one abstract method call() which returns a value of type V.

120. How does Java 8 support parallel processing of collections?

Parallel streams, a concept that was introduced in Java 8, can execute operations on collections concurrently using multiple threads. The essence of parallel streams is to split the data into smaller portions and have them distributed over different threads for handling. This can greatly optimize stream operations on large datasets, especially those running on multicore processors.

121. Discuss the enhancements made to the Comparator interface in Java 8.

To simplify sorting and improve code readability, several enhancements were made to the Comparator interface with the release of Java 8:

  • The introduction of Comparing() method: Allows the creation of comparators based on keys extracted from elements through the use of function
  • Addition of thenComparing() method: Ability to chain comparators used to define secondary sorting criteria
  • Introduction of reverseOrder(), naturalOrder(): Introduce built-in comparators for reverse and natural ordering respectively
  • Null Handling Support: New methods such as nullsFirst() and nullsLast() permit customization of how null values are handled during sorting.

Java Interview Questions for 8 to 10 Years Experience

122. What are latest features introduced in Java 8?

The below features are introduced in Java 8:

  • Lambda Expressions
  • Interface Default and Static Methods
  • Method Reference
  • Parameters Name
  • Optional Streams
  • Concurrency

123. Name a few Java 8 annotations.

@Functional Interface annotation: It was introduced in Java SE 8, which indicates that the type declaration is intended to be a functional interface as defined by the Java language specification.

@Repeatable annotation: Introduced in Java SE 8, @Repeatable annotation indicates that the marked annotation can be applied many times to the same declaration or type use.

124. Distinguish between a predicate and a function.

A predicate takes one argument and returns a Boolean value.

A function takes one argument and returns an object. Both are useful for evaluating lambda expressions.

125. Write a code to sort a list of strings using Java 8 lambda expression.

private void sortUsingJava8(List names){
Collections.sort(names, (p1, p2) -> p1.compareTo(p2));
}

126. What is Nashorn in Java 8?

With Java 8, Nashorn, a much-improved JavaScript engine, is introduced and it replaced the existing Rhino. It provides 2–10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Although, Nashorn uses the invoke dynamic feature, introduced in Java 7, to improve performance.

127. Define a StringJoiner and write a sample code.

StringJoiner is a class in Java that is used to join multiple strings together, optionally adding a delimiter between them. Here’s an example code that demonstrates the usage of StringJoiner:

Sample CodeStringJoiner strJoiner = new StringJoiner(".");
strJoiner.add("AAA").add("BBB");
System.out.println(strJoiner);
OutPut:
AAA.BBB

128. Can you execute the JavaScript code from Java 8 code base?

Yes! We can execute the JavaScript code from Java 8 code base by using ScriptEngineManager. We call JavaScript code and interpret it in Java.

129. What is the use of batch processing in JDBC?

Batch processing is a technique that is used to group a set of related SQL queries and execute them in order. This is done to avoid the execution of a single query at a time.

Batch Processing

Making use of batch processing ensures that the queries execute faster, thereby maintaining the high efficiency and overall speed of execution.

130. What are the types of statements supported by JDBC?

There are three types of statements supported by JDBC as shown below:

  • Statement: Used to execute static queries and for general access to the database
  • CallableStatement: Provides access to stored procedures and runtime parameters
  • PreparedStatement: Provides input parameters to queries while they are executing

131. What is a collection in Java?

A collection is a framework that is used to store and manipulate a container of objects in Java.

Java Collections can be used for performing a variety of operations such as:

  • Search
  • Sort
  • Manipulate
  • Delete

Below is the chart that represents the hierarchy of collections in Java:

Collectiions in Java

132. What is the meaning of constructor overloading in Java?

Constructor overloading is a technique that is popular among programmers who have a requirement of adding multiple constructors to a single class with a different parameter list. The following denotes an example of constructor overloading in Java:

class Hello
{
int i;
public Hello(int x)
{
i=k;
}
public Hello(int x, int y)
{
/* Set of Instruction */
}
}

To clear your doubts you can visit Intellipaat’s Java Community!

133. What is the JDBC Driver?

Java Database Connectivity(JDBC) is an API that allows the client to access different data sources from spreadsheets to flat files and relational databases. It’s a middle layer interface that establishes a connection between java applications and databases. In addition to the connection of data sources, JDBC is used for sending queries and updates to the database, retrieving and processing data received from the database.

There are four types of JDBC drivers:

  • JDBC-ODBC bridge Drivers: Uses Open Database Connectivity(ODBC) to connect with the database. It’s also known as the Universal Driver as it can be used to connect with any database.
  • Native-API Drivers: It’s a partial java Driver that uses client-side libraries of the database to convert JDBC calls into native ones of the database programming interface. The Network-API needs to be installed on individual client machines separately.
  • Network protocol Drivers: The driver uses the middleware or application server to convert the JDBC calls into the vendor-specific protocol. It doesn’t require individual client-side installation as all the connectivity drivers are present in one driver.
  • Thin Drivers: These are portable drivers that won’t require any installation from any client or server-side installation. They directly interact with the database and don’t require any database library to do so.

134. What is the difference between execute, executeQuery, and executeUpdate?

Below are the key differences between execute, executeQuery, and executeUpdate:

execute executeQuery executeUpdate
Used to execute any SQL query and get the result in boolean format (True or False). executeQuery is used to execute the SQL queries and retrieve some data from the database. executeUpdate is used to execute DML (Data Manipulation Language) statements like updating or modifying the database.
Returns a boolean value, where TRUE indicates the query returned is an object of the ResultSet, and FALSE indicates that nothing or an integer value has returned. Returns the ResultSet object that contains the result generated and returned by the query. Returns an integer value representing the number of rows updated or altered by the query.
Used to execute both select and non-select queries. Used to execute select queries. Used to execute non-select queries.
Ex-any SQL statement. Ex- SELECT Ex- INSERT, CREATE, ALTER, DELETEDDL, UPDATE, etc

Want to Prepare for TCS Interview? We have prepared a list of the most common TCS Interview Questions for you.

135. Explain the concept of functional interfaces in Java 8.

A functional interface in Java 8 is an interface that consists of only one abstract method. It can have multiple default or static methods. They are used to implement lambda expressions, which allow for the expression of instances of single-method interfaces (functional interfaces) in a short form of programming language. Some examples of these functional interfaces in Java 8 include Runnable, Comparator, and Callable.

136. What are the advantages of using streams in Java 8?

Streams in Java 8 provide a declarative and functional approach to process collections of data. Here are some benefits of using streams:

  • Consequently, stream operations can be chained together to create codes that are concise and readable.
  • Streams use functional-style operations such as map, filter, and reduce that enhance the clarity and maintainability of code.
  • A Support parallel processing of data streams enhancing performance on multi-core systems.
  • The abstraction layer also removes low-level details involved with iteration while automatically managing resources.

137. How does the Optional class in Java 8 help in handling null values?

Java 8 Optional class provides a means to handle potential null values without needing to explicitly check for null. It makes developers convey their intentions making the code more expressive and safer. Optional can guard against NullPointerExceptions by offering methods like orElse, orElseGet, and orElseThrow that act as default values providers or handlers absent itself.

138. What is the difference between forEach and forEachOrdered methods in Java 8 streams?

A terminal operation is a method that terminates the iteration of elements in a stream. Although both are used to iterate elements in a stream, there is a difference between forEach and forEachOrdered methods:

  • forEach: It processes items in no particular order, meaning it does not guarantee any specific sequence of execution. It can offer improved performance for parallel streams but cannot preserve the original ordering of the stream.
  • forEachOrdered: Elements are processed as per their encounter order provided by the stream. Even for parallel streams, this ensures that items are processed sequentially based on their order of occurrence, it can be more expensive than for.

139. Explain the concept of method references in Java 8

In Java 8, method references provide a shorthand way to create lambda expressions that simply call an existing method. Method references mean you can reuse existing methods as lambdas making code more compact and readable. 

There are four kinds of Method References:

  • Reference to the static method: ContainingClass::staticMethodName
  • Reference to an instance method of a particular object: object::instanceMethodName
  • Reference to an instance method of an arbitrary object of a particular type: ContainingType::methodName
  • Reference to constructor: ClassName::new

Core Java Coding Interview Questions

140. Write a function to determine if a given string is a palindrome.

public boolean palindrome(String s) {
int left = 0, right = s.length() – 1;
while (left < right) { if (s.charAt(left++) != s.charAt(right--)) { return false; } } return true; } [/code]

141. Implement a function to reverse a string.

public String intellipaat(String s) {
    return new StringBuilder(s).reverse().toString();
}

142. Write a program that prints the numbers from 1 to 100. But for multiples of three, print 'Fizz' instead of the number, and for the multiples of five, print 'Buzz'. For numbers that are multiples of both three and five, print 'FizzBuzz'.

<pre>
public void intellipaat() {
    for (int i = 1; i <= 100; i++) {
        if (i % 3 == 0 && i % 5 == 0) {
            System.out.println("FizzBuzz");
        } else if (i % 3 == 0) {
            System.out.println("Fizz");
        } else if (i % 5 == 0) {
            System.out.println("Buzz");
        } else {
            System.out.println(i);
        }
    }
}
</pre>

143. Write a function to determine if two strings are anagrams of each other.

public boolean intellipaat(String str1, String str2) {
    if (str1.length() != str2.length()) {
        return false;
    }
    char[] chars1 = str1.toCharArray();
    char[] chars2 = str2.toCharArray();
    Arrays.sort(chars1);
    Arrays.sort(chars2);
    return Arrays.equals(chars1, chars2);
}

144. Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

public int intellipaat(int[] nums) {
    int n = nums.length;
    int sum = n * (n + 1) / 2;
    for (int num : nums) {
        sum -= num;
    }
    return sum;
}

145. Implement a function to reverse a singly linked list.

class ListNode {
    int v;
    ListNode nxt;

    ListNode(int v) {
        this.v = v;
    }
}

public ListNode S_List(ListNode head) {
    ListNode prev = null;
    ListNode cur = head;
    while (cur != null) {
        ListNode nxt = cur.nxt;
        cur.nxt = prev;
        prev = cur;
        cur = nxt;
    }
    return prev;
}

146. Write a function to determine whether the given number is prime or not.

<pre>
public boolean prime(int n) {
    if (n <= 1) {
        return false;
    }
    for (int x = 2; x * x <= n; x++) {
        if (n % x == 0) {
            return false;
        }
    }
    return true;
}
</pre>

147. Given two sorted arrays, merge them into a single sorted array.

public int[] merge(int[] nums1, int m, int[] nums2, int n) {
    int i = m - 1, j = n - 1, k = m + n - 1;
    while (i >= 0 && j >= 0) {
        if (nums1[i] > nums2[j]) {
            nums1[k--] = nums1[i--];
        } else {
            nums1[k--] = nums2[j--];
        }
    }
    while (j >= 0) {
        nums1[k--] = nums2[j--];
    }
    return nums1;
}

148. Implement a binary search algorithm.

<pre>
public int binary(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}
</pre>

149. Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

<pre>
public boolean palind(int y) {
    if (y < 0) {
        return false;
    }
    int rev = 0, org = y;
    while (y != 0) {
        int rem = y % 10;
        rev = rev * 10 + rem;
        y /= 10;
    }
    return org == rev;
}
</pre>

150. Given an integer array nums, find the contiguous subarray (containing at least one number) that has the largest sum and return its sum.

<pre>
public int large_sum(int[] n) {
    int m_sum = n[0];
    int c_sum = n[0];
    for (int x = 1; x < n.length; x++) {
        c_sum = Math.max(n[x], c_sum + n[x]);
        m_sum = Math.max(m_sum, c_sum);
    }
    return m_sum;
}
</pre>

151. Implement a stack data structure using arrays or linked lists.

class Stack {
    private int maxSize;
    private int[] stackArray;
    private int top;

    public Stack(int size) {
        maxSize = size;
        stackArray = new int[maxSize];
        top = -1;
    }

    public void push(int value) {
        if (top < maxSize - 1) {
            stackArray&#91;++top&#93; = value;
        }
    }

    public int pop() {
        if (top >= 0) {
            return stackArray[top--];
        }
        return -1;
    }

    public int peek() {
        if (top >= 0) {
            return stackArray[top];
        }
        return -1;
    }

    public boolean isEmpty() {
        return (top == -1);
    }
}

152. Implement a queue data structure using stacks.

class MyQueue {
    Stack<Integer> stack1;
    Stack<Integer> stack2;

    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void push(int x) {
        stack1.push(x);
    }

    public int pop() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    public int peek() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.peek();
    }

    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }
}

153. Write a function to calculate the nth number in the Fibonacci sequence.

public int fibonacci(int n) {
    if (n <= 1) {
        return n;
    }
    int a = 0, b = 1;
    for (int i = 2; i <= n; i++) {
        int temp = b;
        b = a + b;
        a = temp;
    }
    return b;
}

154. Write a function to check if a given number is an Armstrong number or not.

public boolean armstrong(int num) {
    int sum = 0;
    int originalNum = num;
    int numDigits = String.valueOf(num).length();
    while (num > 0) {
        int digit = num % 10;
        sum += Math.pow(digit, numDigits);
        num /= 10;
    }
    return sum == originalNum;
}

155. Write a function to count the number of words in a string.

public int countWords(String s) {
    String[] words = s.trim().split("\\s+");
    return words.length;
}

156. Given a sorted array nums, remove the duplicates in place such that each element appears only once and return the new length.

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) {
        return 0;
    }
    int index = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] != nums[index]) {
            nums[++index] = nums[i];
        }
    }
    return index + 1;
}

157. Write a function to calculate the factorial of a given number.

public int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

158. Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), find the duplicate one.

public int findDuplicate(int[] nums) {
    int slow = nums[0];
    int fast = nums[0];
    do {
        slow = nums[slow];
        fast = nums[nums[fast]];
    } while (slow != fast);
    slow = nums[0];
    while (slow != fast) {
        slow = nums[slow];
        fast = nums[fast];
    }
    return slow;
}

159. Implement a simple hashmap data structure.

class MyHashMap {
    private final int SIZE = 1000;
    private final ListNode[] nodes;

    public MyHashMap() {
        nodes = new ListNode[SIZE];
    }

    public void put(int key, int value) {
        int index = getIndex(key);
        if (nodes[index] == null) {
            nodes[index] = new ListNode(-1, -1);
        }
        ListNode prev = find(nodes[index], key);
        if (prev.next == null) {
            prev.next = new ListNode(key, value);
        } else {
            prev.next.val = value;
        }
    }

    public int get(int key) {
        int index = getIndex(key);
        if (nodes[index] == null) {
            return -1;
        }
        ListNode prev = find(nodes[index], key);
        return prev.next == null ? -1 : prev.next.val;
    }

    public void remove(int key) {
        int index = getIndex(key);
        if (nodes[index] == null) {
            return;
        }
        ListNode prev = find(nodes[index], key);
        if (prev.next != null) {
            prev.next = prev.next.next;
        }
    }

    private int getIndex(int key) {
        return Integer.hashCode(key) % SIZE;
    }

    private ListNode find(ListNode bucket, int key) {
        ListNode node = bucket, prev = null;
        while (node != null && node.key != key) {
            prev = node;
            node = node.next;
        }
        return prev;
    }

    private static class ListNode {
        int key, val;
        ListNode next;

        ListNode(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
}

Java Scenario Based Interview Questions

160. Suppose you are working to produce a multi-threaded application that imitates a banking system. Customers can deposit and withdraw money from their accounts. How could thread synchronization be used to make sure that the balance of an account is updated correctly even when multiple threads are trying to update the balance at once?

This would signify that only one thread will execute these methods during a given instance preventing any race condition where the final balance might not reflect all transactions because they occurred simultaneously, thus it updates all these things correctly using this synchronized keyword in them.

class BankAccount {
    private int balance = 0;

    public synchronized void deposit(int amount) {
        balance += amount;
        System.out.println("Deposited " + amount + ", new balance is " + balance);
    }

    public synchronized void withdraw(int amount) {
        if (balance >= amount) {
            balance -= amount;
            System.out.println("Withdrew " + amount + ", new balance is " + balance);
        } else {
            System.out.println("Insufficient balance");
        }
    }
}

class BankingThread extends Thread {
    private BankAccount account;

    public BankingThread(BankAccount account) {
        this.account = account;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            account.deposit(100);
            account.withdraw(50);
        }
    }
}

public class BankingSystem {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        BankingThread t1 = new BankingThread(account);
        BankingThread t2 = new BankingThread(account);

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final balance: " + account.getBalance());
    }
}

161. Imagine a scenario involving the development of a chat application which makes it possible for many users to send messages on one chat room. In what way is it possible to use thread synchronization to make sure that messages are displayed in the right order, even when multiple users are sending them at the same time?

To maintain message display order, the keyword “synchronized” would be used to synchronize access to the method which adds messages into the chat room. Thus, only one thread can add a message at a time and this maintains their order as they come in.

class ChatRoom {
    private final List messages = new ArrayList<>();

    public synchronized void addMessage(String message) {
        messages.add(message);
        System.out.println(message);
    }
}

class UserThread extends Thread {
    private ChatRoom chatRoom;
    private String userName;

    public UserThread(ChatRoom chatRoom, String userName) {
        this.chatRoom = chatRoom;
        this.userName = userName;
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            chatRoom.addMessage(userName + ": Message " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ChatApplication {
    public static void main(String[] args) {
        ChatRoom chatRoom = new ChatRoom();
        UserThread user1 = new UserThread(chatRoom, "User1");
        UserThread user2 = new UserThread(chatRoom, "User2");

        user1.start();
        user2.start();

        try {
            user1.join();
            user2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

162. Think of yourself working on a system that processes massive amounts of data all at once for you. The system has multiple threads that read from a shared data source, do some math with it, and then store the results in the shared output. How would you prevent deadlocks in this situation?

To avoid them, make sure all threads acquire locks in the same order. Alternatively, the wait() method can be used with timeouts to prevent infinite waiting, as well as periodical checks for deadlock conditions.

class Message {
    private String message;
    private boolean empty = true;

    public synchronized String read() {
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
        empty = true;
        notifyAll();
        return message;
    }

    public synchronized void write(String message) {
        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
        empty = false;
        this.message = message;
        notifyAll();
    }
}

163. You are tasked to create a web application that uses a shared resource, such as a database connection pool, to handle requests. How would you use the ‘volatile’ keyword to make sure that all threads see the most recent state of the connection pool?

By declaring the connection pool reference as volatile, you make sure that changes made to the reference by one thread are immediately visible to other threads. This is important for making sure that all threads work on the most current state of the connection pool, preventing issues like using a closed or invalid connection.

class ConnectionPool {
    private volatile List<Connection> connections = new ArrayList<>();

    public synchronized Connection getConnection() {
        if (connections.isEmpty()) {
            System.out.println("Creating a new connection");
            connections.add(new Connection());
        }
        return connections.remove(connections.size() - 1);
    }

    public synchronized void releaseConnection(Connection connection) {
        connections.add(connection);
        System.out.println("Connection released");
    }
}

class Connection {
    // Simulate a connection
}

class DatabaseTask extends Thread {
    private ConnectionPool pool;

    public DatabaseTask(ConnectionPool pool) {
        this.pool = pool;
    }

    public void run() {
        Connection connection = pool.getConnection();
        // Use the connection
        pool.releaseConnection(connection);
    }
}

public class ConnectionPoolDemo {
    public static void main(String[] args) {
        ConnectionPool pool = new ConnectionPool();
        DatabaseTask task1 = new DatabaseTask(pool);
        DatabaseTask task2 = new DatabaseTask(pool);

        task1.start();
        task2.start();

        try {
            task1.join();
            task2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

164. Imagine that you are designing a Java application for an ongoing background task, which will be responsible for verifying updates from a distant server regularly. The job should have the ability to be halted at any time. How do you implement this task using thread interruption?

The background routine could be implemented as a Runnable or Thread class that would check for updates in a loop. This would mean that within the loops, one might invoke Thread.sleep() to momentarily halt it and handle InterruptedException when it crops up. Furthermore, if it is necessary to stop the task you can simply call interrupt() method on the thread which signals its interrupted status and causes InterruptedException during Thread.sleep(). The program can then exit gracefully by checking its interrupted status and telling the loop to stop running.

class BackgroundTask implements Runnable {
    private volatile boolean running = true;

    public void run() {
        while (running) {
            try {
                // Simulate work
                System.out.println("Checking for updates...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Task interrupted, stopping...");
                running = false;
            }
        }
    }

    public void stop() {
        running = false;
    }
}

public class BackgroundTaskDemo {
    public static void main(String[] args) {
        BackgroundTask task = new BackgroundTask();
        Thread thread = new Thread(task);

        thread.start();

        try {
            Thread.sleep(5000); // Let the task run for 5 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        task.stop(); // Stop the task
    }
}

165. Imagine you are developing a Spring Boot application that manages a library. Users can borrow and return books. How would you use Spring's @Transactional annotation to ensure that the operations of borrowing and returning a book are atomic, meaning either both operations succeed or both fail?

You would use the @Transactional annotation on the service methods that handle the borrowing and returning of books. This ensures that if an exception occurs during either operation, the transaction will be rolled back, maintaining the integrity of your data.

@Service
public class LibraryService {

    @Autowired
    private BookRepository bookRepository;

    @Transactional
    public void borrowBook(Long bookId, Long userId) {
        Book book = bookRepository.findById(bookId).orElseThrow(() -> new BookNotFoundException("Book not found"));
        if (book.isBorrowed()) {
            throw new BookAlreadyBorrowedException("Book is already borrowed");
        }
        book.setBorrowed(true);
        book.setUserId(userId);
        bookRepository.save(book);
    }

    @Transactional
    public void returnBook(Long bookId) {
        Book book = bookRepository.findById(bookId).orElseThrow(() -> new BookNotFoundException("Book not found"));
        if (!book.isBorrowed()) {
            throw new BookNotBorrowedException("Book is not borrowed");
        }
        book.setBorrowed(false);
        book.setUserId(null);
        bookRepository.save(book);
    }
}

166. Imagine you are working on a logging system where you need to log messages with different severity levels (INFO, WARN, ERROR). How would you design a custom functional interface to handle this in Java 8?

A custom functional interface named Logger can be defined with only one abstract method log(String message, Severity severity). This way you can create an implementation for this interface using lambda expressions for each level of severity. The following is how you may declare and use this interface.

@FunctionalInterface
interface Logger {
    void log(String message, Severity severity);
}

enum Severity {
    INFO, WARN, ERROR
}

public class Main {
    public static void main(String[] args) {
        Logger logger = (message, severity) -> System.out.println(severity + ": " + message);
        logger.log("Application started", Severity.INFO);
        logger.log("An error occurred", Severity.ERROR);
    }
}

167. Suppose you have a list of user IDs and you need to transform them into user objects by fetching user details from a database. How would you use the Function interface in Java 8 to achieve this?

The Function interface is used to define a lambda expression that takes a user ID and returns a user object. Below is an example:

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<String, User> fetchUser = (userId) -> {
            // Simulate fetching user details from a database
            return new User(userId, "John Doe", "[email protected]");
        };

        String userId = "123";
        User user = fetchUser.apply(userId);
        System.out.println(user.getName()); // Output: John Doe
    }
}

class User {
    private String userId;
    private String name;
    private String email;

    public User(String userId, String name, String email) {
        this.userId = userId;
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }
}

168. You are working on a task management application, and you need to filter a list of tasks based on their priority. How would you use the Predicate interface in Java 8 to filter tasks marked as high priority?

The task-parameterized predicate interface can be used to define the lambda expression that indicates if the given task is a high priority or not, in our context let me give you an example:

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        List<Task> tasks = Arrays.asList(
            new Task("Task 1", "High"),
            new Task("Task 2", "Medium"),
            new Task("Task 3", "High")
        );

        Predicate<Task> isHighPriority = task -> task.getPriority().equals("High");

        List<Task> highPriorityTasks = tasks.stream()
            .filter(isHighPriority)
            .collect(Collectors.toList());

        highPriorityTasks.forEach(task -> System.out.println(task.getName()));
        // Output: Task 1, Task 3
    }
}

class Task {
    private String name;
    private String priority;

    public Task(String name, String priority) {
        this.name = name;
        this.priority = priority;
    }

    public String getName() {
        return name;
    }

    public String getPriority() {
        return priority;
    }
}

169. Consider a scenario where you need to perform calculations on two numbers, such as addition, subtraction, multiplication, and division. How would you use the BiFunction interface in Java 8 to implement these operations?

The BiFunction interface helps us to create an interconnection between two parameters that will be added, subtracted, multiplied, or divided according to a certain condition using appropriate arithmetic operators through lambdas in a few lines of code as shown below.

import java.util.function.BiFunction;
public class Main {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
        BiFunction<Integer, Integer, Integer> subtract = (a, b) -> a - b;
        BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b;
        BiFunction<Integer, Integer, Integer> divide = (a, b) -> a / b;

        System.out.println(add.apply(10, 20)); // Output: 30
        System.out.println(subtract.apply(200, 100)); // Output: 100
        System.out.println(multiply.apply(200, 100)); // Output: 20000
        System.out.println(divide.apply(200, 100)); // Output: 2
    }
}

170. Suppose you are developing a web application that requires detailed logging of various events, such as user actions, system errors, and performance metrics. How would you implement a robust logging system using Java 8 lambdas to improve the readability and maintainability of your logging code?

To implement a robust logging system, Apache Log4j framework supporting Java 8 lambdas can provide an alternative solution that will enable writing more readable and clean logging code as illustrated by the subsequent example on how to use Lambda expression with Log4j for debugging purposes.

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class WebApplication {
    private static final Logger logger = LogManager.getLogger(WebApplication.class);

    public void userAction(String action) {
        logger.debug(() -> String.format("User performed action: %s", action));
    }

    public void systemError(String errorMessage) {
        logger.error(() -> String.format("System error occurred: %s", errorMessage));
    }

    public void performanceMetric(String metric) {
        logger.info(() -> String.format("Performance metric: %s", metric));
    }
}

171. Your web application frequently accesses external resources, such as databases or APIs, which can throw exceptions. How would you handle exceptions gracefully to ensure your application can recover from errors and continue to function without disrupting the user experience?

In your method within a Web application development try-catch blocks might have been used to handle expected exceptions gracefully. Moreover, we are also able to utilize lambda expressions to wrap up logic that might cause trouble therefore making it easy for us during management and debugging processes when we need them most. For instance, handling SQLExceptions

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.function.Function;

public class DatabaseAccess {
    private Connection connection;

    public DatabaseAccess() {
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to connect to database", e);
        }
    }

    public void queryDatabase(String query, Function<ResultSet, Void> resultProcessor) {
        try (Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(query)) {
            resultProcessor.apply(resultSet);
        } catch (SQLException e) {
            logger.error(() -> String.format("Failed to execute query: %s", query), e);
            // Handle the exception appropriately
        }
    }
}

172. Your high-traffic web application is experiencing performance issues, and you suspect that inefficient use of heap memory is the root cause. How would you optimize heap memory usage to improve application performance?

To reduce the use of heap memory you have to be very careful about how object creation and disposal are managed, monitor memory usage, and adjust garbage collection parameters as per the requirements of your application. You can examine memory consumption using visual VM, YourKit, or jconsole which helps identify memory bottlenecks. This will make sure that there are no more objects to be collected by the garbage collector if its tuning is well done.

173. Your large-scale data processing application frequently encounters OutOfMemoryError. How would you diagnose and resolve this issue to prevent application crashes?

When diagnosed with OutOfMemoryError, you must start by analyzing the heap dump generated at that time. An OutOfMemoryError occurs and -XX:HeapDumpOnOutOfMemory parameter causes a heap dump file to be created. The Heap Dump will show you what objects are occupying the most space and never being reclaimed by the garbage collector among other things. Furthermore, using -verbose:gc option allows monitoring of garbage collection behavior via its output. Based on this analysis, one can either increase JVM’s memory allocation towards an application’s optimization for instance adjusting initial/maximum heap size, or better manage its internal patterns of memory use.

174. Your application requires low-latency processing and you're concerned about garbage collection pauses affecting performance. How would you implement a custom garbage collection strategy to minimize these pauses?

To minimize garbage collection pauses in an application with low latency, you might want to consider employing Z Garbage Collector (ZGC), which was introduced in Java 11. ZGC has been designed for applications that stress the need for responsiveness, minimizing pause time during garbage collection. To use ZGC, a user needs to specify -XX:+UseZGC option when starting a Java application. For instances where the system is required to handle huge memory sizes, it can continue collecting older objects without pausing for long durations.

175. Imagine you're working on a large database application where performance is critical. You need to retrieve a large set of data from a database and then perform operations on this data. How would you choose the most efficient Java collection to store this data, considering the operations you need to perform?

If you have a large dataset retrieved from a database that may require operations like searching or sorting, then a TreeSet or LinkedHashSet would be a relevant option. TreeSet retains its elements in sorted order which could be very useful if you need to perform any sorted operation on your data set. On the other hand, LinkedHashSet keeps the insertion order which becomes useful if you care about the elements’ order in your operations. Nevertheless, if one needs frequent access by index ArrayList or LinkedList may make more sense as they have constant-time positional access even though their elements are not inherently sorted out.

176. You are tasked with implementing a multi-threaded caching system that can handle concurrent access to cached data. How would you use Java collections to ensure thread safety and efficient data access?

If you have a multithreaded caching system, it will likely use a ConcurrentHashMap to preserve the cached data. ConcurrentHashMap is designed for concurrent access without requiring external synchronization and, thus, it is ideal for multi-threaded environments. This class also provides thread-safe operations like put(), get(), and remove(), which are important for any caching system that may have multiple threads reading or writing the cache at the same time. Additionally, if one wants to iterate through the map when it’s being modified, they can use keySet(), entrySet(), or values() methods provided by ConcurrentHashMap so that they obtain a collection view that can be modified concurrently.

177. Your web application needs to manage user sessions, ensuring that each user has a unique session ID and that session data is stored efficiently. How would you use Java collections to implement this feature?

In a web application managing user sessions can be done with the help of a HashMap where session data is stored such as each session ID serving as keys and each session value given in return. By using session ID you can retrieve your session data faster since this approach allows efficient retrieval of these kinds of information from the server side. It may also be used conveniently where there are no requirements for maintaining any order over its elements as HashMap does not maintain any order on its elements. If you would want to keep sessions insertion ordered, LinkedHashMap is recommended because it maintains them according to their insertion order. This could enable developers to implement decisions like expiring sessions based on their creation times.

178. You are developing a task scheduling system where tasks have different priorities. How would you use Java collections to implement a priority queue that efficiently handles tasks based on their priority?

A PriorityQueue could be used to execute a priority queue for task scheduling. The elements of the PriorityQueue are sorted by their natural order or with a custom comparator passed when constructing the queue. This is ideal for managing tasks based on priority since those at a higher position are dequeued first. The class PriorityQueue has efficient enqueue and dequeue operations that make it useful for a task scheduling system that processes tasks according to their priority.

179. You are building an e-commerce application where users can add items to their shopping cart. How would you use Java collections to implement the shopping cart feature, ensuring that each user has a unique shopping cart and that items within the cart are uniquely identified?

In an e-commerce application, this feature can be done using a HashMap where each key represents a user ID and the value is another collection such as HashSet or LinkedList showing items in users’ shopping carts. It helps avoid adding duplicate items as each item is only represented once in the cart with the help of HashSet which does not allow duplicates. If you want to add items while keeping track of insertion order, then consider using LinkedList because it maintains insertion order among its elements. This method enables additions and retrievals from shopping carts to be made more effectively and concurrently ensures the uniqueness of every item there.

Java MCQ Interview Questions

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

  1. 32 and 64
  2. 32 and 31
  3. 64 and 69
  4. 64 and 32

Ans: A.  32 and 64

181. Automatic type conversion is possible in which of the possible cases?

  1. Byte to float
  2. Byte to long
  3. Int to long
  4. Long to byte

Ans: C. Int to long

182. What is the output of the snippet:

int Int = 20
System.out.println(Int);

  1. Compiler error
  2. Runtime error
  3. 224
  4. 24

Ans: A. Compiler error

183. On passing an array to a method, what does the method receive?

  1. Reference to memory
  2. Copy of array
  3. Length of array
  4. Reference of array

Ans: D. Reference of array

184. Which is the valid statement to declare and initialize an array?

  1. int[] A = {}
  2. int[] A = {1,2,3}
  3. int[] A = {134)
  4. int[] A = (1,3,5)

Ans: B.  int[] A = {1,2,3}

185. Arrays in Java are:

  1. Objects reference
  2. Objects
  3. Data type
  4. All of the above 

Ans: B. Objects

186. When is the object created with a new keyword?

  1. At run time 
  2. At compile time
  3. Depends on code
  4. None

Ans: A.  At run time

187. Identify the correct statement.

  1. Package is collection of editing tools
  2. Package is collection of goods
  3. Package is collection of classes and interfaces
  4. All of the above

Ans: C.  Package is collection of classes and interfaces

188. compareTo() returns

  1. True
  2. False
  3. An int value
  4. None

Ans: C.  An int value

189. Which is the string class:

  1. java.lang
  2. java.awt
  3. java.applet
  4. java.string

Ans: A. java.lang

190. Total constructor in string class:

  1. 3
  2. 7
  3. 13
  4. 20

Ans: C. 13

191. Return type of method that doesn’t return any value:

  1. int
  2. void
  3. double
  4. None

Ans: B. void

192. Who invented Java Programming?

  1. Guido van Rossum
  2. James Gosling
  3. Dennis Ritchie
  4. Bjarne Stroustrup

Ans: B.  James Gosling

193. What are the number of primitive data types in Java?

  1. 6
  2. 7
  3. 8
  4. 9

Ans: C. 8

194. Which component is used to compile, debug and execute the Java programs?

  1.  JRE
  2. JIT
  3. JDK
  4. JVM

Ans: C. JDK

195. Which environment variable sets Java path?

  1. My_Path
  2. JPATH
  3. JHTTP
  4. JAVA_HOME

Ans: D. JAVA_HOME

196. What is the output:

class Intellipaat {
        public static void main(String args[]) 
        {
            double e, f,g;
            e = 3.0/0;
            f = 0/4.0;
            g=0/0.0;
 
	    System.out.println(e);
        } 
    }
  1. 0
  2. 12
  3. Zero Division Error
  4. All of the above

Ans: C.  Zero Division Error

197. Find out the error:

class variable_scope 
    {
        public static void main(String args[]) 
        {
            int x;
            x = 5;
            {
	        int y = 6;
	        System.out.print(x  " " + y);
            }
            System.out.println(x  " " + y);
        } 
    }
  1. System.out.print(x  ” ” + y);and  System.out.println(x  ” ” + y);
  2.  x = 5; and int y = 6;
  3. Y is not accessible in the code
  4. Both A and C

Ans: D.  Both A and C

198. State error:

Byte a = 10;

a = a * 10;

  1. Variable a can’t have value 10.
  2. Variable a can’t have a value of 100
  3. No error
  4. Multiplication operator converts the data type to Int

Ans: D. Multiplication operator converts the data type to Int

199. Fill in the missing code

public class MissingCodeSnippet {
    public static void main(String[] args) {
        int x = 5;
        int y = 3;
        
        // Missing code snippet
        
        System.out.println("Result: " + z);
    }
}
  1. int z = x +y;
  2. int z = x – y;
  3. int z = x * y;
  4. None of the above

Ans: A. int z = x +y;

200. Select the correct option:

public class Palindrome {

// Function to check if a string is palindrome
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() – 1;

while (left < right) { if (str.charAt(left) != str.charAt(right)) { return false; } left++; right--; } return true; } public static void main(String[] args) { String option1 = "racecar"; String option2 = "hello"; String option3 = "level"; String option4 = "world"; System.out.println("Option 1 is palindrome: " + isPalindrome(option1)); } } [/code]

  1. isPalindrome(option1)
  2. isPalindrome(option2)
  3. isPalindrome(option3)
  4. isPalindrome(option4)

Ans: A. isPalindrome(option1)

201. What is 'Truncation'?

  1. Giving a floating point to an integer type
  2. Assigning a floating-point value to an integer type.
  3. Assigning an integer value to a floating type
  4. Assigning an integer value to a floating type.

Ans: B. Assigning a floating-point value to an integer type.

202. Output of the following code:

class abc {
    public static void main(String args[]) {
        if(args.length > 0)
            System.out.println(args.length);
    }
}
  1. Prints length of array argos.
  2. prints nothing because the condition in the if statement is always false.
  3. Prints the number of command-line arguments passed when running the program.
  4. It will result in a compilation error because the args array is not initialized

Ans: C.  Prints the number of command-line arguments passed when running the program.

203. Which is the out of memory exception:

  1. MemoryErrorOut
  2. OutOfMemoryError
  3. Memoryoutofindex
  4. None

Ans: B. OutOfMemoryError

204. Selection statements of Java are:

  1. break
  2. continue
  3. for()
  4. if()

Ans: D. if()

205. Which is the superclass of every java class:

  1. ArrayList
  2. Abstract class
  3. Object class
  4. String

Ans: C. Object class

206. Output for the code will be

public class PrintArray {
public static void main(String[] args) {
int[] numbers = new int[11];
int start = 10;
for (int i = 0; i < numbers.length; i++) { numbers[i] = start++; } System.out.println("Array :"); for (int num : numbers) { System.out.print(num + " "); } } } [/code]

  1. int[] numbers = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
  2. int[] numbers = new int[11]; for (int i = 10; i <= 20; i++) { numbers[i – 10] = i; }
  3. int[] numbers = new int[11]; for (int i = 10; i <= 20; i++) { numbers[i + 10] = i; }
  4. int[] numbers = new int[11]; for (int i = 0; i < 10; i++) { numbers[i] = 10 + i; }

Ans: A. int[] numbers = new int[11]; for (int i = 10; i <= 20; i++) { numbers[i – 10] = i; }

207. Give output

public class ArraySum {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int sum = 0;
        
        for (int num : numbers) {
            sum += num;
        }
        
        System.out.println("Sum of elements: " + sum);
    }
}
  1. Sum of elements: 15
  2. Sum of elements: 10
  3. Sum of elements: 0
  4. Sum of elements: 25

Ans: A. Sum of elements: 15

208. Output of the code:

public class StringConcatenation {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "World";
        String result = str1 + str2;
        
        System.out.println(result);
    }
}
  1. Hello World
  2. HelloWorld
  3. Hello + World
  4. Compilation error

Ans: A. Hello World

209. Code gives

public class ArrayLength {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        
        System.out.println("Length of array: " + numbers.length);
    }
}
  1. Length of array: 0
  2. Length of array: 5
  3. Length of array: 1
  4. Compilation error

Ans: B. Length of array:5

CTA

Java Developer Salary Trends

Job Role  Average Salary in India Average Salary in the USA
Java Developers – Experience (0 – 9) years Minimum – 1.8 LPA Minimum – 67,626 USD
Average – 5.8 LPA Average – 92,611 USD
Highest – 17.9 LPA Highest – 126,826 USD

Java Developers Job Trends

Job Opportunities in Java:

There are multiple job roles in Java. Here are a few of them:

Job Role Description
Junior Java Developer Works on module development under the guidance of senior developers. It focuses on core Java, data structures, and databases.
Java Developer Builds applications and systems end-to-end. Proficient in Java, Spring, Hibernate, and web services.
Senior Java Developer Leads project development and code reviews. Deep expertise in architecture and advanced Java EE technologies.
Java Tech Lead Owns delivery for the entire product development lifecycle. Provides guidance to developers and testers in a team.
Java Architect Develops overall software architectures and high-level technical designs. Ensures the scalability and performance of complex systems.


According to a job description posted by Tata Consultancy Services on Linkedin
Role: Java Software Engineer

Java Developer Roles and Responsibilities

Roles and Responsibilities:

  • Hands-on experience in Java and Spring Boot (primary skills).
  • Secondary skills required: SQL and one database, such as Oracle or MongoDB.
  • Well versed in Lambda expressions.
  • Experience in Docker, Kubernetes, /OpenShift is also expected.
  • Enterprise application development experience using CI/CD pipelines.
  • Good command of code version management.
  • Experience in unit testing frameworks.
  • Agile development experience.
  • Roles require interaction with developers distributed across locations.
  • Good communication skills and good analytical skills.

Conclusion

I hope this set of Java Interview Questions will help you prepare for your interviews. Best of luck in your endeavors!

If you are looking to embark on a Java journey that will uplift your career, check out Intellipaat’s Java course, for an enriching learning experience and career growth. 

Got any questions regarding Java? Post your query in the Intellipaat Community space, and we will get back to you.

Course Schedule

Name Date Details
Python Course 20 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 04 May 2024(Sat-Sun) Weekend Batch
View Details