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.
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 Programming (OOP) includes
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.
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.
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.
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.
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:
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.
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:
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.
A String is made immutable due to the following reasons:
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.
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.
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.
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:
for (;;)
{
// Business logic
// Any break logic
}
do{
// Business logic
// Any break logic
}while(true);
while(true){
// Business logic
// Any break logic
}
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).
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.
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.
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);
}
}
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0
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);
}
}
Copy constructor called
(10.0 + 15.0i)
Abstract classes and interfaces can both be created in Java. Although both implementations share specific characteristics, the following features differentiate them:
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
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:
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.
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:
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.
Following are the differences between HashMap and Hashtable:
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.
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.
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.
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.
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.