Java Interview Questions

Java is a high-level programming language used to build various apps by developers for laptops, game consoles, mobile phones, and other devices. In other words, it is a strongly-typed, general purpose, and object-oriented coding language. 

The following Java Interview Questions and Answers are compiled for you to make you familiar with the types of questions you may encounter in your interview. These questions are useful for basic to medium and advanced level interviews.

Most Frequently Asked Java Interview Questions

1. What is meant by Java programming?

Ans: Java is a high-level object-oriented coding language developed & released by Sun Microsystems in 1995. Java runs on multiple platforms like Windows, Mac OS, etc.

2. Name the platforms supported by Java Programming.

Ans: Java language supports multiple platforms like Windows, Mac OS, and the other editions of UNIX/Linux such as HP-Unix, Redhat Linux, Ubuntu, CentOS, and so on.

3. Why is Java programming Architectural Neutral?

Ans: Java’s compiler produces an object file format that is architecture-neutral. It makes the arranged code to be executable on several processors including a Java runtime system.

4. How does Java enable High Performance?

Ans: The language uses a Just-In-Time (JIT) compiler which is an integral part of JVM to enable high and faster performance. JIT compiler turns Java bytecode to speed up the Java application. This is a type of program that includes certain instructions that must be converted into orders that can be sent directly to the processor.

5. What do mean by a Local Variable?

Ans: Local variables in Java are defined within the body including methods, constructors, or blocks. You can declare and initialize the variable within the same method only. And it will be removed after completion of that method.

6. Name the five top features of Java programming.

Ans: The top features of Java include Object Oriented, Robust, Portable, Platform Independent, and Multi-threaded.

7. Define why Java language is considered dynamic?

Ans: Java programming language is considered more dynamic as it is designed to adapt to an evolving environment. Java programs can move a large amount of run-time data. This data is useful to verify and work out access to objects on run-time. Further, it supports dynamic loading of various classes which are loaded on-demand basis.

8. Name the two Java IDEs.

Ans: Two popular Java IDEs are- Netbeans and Eclipse.

9. Mention a few Java keywords.

Ans: There are some useful Java keywords such as import, super, finally, for, abstract, byte, case, etc.

10: What is meant by an Instance Variable?

Ans: Instance variables are non-static variables defined inside a class but outside any method or block. Moreover, these variables are instantiated or expressed when the class is loaded.

11. Define Java Virtual Machine (JVM) and how to consider it as Java’s platform-independent feature?

Ans: When we compile a Java program, it is not compiled into the platform-specific system but rather into platform-independent byte code. This byte code is allocated over the web and converted by JVM which is a specification and a runtime instance, on whatever platform it runs actually.

12: Define what is the class?

Ans: A class in a Java program is a basic building block through which individual objects are built. Moreover, a class can include certain fields and methods that explain the object’s (variable’s) behavior.

Wish to make a career in the world of Java? Start with HKR'S  Java Training ! 

13: Mention the types of variables that a class can contain.

Ans: A class in Java can contain Local variables, instance variables, and class variables.

14: Describe what is an Object?

Ans: An object is a runtime entity and a member of the Java class. It consists of a state and behavior such as a chair, bike, etc. Moreover, the object includes three different features such as state, behavior, and identity. Further, an object can be physical or logical in nature.

15: Define a Class Variable.

Ans: These variables are declared within a class, but outside of any method using the static keyword in the Java program.

16: What is a Constructor in a Java program?

Ans: A Constructor is a block of several codes which is equal to the method. It is called when a new object or instance of a class is created. Every class in Java consists of a constructor. If we do not clearly define or write a constructor for a class the java compiler then creates a default constructor for the same class.

17: What are the three different steps useful to create an Object for a class?

Ans: The creation of an object includes- declaration, instantiation, and initialization.

18: Mention the default value of byte data type in the Java program.

Ans: The default byte datatype value in a Java program is 0 (zero).

19: Define Singleton class.

Ans: A Singleton class in Java is a design pattern that makes sure that a class should contain only a single object. It controls the number to one but allows the flexibility to build more objects if the condition alters. Moreover, it is useful when a single instance of a class needs to control the actions in the entire execution.

20: Name the default values of float and double datatype.

Ans: The following are the default values of float and double data types:- for float the value is 0.0f and for double data type the value is 0.0d.

Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

21: What is the use of byte data type?

Ans: A byte data type is useful to save space in large arrays. This is mainly used in the place of integers. But a byte is 4 times smaller than an integer in reality.

22: Define the Static variable.

Ans: The static variables have another name: Class variables that are declared with the static keyword in a class but outside of a method, or a block.

23: What is an Access Modifier in Java?

Ans: Access modifiers are useful to set access levels for classes, methods, variables, and constructors. Further, these modifiers mention the accessibility or scope of a method or a field.

24: How do you define a Protected Access Modifier?

Ans: The protected modifiers’ access level is within and outside the package through the child class in Java. In case, if you don’t build the child class, you can access it from outside the package.

25: Why is a String class in Java considered immutable?

Ans: The String class in Java is immutable or cannot be altered as once you create a String object it cannot be changed. Also, you can easily share this between many threads, and is viewed as important for multithreaded programming.

26: What is the reason that a StringBuffer is called mutable?

Ans: The String class is viewed as immutable as once created, it cannot be altered. If there is a need to make a lot of changes to Strings of characters then StringBuffer is highly useful.

27: Define Exception.

Ans: An exception is a problem or error that occurs at the time of execution of a program. These errors/exceptions are grabbed by handlers located along the thread's method citation stack.

28: Explain Inheritance in Java.

Ans: Inheritance is a type of process where one object obtains another object’s properties. By using inheritance, the data is made viable in a hierarchical order.

29: What is meant by Abstraction?

Ans: The term refers to the capability to make a class abstract in object-oriented programming. It minimizes the complexity and helps to improve the system’s maintainability.

30: Define Encapsulation.

Ans: It is the technique to integrate code and data into a single unit. Here, we can build a completely encapsulated Java class by ensuring all the data members of the class are private. Java Bean is an example of this type of Java class.

31: What is a Local variable and the instance variable?

Ans: A local variable is a variable that can be defined inside a method and the scope of that variable is accessible only to its method but not outside the method. An instance variable is a variable which is defined inside a class and outside a method and the scope of that variable is accessible all throughout the class.

32: Why pointers not used in Java?

Ans: Pointers increases the complexity of a program and becomes unsafe. Hence the java code is designed with simplicity by avoiding the pointers that will become contradicting. JVM is responsible for implicit memory allocation, thus in order to avoid direct access to memory by the user,  pointers are discouraged in Java.

33: Explain the features in Java.

Ans: The features are.

1. The concepts of OOPs that include

  • Object-oriented
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction

2. Platform Independent - A single program runs on different platforms without any modifications.

3. High Performance - JIT (Just in Time compiler) enables high performance which converts the bytecode into machine language and then JVM starts the execution.

4. Multi-threading - Thread is a flow of execution. JVM creates a thread that is called the main thread. A user can able to create multiple threads by extending the thread class or by implementing the Runnable interface.

34: What are the main concepts of OOPs in Java?

Ans: The concepts of OOPs are:

Inheritance: It is a process by which one class acquires the properties of another class.

Encapsulation: It is a mechanism of wrapping the code and data as a single unit.

Abstraction: It is a methodology for hiding the implementation details and proving only the functionality to the users. 

Polymorphism: It is the ability of a variable, function or object to take multiple forms.

35: Explain the difference between Public and Private access specifiers.

Ans: Members are the methods and instance variables.

Public: These members are visible in the same package as well as in the outside packages of other packages.

Public

Here the public members in Class A are visible to Class B of the same package 1 as well as Class C of a different package 2.

Private: These members are visible only in the same class but not in the other classes of the same package or classes in the outside packages.

Private

Here the private members in class A are visible only in that class. It is invisible for class B of same package 1 as well as class C of different package 2.

36. Explain the difference between Default and Protected access specifiers.

Ans: 

Default: The default specifiers are those in which the methods and variables are declared in a class without any access specifiers.

Default

Default members in Class A are visible to the other classes which are inside the same package 1 and it is invisible to the classes which are outside the package 2. The members in Class A are visible to the Class B and invisible to the Class C.

Protected: The protected specifier is the same as a default specifier but when a class is extended than it is also visible even in a class which is outside the package.

Protected

Here the members in class A are visible in Class B of the same Package 1. For Class C of different Package 2, these members are invisible but if Class C extends Class A than these members becomes visible in Class C even outside the package 2.

Related Article: Python VS JAVA

37: What is the difference between the break and continue?

Ans: 

Break:

  • It can be used in switch and loop statements such as for, while, do-while.
  • The moment the break is executed it will terminate the switch or loop statements.
  • It immediately terminates the innermost enclosing loop or switch statements.

Example:

for (int i = 0; i < 10; i++)

{

if (i == 5)

{

break;

}

System.out.println(i);

}

Continue: 

  • It can be used only in loops statements.
  • It will not terminate the loop but it causes the loop to jump to the next iteration.
  • A continue within a loop nested with a switch will cause the next loop iteration to execute

Example:

for (int i = 0; i < 10; i++)

{

if(i == 5)

{

continue;

}

System.out.println(i);

}

38: What is the final keyword in Java?

Ans: The final keyword is used as a non-access modifier. A final variable is used in different contexts of a class, method and a variable.

  • Final variable: Once if any variable is assigned with a final keyword than that value of that variable cannot be modified and remains unchanging. If in case the final variable is assigned without any value than by using only the class constructor a value can be assigned to it.
  • Final method: When the method is declared as final then it cannot be overridden by the inheriting class.
  • Final class: When a class is declared as a final then it cannot be extended by any sub-class but it can able to extend the other class.

39: What is Constructor?

Ans: 

  • A constructor is a method which has the same name as that of a class.
  • When a new object is created in a class than the constructor is invoked by that corresponding class.
  • If a user doesn’t create a constructor implicitly than a default constructor is created.
  • A constructor can be overloaded.
  • If a user creates a parameterized constructor than that user should create another constructor without any parameters explicitly.

40: What is the difference between methods and constructors in Java?

Ans: 

Methods:

  • Methods are used to represent the behaviour of an object.
  • Should have the return type.
  • Methods must be invoked explicitly.
  • The compiler doesn’t provide any default method.
  • Method name may be or may not be the same as a class name.

Constructors:

  • Constructors are used in initializing the state of an object.
  • The constructor method will not have any return type.
  • The methods are invoked implicitly.
  • The compiler provides a default constructor when a class doesn’t contain any.
  • The method name of a constructor will be the same as a class name.

41: What is the difference between Abstract class and Interface?

Ans: 

Abstract class:

  • Abstract classes have a default constructor that is called when a concrete subclass is instantiated.
  • Contains both Abstract and Non-abstract methods.
  • A class that extends the abstract class doesn’t need the implementation of all methods, only abstract methods are implemented in the concrete sub-class.
  • Abstract class contains instance variables.

Interface: 

  • The interfaces have no constructors and couldn’t be instantiated.
  • Only the abstract methods alone must be declared.
  • The classes which implement the interface should provide the implementation for all methods.
  • Interfaces contain only constants.

42: Can you override a private or static method in java?

Ans: No. You cannot override private or static methods. If a similar method is created with the same return type and the same method arguments in child class then it hides the superclass method which is also called as method hiding. Similarly, the private method is not overridable in sub-class which is not accessible there. You can create another private method with the same name in the child class as in this example.

Example:

class Base_class {

private static void display() {

System.out.println("Static or class method from Base class");

}

public void print() {

System.out.println("Non-static or instance method from Base class");

}

class Derived_class extends Base_class {

private static void display() {

System.out.println("Static or class method from Derived class");

}

public void print() {

System.out.println("Non-static or instance method from Derived class");

}

public class test {

public static void main(String args[])

{

Base obj= new Derived_class();

obj.display();

obj.print();

}

}

43: What is the difference between Error and Exception?

Ans: An error is an unrecoverable condition that occurs at runtime such as “OutofMemory” error.  These JVM errors cannot be repaired at runtime. Even though such kind of errors is caught in the catch block, the application execution will be halted and becomes unrecoverable. 

The exceptions are the conditions which applied for tracking the bad input to human error while executing a program. For example “FileNotFoundException” is an exception which is thrown to handle if the specified file doesn’t exist. 

44: What is the difference between Serialization and Deserialization in Java?

Ans:

Serialization:

  • The Serialization is a process of converting the objects into a byte stream.
  • An object is serialized by writing it an ObjectOutputStream.

Deserialization:

  • The Deserialization is an exact opposite of what a Serialization will process where we can get the objects back from the byte stream.
  • An object is deserialized by reading it from an ObjectInputStream.

45: When to use Runnable interface and Thread class in Java?

Ans: When a class is needed for extending some other classes other than a thread then it is recommended to implement the runnable interface because java can extend only one class. If there is no need for extending any class than at the time it is recommended to extend the properties of a thread class.

Subscribe to our youtube channel to get new updates..!

46: Explain the difference between HashMap and HashTable.

Ans: 

HashMap:

  • The methods in HashMap are not synchronized.
  • HashMap will not have thread-safety.
  • The iterator will be used for iterating the values.
  • Allows one null key and multiple null values.
  • Performs high compare to the HashTable.

HashTable:

  • The key methods in HashTable are synchronized.
  • HashTable will have thread-safety.
  • The enumerator will be used for iterating the values.
  • Doesn’t allow anything which is null.
  • Performs low compare to the HashMap.

47: What is the difference between HashSet and Treeset?

Ans: 

HashSet:

  • The elements which are inserted into HashSet will be in random order.
  • HashSet can store null objects.
  • Performance is fast.

TreeSet:

  • The elements in a TreeSet will be maintained in sorted order.
  • TreeSet cannot store null objects.
  • Performance is slow.

48: What are Collections in java?

Ans: Collections are the framework which is designed to store and manipulate the objects. The collections perform the following operations.

  • Searching
  • Sorting
  • Insertion
    Deletion
  • Manipulation.

A group of objects are known as collections. All the collection classes and interfaces are available in the util package.

49: What is the difference between Ordered and Sorted in collections?

Ans: Ordered collections are values which are stored in a collection that is based on the values that are added to the collection. These values can be iterated from the collection in a specific order.

The sorted collection mechanism is applied internally or externally such that the group of objects sorted in a particular collection is based on the properties of objects.

50: What is the difference between Array list and Vector in Java?

Ans: 

ArrayList:

  • An Array List is not synchronized.
  • It performs fast as it’s non-synchronised.
  • The size of an array increases by 50% when an element is inserted into an Array List.
  • Array List will not define the size of increment.
  • Array List uses Iterator only for traversing.

Vector:

  • A Vector is synchronized.
  • It performs slow as it’s thread-safe.
  • By default, vector doubles the size of an array.
  • Vector will define the size of increment.
  • Vector uses both Enumerator and Iterator for traversing.

51: What is the difference between Array and ArrayList?

Ans: 

Array:

  • Arrays will not contain the values of different data types.
  • Size of an Array is defined during declaration.
  • To add data index is specified in Arrays.
  • Arrays are not parameterized type.
  • Arrays contain primitive data types as well as objects.

ArrayList:

  • ArrayList contains the values of different data types.
  • Size of ArrayList changes dynamically.
  • There is no need for specifying indexes in ArrayList.
  • ArrayLists are parameterized type. 
  • Primitive data types are not allowed in ArrayList but contain only objects.

52: What is the difference between Get and Post methods in Servlet?

Ans:

Get method:

  • Limited amount of data can be sent because the data is sent in the header section.
  • The data is exposed to a URL bar and so it is not secured.
  • It can be bookmarked.
  • It is Idempotent.
  • It is used more efficiently than a Post method.

Post method:

  • A large amount of data can be sent because the data is sent in the body section.
  • The data is secured since it is not exposed to a URL bar. 
  • It cannot be bookmarked.
  • It is not Idempotent.
  • It is used with less efficiency. 

53: What are the different methods of session management in Servlets?

Ans: Session is a state of a conversation between client and server and consists of multiple requests and responses. As HTTP and Web Server are stateless, the session maintains the unique information as session-id that is passed between client and server in every request and response. The methods of session management in servlets are:

  1. User Authentication
  2. HTML Hidden Field
  3. Cookies
  4. URL Rewriting
  5. Session Management API

54: What is a JDBC Driver?

Ans: JDBC is a software component which enables the application to interact with the database. There are mainly four types of JDBC drivers.

  1. JDBC-ODBC bridge driver
  2. Native-API driver (partially java driver)
  3. Network Protocol driver (fully java driver)
  4. Thin driver (fully java driver)

55: What are the JDBC statements?

Ans: These are the statements which are used to send SQL commands to the database and also retrieve the data from the database. The methods like execute(), executeUpdate() and executeQuery() are provided by JDBC to interact with the database.

JDBC supports three types of statements.

  1. Statement: It is a general statement which is used to access the database and execute static SQL query at runtime.
  2. PreparedStatement: It is used in providing the input parameters to the query during the execution.
  3. CallableStatement: It is used for accessing the database stored procedures and helps in accepting runtime parameters.

56: What are the lifecycle methods for a JSP?

Ans: There are three lifecycle methods in JSP.

  • public void jspInit() - It is invoked only once which is same as that of init() method used in servlet.
  • public void _jspService(ServletRequest request, ServletResponse response) throws ServletException, IOException - It is invoked at each request which is same as that of service() method used in servlet.
  • public void jspDestroy() - It is invoked only once which is same as that of destroy() method used in servlet.

57. How is JSP better than a Servlet Technology?

Ans: JSP is a technology of the server’s side programming with simple content generation. JSP’s are document-centric while Servlets are programs. A JSP page contains the fragments of java programming code which executes and instantiates Java classes. However, they occur inside an HTML template file. It provides the framework for the development of a Web Application.

58. What is Synchronization?

Ans: Synchronization is about handling only one thread for accessing a block of code at a time. While multiple threads access the block of code then there are chances for inaccurate results, in the end, to avoid this the synchronization is provided for the sensitive block of code. The keyword “synchronized” means that a thread requires a key to access the synchronized code.

It locks as per object. Each Java object has a lock which has only one key. A thread can access a synchronized method only if the thread can get a key to the objects to lock. Towards this, the “Synchronization” keyword will be used.

Example:

public class ExampleThread implements Runnable{

 public static void main (String[] args){

 Thread t = new Thread ();

 t.start ();

 }

 public void run(){

 synchronized(object){

 {

 }

}

59. Name the different modules of Spring framework.

Ans: The modules of spring framework include.

  • Spring Context – for dependency injection.
  • Spring Web Module – for creating web applications.
  • Spring AOP – for aspect-oriented programming.
  • Spring ORM – for ORM tools support such as Hibernate
  • Spring DAO – for database operations using DAO pattern
  • Spring JDBC – for JDBC and DataSource support.
  • Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.

60. Explain the role of DispatcherServlet and ContextLoaderListner.

Ans: Dispatcher Servlet is a front controller in Spring MVC application which loads the spring bean configuration file and initializes all beans which are configured. By enabling the annotations it allows scanning the packages to configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.

ContextLoaderListner is a listener that can start and shut the “WebApplicationContext” in spring root. Its main function ties the lifecycle of Application Context to the lifecycle of the ServletContext and automating the creation of ApplicationContext.

Java Certification Training

Weekday / Weekend Batches

Find our upcoming Java Certification Training Online Classes

  • Batch starts on 9th Dec 2022, Fast Track batch

  • Batch starts on 13th Dec 2022, Weekday batch

  • Batch starts on 17th Dec 2022, Weekend batch

 
Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.