Top 50 Java Interview Questions For Beginners & Experienced

Top 50 Java Interview Questions For Beginners & Experienced

Are you looking for Java interview questions? This article will help you become a Java wizard. Read more to get the complete list of Java questions.

Have you ever tried your hand at Java? Do you think you have the skills to be a Java guru? In this article, I will help you with leveraging your Java knowledge and share the most common Java interview questions for freshers and experienced candidates.

The importance of Java in the programming world is well known. Learn Java to develop several applications such as enterprise applications, network applications, desktop applications, web applications, games, android app, and more with the best Java tutorials for beginners in 2021.

Best Java Interview Questions & Answers

This list of Java Interview Questions intends to give you an idea of what type of questions you may encounter in an interview related to Java Programming Language. Generally, a good interviewer will rarely ask any particular question during the interview. Usually, questions begin with a basic concept of the subject and then continue based on further discussion.

1. What is Java?

Answer: Java is an object-oriented, robust, secure, platform-independent, multithreaded, multiprocessing, high-performance programming language. James Gosling developed it in June 1991. Since it provides its own JRE and API, it is also referred to as the platform.

2. Why is Java a platform-independent language?

Answer: Java was designed so that Java does not require any hardware or software since the compiler compiles the code and then converts it to platform-independent byte code, which can run on multiple systems.

The only requirement to run that byte code is that the machine has a Java runtime environment (JRE).

3. What are the supported platforms by Java Programming Language?

Answer: Java is compatible with many platforms, such as Windows, Mac OS, and several UNIX/Linux operating systems like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.

4. Why is Java not a pure object-oriented language?

Answer: Java supports primitive data types - byte, boolean, char, short, int, float, long, and double; thus, it cannot be considered an object-oriented programming language.

5. What do you understand by Java virtual machine?

Answer: Java Virtual Machine allows the computer to run Java programs. In Java code, it acts like a runtime engine that calls the main method. It is the specification that has to be implemented in the computer system. JVM compiles Java code into Bytecode, which is machine-independent and close to native code.

6. Explain JDK, JRE, and JVM?

Answer:

  1. JDK: It stands for Java Development Kit. This tool is required to compile, document, and package Java programs. Additionally, it includes JRE + and development tools.

  2. JRE: It is short for Java Runtime Environment. JRE is a runtime environment in which Java bytecode can be executed. Physically, it is an implementation of the JVM.

  3. JVM: It stands for Java Virtual Machine. It is an abstract machine. It is a specification that allows Java bytecode to be executed in a runtime environment. JVM uses three notations: Specification, Implementation, and Runtime Instance.

7. What are wrapper classes in Java?

Answer: Wrapper classes convert the Java primitives into reference types (objects). For every primitive data type, there is a class. Hence, these classes are often referred to as wrapper classes since they wrap the primitive type into a class object.

8. Pointers are used in C/ C++. Why does Java not make use of pointers?

Answer: Beginner programmers should avoid using pointers because they are quite complicated and risky. The use of pointers in Java makes it challenging because it focuses on code simplicity. Pointer usage can also lead to errors. Furthermore, pointers compromise security as users can directly access memory when using them.

As a result, Java grants a certain level of abstraction by not including pointers. Furthermore, garbage collection can be slowed down and erroneous by using pointers. Java relies on references as they cannot be manipulated, unlike pointers.

9. What do you understand by an instance variable and a local variable?

Answer: Variables that are accessible by every method in a class are called instance variables. The variables are declared outside the methods and inside the class. Variables used to describe objects' properties remain bound to them regardless of cost.

Every object in the class will have a copy of the variables for utilization. Modifications made to these variables will only affect the modified instance, and all other class instances will remain unaffected.

Local variables reside within a block, function, or constructor and can be accessed only within them. Using the variable is restricted to the block scope. When a local variable is declared inside a method, the other class methods do not know the local variable.

10. Can you tell the difference between equals() method and equality operator (==) in Java?

Answer:

equals()==
This method is defined in the Object class.A binary operator in Java.
According to the specified business logic, this method is used to check for the equality of contents between two objects.Comparing addresses (or references) is what this operator does, i.e. checking whether both objects point to the same memory location.

Please note:

  • When the equals method is not overridden in a class, the class uses the default implementation of the equals method closest to the parent class.
  • Object class serves as the parent class of all the java classes. In the Object class, the equals method uses the == operator to compare two objects. Default implementations can be overridden according to business logic.

11. What is JIT compiler?

Answer: Just-In-Time(JIT) compiler is used to improve performance. By compiling parts of the bytecode with similar functionality together, JIT reduces the amount of time needed for compilation. In this context, “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

12. What are the main differences between the Java platform and other platforms?

Answer: The Java platform differs from other platforms in the following ways.

  • Java is a software platform, whereas other platforms might be hardware platforms or software platforms.
  • Java runs over other hardware platforms, while other platforms have nothing but hardware components.

13. Can the static methods be overloaded?

Answer: Definitely! It is possible for a class to contain multiple static methods of the same name but with different input parameters.

14. Is delete, next, main, exit, or null keyword in java?

Answer: No

15. Can the static methods be overridden?

Answer:

  • No. Although static methods with the same signature can be declared in a subclass, runtime polymorphism is impossible.
  • While overriding and dynamic polymorphism occurs at runtime, static methods are loaded and looked up statically at compile time. Therefore, these methods cannot be overridden.

16. What part of memory - Stack or Heap - is cleaned in the garbage collection process?

Answer: Heap

17. When can you use the super keyword?

Answer: With the super keyword, you can access hidden fields and overridden methods or attributes of the parent class. The following are the possible uses of this keyword:

  • To access the parent class methods after the child classes have overridden them.
  • To access data members of parent class when the member names of the class and its child subclasses are same.
  • Within the child class, call the default and parameterized constructor of the parent class.

18. How would you differentiate between a String, StringBuffer, and a StringBuilder?

Answer:

  • Storage area: String pools serve as storage areas in String. StringBuilder and StringBuffer store data in heap memory.
  • Mutability: Strings are immutable, whereas StringBuilder and StringBuffer are mutable.
  • Efficiency: Strings are quite slow to work with. StringBuilder, however, is the fastest. The speed of a StringBuffer is higher than that of a String and lower than a StringBuilder. (For instance, appending a character is faster in StringBuilder than in String, since the new String with the appended character requires a new memory.)
  • Thread-safe: In a threaded environment, StringBuilder and StringBuffer are used instead of a String. StringBuilder is suitable for an environment with a single thread, while StringBuffer is suitable for an environment with multiple threads.

19. If I don't provide any arguments on the command line, then what will the value stored in the String array passed into the main() method, empty or NULL?

Answer: It will be empty but not null.

20. What are the advantages of Packages in Java?

Answer: Defining packages in Java has many advantages.

  • Name clashes are avoided in packages.
  • Packages provide easy access control.
  • The related classes are easier to find.
  • The package may also contain hidden classes which are not visible outside of the package but used by

21. What is the purpose of static methods and variables?

Answer: Methods and variables defined as static are shared within all objects in the class. Static is a part of a class, not of an object. ThIn the class area, static variables are stored, and we do not have to create an object to access them. Therefore, static is used when we need to define variables or methods common to all objects in the class.

As an example, for the class simulating a college, the students all share the same attribute: the name of the college. As a result, the college name will be defined as static.

22. Why is the character array preferred over string for storing confidential information?

Answer: In Java, a string is immutable, meaning it cannot be modified. If it is not removed in the form of garbage, it remains in the string pool. Essentially, a string resides in the heap section of memory for an unregulated and unspecified time after string value processing is completed.

The result is that vital information can be stolen to pursue harmful activities by hackers if a memory dump is illegally accessed. By storing variables in mutable structures like character arrays, we eliminate these risks. Immediately after the work of the character array variable is complete, you can also set it to a blank value. Additionally, it prevents hackers from accessing vital information because heap memory is conserved.

23. What are the differences between HashMap and HashTable in Java?

Answer:

HashMapHashTable
HashMap is not synchronized, so it is better suited for non-threaded applications.Since HashTables are synchronized, they are suitable for threaded applications.
It allows just one null key but any number of null in the values.It does not allow null for either keys or values.
It supports order of insertion by using its subclass LinkedHashMap.HashTables do not guarantee the order of insertion.

24. Does Java work as a “pass by value” or “pass by reference” phenomenon?

Answer: Java is always a "pass by value" language. Java doesn't have anything called "pass by reference". Nonetheless, when the object is passed in any method, the address of the value is passed due to the way Java handles objects. When an object is passed to a method, Java creates a copy of the reference and passes it to the method. In both cases, the memory location is the same. Within the method, there are two possible outcomes:

Case 1: When the object is pointed to another location: As the reference points to another location, any changes made to the object before it was passed to the method are not reflected in the original object.

Case 2: When object references are not modified: As the copy of the main object points to the same memory location, any changes made to the content of the original object will be reflected in the copy.

25. What are constructors in Java?

Answer: A constructor in Java is a block of code that is used to initialize an object. Its name must be the same as that of the class. Additionally, it has no return type and is automatically invoked when an object is created. Constructors come in two types:

1. Default Constructor: A default constructor does not accept any inputs. In other words, default constructors do not require an argument and are created automatically if no other constructor is defined. Its primary purpose is to set the default values for the instance variables. Additionally, it is mainly used to create objects.

2. Parameterized Constructor: In Java, the parameterized constructor is the constructor capable of initializing instance variables with provided values. These are called parameterized constructors since they accept arguments.

26. What is a singleton class in Java and how can we make a class singleton?

Answer: A singleton class is one whose instance can be created only once in a single JVM at any given time. You can make a class singleton by making its constructor private.

27. What are access modifiers in Java?

Answer: Access modifiers in Java, are special keywords used to limit the access of a class, constructor, data member, and method in another class. There are four types of access modifiers in Java:

  • Default
  • Private
  • Protected
  • Public

28. What will be the initial value of an object reference which is defined as an instance variable?

Answer: Java initializes all object references to null.

29. What is an object?

Answer: An Object is a real-time entity with some state and behavior. In Java, an object is an instance of a class, with instance variables representing its state and methods representing its behavior. Using the new keyword, an object of a class can be created.

30. What is an object in Java and how is it created?

Answer: An object is a real-world entity with a state and behaviour. There are three characteristics of an object:

  • State
  • Behavior
  • Identity

31. What are the main concepts of OOPs in Java?

Answer: OOPs, or object-oriented programming is a programming style associated with concepts such as:

  1. Inheritance: Inheritance occurs when one class acquires the properties of another.
  2. Encapsulation: Encapsulation in Java is the process of wrapping up the data and code together as a single unit.
  3. Abstraction: Abstraction is the process of hiding implementation details from the user while providing functionality only.
  4. Polymorphism: The ability of a variable, function, or object to take on multiple forms.

32. Differentiate between the constructors and methods in Java?

Answer: Here's the difference between the constructors and methods in Java:

ConstructorsMethods
It is used to initialize the state of an object.It is used to define the behaviour of an object.
There is no return typeReturn type must exist
Invoked implicitlyMust be explicitly invoked
If a class does not have a constructor, a default constructor is provided by the compiler.Compilers do not provide a default method.
It is necessary to name the constructor the same as the class name.The method name may or may not be the same as the class name.

33. What is the final keyword in Java?

Answer: Java uses the final keyword as a non-access modifier. A final variable is useful in various contexts, including:

final variable

Using the final keyword with a variable prevents its value from being changed once it has been assigned. If a value hasn't yet been assigned to the final variable, then it can only be assigned by using the class constructor.

final method

When a method is declared final, the inheriting class cannot override it.

final class

In Java, a class that is declared final cannot be extended by a subclass class, but it can extend other classes.

34. What is an infinite loop in Java? Explain with an example.

Answer: A Java infinite loop is a sequence of instructions that loops indefinitely when a functional exit is not met. The loop can result from a programming error or maybe a deliberate choice based on the application's behaviour. Once the application exits, an infinite loop will terminate automatically.

35. What is Java String Pool?

Answer: The Java String pool is a collection of Strings that are stored in heap memory. Whenever a new object is created, the String pool first checks whether the object already exists. If it is present, the same reference is returned to the variable; otherwise, a new object is created in the String pool, and the particular reference is returned.

36. Why Java Strings are immutable in nature?

Answer: String objects in Java are immutable by nature, meaning that their state cannot be changed once they have been created. If you update the value of that object rather than updating the value of that particular object, Java attempts to create a new string object. Because String objects are usually cached in String pools, Java String objects are immutable. String literals are shared across multiple clients, so actions from one client may affect the rest. It increases the security, caching, synchronization, and performance of the application.

37. What is a classloader in Java?

Answer: The Java ClassLoader is a subset of JVM (Java Virtual Machine) used to load class files. Whenever a Java program is executed, the classloader loads it first. There are three classloaders built into Java:

  • Bootstrap ClassLoader
  • Extension ClassLoader
  • System/Application ClassLoader

38. What is a Map in Java?

Answer: A map is an interface of the Util package that maps unique keys to values. The Map interface is not a subset of the main Collection interface, and as a result, it behaves a little differently from the other types of collections. The following are some of the characteristics of the Map interface:

  • Map does not have duplicate keys.
  • A key can map a maximum of one value.

39. What is a collection class in Java? List down its methods and interfaces.

Answer: The collection class is a framework in Java that acts as an architecture for storing and manipulating a group of objects. You can perform various tasks with Collections, such as searching, sorting, insertion, manipulation, and deletion. Collection frameworks in Java include:

  • Classes
  • Interfaces
  • Methods

40. What is Polymorphism?

Answer: In simple terms, polymorphism is "one interface, many implementations". An example of polymorphism is the ability to assign a different meaning or use to something in different contexts specifically; when an entity, such as a variable, function, or object, has more than one form. Polymorphism comes in two forms:

  • Compile-time polymorphism
  • Run time polymorphism

A compile-time polymorphism uses method overloading, while a run-time polymorphism uses inheritance and interfaces.

41. What is inheritance in Java?

Answer: The concept of inheritance in Java refers to the inheritance of properties from one class to another. You can reuse the code and establish relationships between different classes using it. Inheritance occurs between two types of classes:

  • Parent Class (Super or Base class)
  • Child Class (Subclass or Derived class)

The term Child Class refers to a class that inherits properties, whereas Parent Class refers to a class whose properties are inherited.

42. What are the different types of inheritance in Java?

Answer: There are four types of inheritance in Java:

  1. Single Inheritance: A class inherits the properties of another class, so there is only one parent and one child class.
  2. Multilevel Inheritance: When a class is derived from a class that is also derived from another class, or when a class has more than one parent class but at different levels, such inheritance is multilevel inheritance.
  3. Hierarchical Inheritance: When a class has more than one child class (subclass) or in other words, more than one child class has the same parent class, it is called hierarchical inheritance.
  4. Hybrid Inheritance: It occurs when two or more types of inheritance are combined.

43. What are the steps to connect to a database in Java?

Answer: The following are the steps to connect to a database in Java:

  • Registering the driver class
  • Creating a connection
  • Creating a statement
  • Executing queries
  • Closing connection

44. What is JDBC Driver?

Answer: Java applications can interact with databases via the JDBC Driver software component. JDBC drivers fall into four categories:

  • JDBC-ODBC bridge driver
  • Network Protocol driver (fully java driver)
  • Native-API driver (partially java driver)
  • Thin driver (fully java driver)

45. What is a copy constructor in Java?

Answer: A copy constructor is a member function used to initialize an object with another object of the same class. However, Java doesn't need a copy constructor because all objects are passed by reference. Additionally, Java does not even support automatic pass-by-value.

46. What is encapsulation in Java?

Answer: Encapsulation refers to the mechanism by which you bind your data (variables) and code (methods) together as a single entity. In this case, the data is hidden from the outer world and can only be accessed through current class methods. As a result, the data is protected from being modified unnecessarily. Encapsulation in Java can be achieved by:

Declaring the class variables as private. Providing public setter and getter methods for modifying and viewing the values of the variables.

47. What do you mean by aggregation?

Answer: In aggregation, all objects have the same lifecycle, but there is ownership and the child objects can't be members of other parent objects. Here is an example of a department and a teacher. A teacher can't belong to more than one department, but if we delete the department, the teacher's object will not be destroyed.

48. What is an association?

Answer: An association is a relationship where all objects have a lifecycle and there is no owner. Let's consider the example of a Teacher and a Student. Each student can be associated with multiple teachers, and each teacher can be associated with multiple students, but there is no ownership between the objects, and both have their lifecycles. It is possible to have relationships that are many to one, many to one, and many to many.

49. What is a composition in Java?

Answer: It is possible to think of composition as a specialized form of Aggregation. We can call this a death relationship. In other words, it is a strong type of Aggregation. The child object does not have its lifecycle, and if a parent object gets deleted, all the child objects get deleted also. Again, let us take the example of a house and its rooms. There is no independent life of a room in a house. No room can belong to two different houses. If we delete the house, the room will also be deleted.

50. What are method overloading and method overriding?

Answer:

Method Overloading:

  • It is a compile-time polymorphism.
  • Each method must have a distinct signature.
  • In Method Overloading, inheritance may or may not be necessary.
  • In method overloading, you "add" or "expand" more to the method's behaviour.
  • Under method overloading, methods of the same class share the same name, but each method has a different number of parameters or parameters of different types and orders.

Method Overriding:

  • It is a run-time polymorphism.
  • Each method must have the same signature.
  • Inheritance is always required in Method Overriding.
  • The purpose of method overriding is to change the existing behaviour of the method.
  • In Method Overriding, the subclass has the same method with the same name and number and type of parameters and the same return type as a superclass.

If you have made it this far, then certainly you are willing to learn more about Java. Here are some more resources related to Java that we think will be useful to you.

Did you find this article valuable?

Support Yash Tiwari by becoming a sponsor. Any amount is appreciated!