Java Interview Questions

Java Interview Questions

Java Interview Questions

Java is a popular object-oriented programming language that is used worldwide. Here are some common interview questions that you might encounter if you’re applying for a role that requires knowledge of Java.

1. What is Java?

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.

2. Explain public static void main(String args[]).

This is the main method which is the entry point for any Java program. The keywords have the following meaning:

  • public: It is an access modifier that means the method can be accessed from outside the class.
  • static: It is a keyword which indicates that the method can be called without creating an instance of the class.
  • void: It means the method doesn’t return any value.
  • main: It’s the name of the method.
  • String args[]: It’s an array of String objects, allowing the program to take arguments at the command line.

3. What is an Object and a Class?

A class is a blueprint or template from which objects are created. A class contains methods and variables that will be part of each object created from the class.

An object is an instance of a class. It has state and behavior. The state is represented by attributes or variables and the behavior is represented by methods.

public class Car {
    // State
    private String color;
    private String model;

    // Behavior
    public void accelerate() {
        System.out.println("Car is accelerating");
    }

    // getters and setters
}

In the above example, Car is a class and it has state (color, model) and behavior (accelerate method).

4. What is Inheritance?

Inheritance is one of the four fundamental OOP concepts. The other three are Encapsulation, Polymorphism, and Abstraction. Inheritance allows a class (Child class) to inherit the features(fields and methods) of another class (Parent class).

public class Vehicle {
    public void startEngine() {
        System.out.println("Starting engine...");
    }
}

public class Car extends Vehicle {
    public void accelerate() {
        System.out.println("Accelerating...");
    }
}

In the above example, Car is a child class that inherits the startEngine method from the Vehicle parent class.

5. What is Polymorphism?

Polymorphism is another fundamental concept of OOP. It allows us to perform a single action in different ways. In Java, we use method overloading and method overriding to achieve polymorphism.

public class Animal {
    public void sound() {
        System.out.println("The animal makes a sound");
    }
}

public class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("The dog barks");
    }
}

In the above example, the Dog class overrides the sound method of the Animal class. This is an example of polymorphism.


6. What is Encapsulation?

Encapsulation is one of the four fundamental OOP concepts. It refers to the bundling of data, and the methods that operate on that data, into a single unit called a class. In Java, encapsulation is achieved using private fields and public getters and setters.

public class Employee {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

In the above example, the name field of the Employee class is private, so it’s hidden from other classes. It can only be accessed through the public getName and setName methods.

7. What is Abstraction?

Abstraction is another fundamental concept of OOP. It refers to the practice of hiding complex details and showing only the essential features of the object. In Java, abstraction is achieved using abstract classes and interfaces.

public abstract class Animal {
    public abstract void sound();
}

public class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("The dog barks");
    }
}

In the above example, Animal is an abstract class that has an abstract method sound. The Dog class extends the Animal class and provides an implementation for the sound method.

8. What is the difference between an Interface and an Abstract Class?

An interface is a completely abstract class that can only declare methods but not implement them. A class can implement multiple interfaces.

An abstract class can have both abstract and non-abstract methods. A class can extend only one abstract class.

9. What is Exception Handling?

Exception handling is a mechanism to handle runtime errors. It maintains the normal flow of the application. The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application, which is why we use exception handling.

10. What is a Java Package?

A Java package is a group of similar types of classes, interfaces, and sub-packages. It provides access protection and removes naming collision.

Absolutely, here are some more Java interview questions:

11. What is Multithreading?

Multithreading is a feature in Java that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Threads are independent, they don’t affect the execution of other threads. An exception in one thread will not interrupt other threads.

12. What is the difference between ArrayList and LinkedList?

Both ArrayList and LinkedList are implementation of List interface. They both maintain the elements insertion order. The main difference between them is their performance: ArrayList is faster for stored data retrieval while LinkedList is faster for adding and removing elements.

13. What is a Java Lambda Expression?

Lambda expression is a new and important feature of Java which was included in Java 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.

List<String> list = new ArrayList<String>();
list.add("Rick");
list.add("Negan");
list.add("Daryl");

list.forEach(
    (names)->System.out.println(names)
);

In the above example, (names)->System.out.println(names) is a lambda expression.

14. What is the Java Stream API?

The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are:

  • It is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
  • Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
  • Each intermediate operation is lazily executed and returns a stream as a result.

15. What is JDBC?

JDBC (Java Database Connectivity) is a standard Java API for database-independent connectivity between Java & a wide range of databases. The JDBC library includes APIs for each of the tasks commonly associated with database usage:

  • Making a connection to a database
  • Creating SQL or MySQL statements
  • Executing that SQL or MySQL queries in the database
  • Viewing & Modifying the resulting records

Sure, here are some more Java interview questions:

16. What is the difference between == and equals() in Java?

In Java, == operator compares the memory locations of two objects to check their equality, while equals() method compares the content of the objects.

17. What is the difference between final, finally, and finalize?

final is a keyword used to apply restrictions on class, method, and variable. A final class cannot be subclassed, a final method cannot be overridden, and a final variable value cannot be changed.

finally is a block that is used to execute important code such as closing connection, stream etc. It always executes whether an exception is handled or not.

finalize is a method that is invoked by the garbage collector before an object is being garbage collected. This method can be used to perform cleanup processing.

18. What is the purpose of default keyword in Java?

The default keyword in Java is used in switch statements to specify the block of code that should be executed if none of the case statements match the switch expression. It is also used in interfaces from Java 8 onwards to provide default implementations of methods.

19. What is a Java Annotation?

Annotations are used to provide meta data for your Java code. They do not directly affect the execution of your code, although some types of annotations can actually be used for that purpose. Java built-in annotations are @Override, @Deprecated, @SuppressWarnings, etc.

20. What is Java Reflection API?

Java Reflection is a process of examining or modifying the runtime behavior of a class at runtime. The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.

21. What is the difference between ArrayList and Vector?

ArrayList and Vector both implement the List interface and use a dynamically resizable array to store elements. The primary difference between them is that Vector is synchronized, which means it is thread-safe and can be used in a multi-threaded environment, while ArrayList is not synchronized.

22. What is a Singleton class?

A Singleton class is a class that can have only one object (an instance of the class) at a time. The purpose of the singleton class is to control object creation, limiting the number of objects to only one.

public class Singleton {
    private static Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

In the above example, the Singleton class has a private constructor, so other classes cannot instantiate it. The getInstance method returns the singleton instance.

23. What is the difference between throw and throws?

throw is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception.

throws is used to declare an exception and delay the handling of a checked exception. throws is followed by exception class names.

24. What is Serialization and Deserialization?

Serialization is a mechanism of converting the state of an object into a byte stream. It is mainly used to travel object’s state on the network (known as marshalling).

Deserialization is the reverse process of serialization where we convert byte stream into an object.

25. What is JavaBean?

JavaBean is a java class that should follow following conventions:

  • It should have a no-arg constructor.
  • It should be Serializable.
  • It should provide methods to set and get the values of the properties, known as getter and setter methods.

Sure, here are some more Java interview questions:

26. What is Autoboxing and Unboxing?

Autoboxing is the automatic conversion of primitive types to the object of their corresponding wrapper classes. Unboxing is the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing.

27. What is the Collection Framework in Java?

The Collection Framework in Java is a unified architecture for representing and manipulating collections. It includes interfaces like List, Set, Queue, Deque and classes like ArrayList, Vector, LinkedList, HashSet, LinkedHashSet, TreeSet.

28. What is the difference between Comparable and Comparator interfaces?

The Comparable interface is used to sort objects in their natural order using the compareTo() method. The Comparator interface is used to sort objects in a custom order using the compare() method. We can define a different ordering for objects.

29. What is Java Generics?

Java Generics add stability to your code by making more of your bugs detectable at compile time. It allows type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well.

30. What is Java Enum?

Java Enum is a type whose fields consist of a fixed set of constants. The enum keyword is used to define a type of enum and the curly braces contain an optional list of comma-separated constants. For example, you could represent the days of the week as an enum called Day.

Sure, here are some more Java interview questions:

31. What is Java Reflection API?

Java Reflection is a process of examining or modifying the runtime behavior of a class at runtime. The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.

32. What is JVM, JRE, and JDK?

JVM (Java Virtual Machine) is an abstract machine that provides a runtime environment in which Java bytecode can be executed.

JRE (Java Runtime Environment) is a software distribution that contains Java Virtual Machine (JVM), libraries, and other components necessary to run Java applications.

JDK (Java Development Kit) is a software development environment that includes JRE, compilers, and various tools for developing, debugging, and monitoring Java applications.

33. What is Java ClassLoader?

The ClassLoader in Java is a part of the Java Runtime Environment that dynamically loads Java classes into the JVM. It is used to load classes and interfaces.

34. What is Java NIO?

Java NIO (New IO) is an alternative IO API for Java (from Java 1.4), meaning alternative to the standard Java IO and Java Networking API’s. Java NIO offers a different way of working with IO than the standard IO API’s.

35. What is Java AWT and Swing?

AWT (Abstract Window Toolkit) and Swing are used in Java for creating standalone applications and applets. While AWT contains a number of pre-assembled components such as menu, button, list, etc., Swing is a GUI widget toolkit for Java that is part of the Java Foundation Classes.

Sure, here are some more Java interview questions:

36. What is Java Servlet?

A Servlet is a Java class that is used to extend the capabilities of servers that host applications accessed via a request-response model. Servlets can respond to any type of request, but they are commonly used to extend the applications hosted by web servers.

37. What is JavaServer Pages (JSP)?

JavaServer Pages (JSP) is a technology used for developing webpages that support dynamic content. This helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.

38. What is Java Persistence API (JPA)?

The Java Persistence API (JPA) is a Java specification for accessing, persisting, and managing data between Java objects / classes and a relational database. JPA was defined as part of the EJB 3.0 specification as a replacement for the EJB 2 CMP Entity Beans specification.

39. What is JavaServer Faces (JSF)?

JavaServer Faces (JSF) is a Java specification for building component-based user interfaces for web applications. It is also a MVC web framework that simplifies construction of user interfaces (UI) for server-based applications by using reusable UI components in a page.

40. What is Java Message Service (JMS)?

Java Message Service (JMS) is a Java Message Oriented Middleware used to send messages between clients and works by sending messages to a message queue which are then taken when possible to execute a transaction.

I hope these questions help you prepare for your Java interview. Good luck!

Comments

Popular posts from this blog

GTM for SFCC

Javascript check if key exists in map