University

30 JAVA INTERVIEW QUESTIONS

Cogent Infotech
Blog
Location icon
Dallas, TX

30 JAVA INTERVIEW QUESTIONS

We've compiled a collection of Java Interview Questions which includes object-oriented programming, Java's general functionality, collections in Java, garbage collectors, exception handling, Swing, OOPs, String Handling, and Multithreading, with a complete explanation of all important Java concepts with examples.

1. Java - what is it? What are its features?

Java is a concurrent, class-based, and object-oriented high-level programing language credited to James Gosling in 1982. Object-oriented programming principles are at the core of its design and can be used to develop large-scale applications. It has the following features:

Object-Oriented Concepts

  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Platform independent
  • High Performance
  • Multithreaded
  • Portable
  • Secure

2. What are the concepts of OOP? 

Object Oriented Programming (OOP) includes

  • Class 
  • Object 
  • Method and Method passing
  • Pillars of OOP
  • Interface
  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance

3. Is Java a pure OOP? 

No. Java does not satisfy all the OOP conditions (predefined types must be objects) because it supports older data types as well - byte, boolean, char, short, int, float, long, and double, which are not objects. 

4. What are wrapper classes? 

Java primitives are converted into objects by a wrapper class. Wrapper classes wrap data types from the eight primitive types encapsulating or hiding them. In simple words, wrapper classes enable using primitive data types as objects. Java API contains primitive wrapper classes.

5. How is Java and C++ different?

  • Java is both a compiled and an interpreted language, while C++ is a compiled language. The central processing unit executes C++ directly after it is compiled into machine code. Meanwhile, the Java virtual machine (JVM) interprets the Java bytecode at runtime after it is compiled into bytecode. 
  • They are machine-independent, whereas C++ programs can only run on the machine on which they are compiled. 
  • The C++ language permits pointers in programs, while Java does not. On the internal level, Java uses pointers.
  • We can use multiple inheritances in C++, which isn't possible in Java. When one class inherits properties from more than one class, it is called multiple inheritances. It is also known as the diamond problem. As a result of allowing multiple inheritances, a complexity called ambiguity may arise. This is a serious problem. Thus, Java doesn't support multiple inheritances.  

6. Does Java use pointers? 

The general-purpose OOP programming in Java does not require pointers. One should avoid using pointers due to their complexity, safety concerns, the complication of Java's focus on reducing complexity, and errors encountered.

Unlike pointers, object references are used in Java because we cannot manipulate them. The absence of pointers in Java enables partial abstraction. Moreover, pointers can result in long and inefficient garbage collection and are vulnerable to security threats because they allow direct memory access. 

7. Java is called the Platform Independent Programming Language- why?

Programmers do not have to rewrite or recompile Java codes for each platform because the language was designed such that there would be no need to rewrite, recompile, or rewrite applications. The Java virtual machine makes this possible since it recognizes the underlying hardware platform's specifics, such as instruction lengths.

Therefore, the Java language cannot be affected by hardware or software. The code is compiled and converted into a platform-independent byte code that can run on several platforms. A runtime environment (JRE) must be installed on the machine for running that byte code.

8.What is Encapsulation? 

Encapsulation is a process by which data is wrapped into a single unit. It provides the link between the code and the data it manipulates. Encapsulation can also be viewed as a protective shield that prevents the code from being able to access the data outside the shield.

By making the members or methods of a class private, a class can hide its data from other classes, a concept similar to encapsulation. Applying the abstraction concept exposes the class to the end-user or world without providing details of its implementation. Therefore, it is a combination of data hiding and abstraction.

Several methods available to other objects can change the internal data of each object. It is possible to modify access to a Java object with three modifiers: public, private, or protected. Modifiers impose different access rights on other classes, either within or outside of the same package. 

Encapsulation has several benefits, including:

  • Hidden attributes protect an object's internal state.
  • The ability to independently modify or extend an object's behavior increases code usability and maintainability.
  • By preventing unwanted interactions between objects, it improves modularity.

9. What are the differences between Abstraction and Encapsulation?

The concepts of abstraction and encapsulation are complementary. Aspects of an object's behavior are the focus of abstraction. Encapsulation, however, focuses on implementing an object's behavior, which is usually based on hiding information about a given object's internal state so that it can provide the abstraction of that object's state.

10. What is Polymorphism? 

Among programming languages, polymorphism is the ability to present the same user interface regardless of the underlying data type. In other words, it's the ability to perform a single action in multiple ways. 

Polymorphism occurs when inheritance Inheritance is one of the most powerful features of Java. One class can inherit properties and attributes from another with Java inheritance. These inherited properties can be used in various ways through polymorphism in Java. 

Polymorphic types can apply their operations to a wide variety of values. Java supports two types of polymorphism:

  1. Runtime polymorphism (Dynamic binding) “ Method overriding
  2. Compile-time polymorphism (Static binding) “ Method overloading

11.What is Inheritance? 

Inheritance is a mechanism by which a new class is derived from an existing class. The new class inherits the properties from another class and can add new features to itself. Unlike a superclass, a subclass is derived from a superclass, which, in turn, is derived from a class.

Java inheritance allows you to create new classes based on existing classes. A parent class's methods and fields can be reused when inheriting from it. Aside from that, you can add new methods and fields to your existing class.

A parent-child relationship is an inheritance, also known as the IS-A relationship. In addition, HAS-A has a composition relationship. Unlike inheritance, which is a static binding (compile time), it is a dynamic binding (run time). It implies that occurrences of one class are related to occurrences of another class or a similar class. 

12.What are the reasons behind Java's immutable strings, aside from security? 

A String is made immutable due to the following reasons:

Collections

Keys in Hashtables and HashMaps are String objects. If String objects are not immutable, they can be modified when stored in HashMaps. Therefore, it is not possible to retrieve the desired data. It is risky to deal with such fluctuations in data. As a result, making the string immutable is relatively safe.

Multithreading

String objects have a crucial role to play when it comes to thread safety in Java. Immutable String objects do not require external synchronization. It is, therefore, possible to write cleaner code for sharing String objects across threads. Through this method, concurrency is made easier.

String Pool

The designers of Java were aware that programmers and developers would heavily use String data types. Thus, optimization was a priority from the get-go. They came up with the concept of storing String literals in a String pool (a Java heap area). By sharing, they intended to decrease the temporary String object. It is necessary to have an immutable class to facilitate sharing. No mutable structure can be shared between two unknown parties. Thus, Java Strings are immutable and help implement String Pool concepts.

13. How to declare an infinite loop in Java?

An infinite loop runs without any break conditions and cannot be broken. A condition that evaluates to true always results in an infinite loop. You can declare an infinite loop consciously by doing the following:

Using For Loop

for (;;)

{

   // Business logic

   // Any break logic

}

Using do-while loop

do{

   // Business logic

   // Any break logic

}while(true);

Using while loop

while(true){

   // Business logic

   // Any break logic

}

14. What is JVM? 

The Java virtual machine (JVM) is a platform-independent, abstract computing platform. It consists of 3 specifications: a document describing the implementation requirements, the software to implement those requirements, and an executing Java bytecode object and runtime environment. In other words, a Java virtual machine (JVM) enables a computer to run Java programs and programs written in other languages. Bytecodes are executed by the Java virtual machine (JVM). 

15. Does Java allow you to override private and static methods? 

Java does not allow users to override static methods because overriding is done at runtime based on dynamic binding, while static methods are bound statically at compile time. It does not apply to static methods because they are not associated with instance classes.

16.What is a Comparator in Java? 

As part of the Comparator interface, Java provides two methods, compare and equals. Two input arguments are compared in the first method, and order is imposed between them. To indicate whether the first argument is less than, equal to, or greater than the second, it returns a negative integer, zero, or a positive integer. 

We use the second method to determine whether an input object is equal to its comparator by passing it a parameter. If the specified object is a comparator and imposes the same ordering as the comparator, then this method returns true. 

For instance, the Method of Collections class sorts List elements based on a comparator.  

Syntax: public void sort(List list, ComparatorClass c)

Read more about it here.

17. What is Constructor Overloading? 

In Java, constructor overloading is similar to method overloading. The constructors of a single class can be created differently. However, parameter lists must be unique for each constructor.

Overloading constructors can solve these problems in different ways of initializing an object. The following is an improved version of class Box with constructor overloading by Geeksforgeeks.


// Java program to illustrate

// Constructor Overloading

class Box

{

 double width, height, depth;


 // constructor used when all dimensions

 // specified

 Box(double w, double h, double d)

 {

  width = w;

  height = h;

  depth = d;

 }


 // constructor used when no dimensions

 // specified

 Box()

 {

  width = height = depth = 0;

 }


 // constructor used when a cube is created

 Box(double len)

 {

  width = height = depth = len;

 }


 // compute and return volume

 double volume()

 {

  return width  height  depth;

 }

}


// Driver code

public class Test

{

 public static void main(String args[])

 {

  // create boxes using the various

  // constructors

  Box mybox1 = new Box(10, 20, 15);

  Box mybox2 = new Box();

  Box mycube = new Box(7);


  double vol;


  // get volume of first box

  vol = mybox1.volume();

  System.out.println(" Volume of mybox1 is " + vol);


  // get volume of second box

  vol = mybox2.volume();

  System.out.println(" Volume of mybox2 is " + vol);


  // get volume of cube

  vol = mycube.volume();

  System.out.println(" Volume of mycube is " + vol);

 }

}


Output:

Volume of mybox1 is 3000.0

Volume of mybox2 is 0.0

Volume of mycube is 343.0


18. What is Copy-Constructor?

Java supports copy constructors, but unlike C++, it doesn't create a default copy constructor unless you write it yourself. Look at the example from Geekforgeeks:

// Java Program to Illustrate Copy Constructor


// Class 1

class Complex {

//class data members

private double re, im;

// Constructor 1

// Parameterized constructor

public Complex(double re, double im)

{

// this keyword refers to current instance itself

this.re = re;

this.im = im;

}


// Constructor 2

// Copy constructor

Complex(Complex c)

{

System.out.println("Copy constructor called");

re = c.re;

im = c.im;

}


// Overriding the toString() of Object class

@Override public String toString()


{

return "(" + re + " + " + im + "i)";

}

}


// Class 2

// Main class

public class Main {

// Main driver method

public static void main(String[] args)

{

// Creating object of the above class

Complex c1 = new Complex(10, 15);

// Following involves a copy constructor call

Complex c2 = new Complex(c1);


// Note: The following doesn't involve a copy

// constructor call

// as non-primitive variables are just references.

Complex c3 = c2;


// toString() of c2 is called here

System.out.println(c2);

}

}


Output:

Copy constructor called

(10.0 + 15.0i)

 

19. What is the difference between an Interface and an Abstract class? 

Abstract classes and interfaces can both be created in Java. Although both implementations share specific characteristics, the following features differentiate them:

  • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
  • A class can implement multiple interfaces, but an abstract class can be extended by only one other class.
  • To implement an interface, a class must implement all its declared methods. The class, however, may not implement all the methods declared in the abstract class. Despite this, the sub-class must also be abstract in this case.
  • Java interface variables are, by default, final. Non-final variables can be contained in abstract classes. Java interfaces have public members by default. Members can be private, protected, or public in an abstract class.
  • Interfaces cannot be instantiated because they are abstract. An abstract class cannot be instantiated but can be invoked if it contains the main method.

20.What are Local Variable and Instance Variable? 

A local variable exists inside the method and is defined by the scope of the variables within the method. While the scope of instance variables exists throughout the instance of the object of that class 

21. What is the difference between processes and threads? 

An execution sequence within a process is called a thread, while a process is the execution of a program. In a process, there can be multiple threads. It is sometimes called a lightweight process to refer to threads. The difference between processes and threads is shown below:

22. How does thread synchronization occur inside a monitor? 

A JVM utilizes locks and monitors in conjunction. Monitors ensure that only one thread at a time executes synchronized code and watch over a sequence of synchronized code. Object references are assigned to each monitor. A thread cannot execute code until a lock has been obtained.

23. Is there a basic interface for Java Collections Framework? 

The Java Collections Framework provides a well-designed set of interfaces and classes for supporting operations on collections of objects. Java Collections Framework provides the following interfaces:

  • Collections
  • Set
  • List
  • Map

24. Why does Collection not extend Cloneable and Serializable interfaces? 

An element is a group of objects specified by the Collection interface. A collection can be implemented in various ways, each having its method of maintaining and ordering its elements. Duplicate keys are allowed in some collections but not in others. Cloning and serialization are semantically related, but their implications are also relevant regarding actual implementation. Therefore, collections should be cloned or serialized based on their concrete implementations.

25. What is the difference between HashMap and Hashtable? 

Following are the differences between HashMap and Hashtable:

  • Null keys and values are allowed in HashMaps but not in Hashtables.
  • Unlike HashMaps, Hashtables are synchronized. Therefore, a Hash Map is preferable in single-threaded environments, while a Hash table is more appropriate for multithreaded environments.
  • Hash Maps provide their keys to Java applications, which can iterate over them. It is, therefore, fail-safe to use a Hash Map. The keys of a Hash table, however, are enumerated.

26. What is the difference between Array and Array List?  

  • An Array List contains only objects, while an Array can contain both primitives and objects.
  • An array has a fixed size, while an array list has a variable size.
  • Add All, remove All, iterator, and other methods are available in an Array List.

27. What is Priority Queue? 

A queue interface has been implemented in the linked list class. Linked lists are useful for managing queues. Priority-in, Priority-out is the purpose of a queue. This results in either a natural or a comparative order for the elements. An element's order represents its relative importance. In other words, Priority Queues are unbounded queues based on priority heaps whose elements are sorted in the natural order. Priority Queue elements are ordered using a Comparator, which is provided during creation. 

There are no null values, no objects with natural ordering, and no objects with a comparator associated with them in a Priority Queue. As a final note, Java Priority Queue is not thread-safe, and its enqueuing and dequeuing operations take O(log(n)) time.

28. When is the finalize() called? What is the purpose of finalization? 

When a garbage collector releases an object's memory, it calls the finalize method. In most cases, it is recommended to release any resources held by the object during the finalization process.

Syntax: protected void finalize throws Throwable{}

Its purpose is to release system resources before the garbage collector runs for a specific object. The JVM only allows finalize() to be invoked once per object.

29. What is an exception?

An exception is an unexpected or unwanted event during the program's execution, i.e. when the program is running. This event disrupts the normal flow of instructions within the program. By catching and handling exceptions, the program can prevent errors. An object is created when an exception occurs within a method. It is called the exception object. An exception description contains information about the exception, such as its name and description, as well as the state of the program when the exception occurred.

30. What is the difference between Exception and Error in Java? 

Final Words

Java is a popular programming language that helps developers build robust and high-performing applications. In this article, we have shared some interview questions covering both basic and advanced concepts. Reading this article will deepen your understanding of Java programming and its core concepts. The explanations provided will enrich your knowledge of Java programming concepts.

Get ready to ace your next Java interview! To read more of such content, visit the Cogent Infotech website.

No items found.

COGENT / RESOURCES

Real-World Journeys

Learn about what we do, who our clients are, and how we create future-ready businesses.
Blog
The Future of Java
This blog talks about the future of java. Check out our blog to get details on it.
Arrow
Blog
15 Best JAVA Programming Books For Beginners
Top 15 Java books for beginners - clear your doubts!"
Arrow

Download Resource

Enter your email to download your requested file.
Thank you! Your submission has been received! Please click on the button below to download the file.
Download
Oops! Something went wrong while submitting the form. Please enter a valid email.