Popular
Data Science
Technology
Finance
Management
Future Tech
Among the most commonly used programming languages in the world, Java holds a significant importance in developing software applications. Unlike other complex language methods like C++, Java is known for its simplicity and robust performance. Moreover, many businesses look for Java developers to design and manage their programs. Nevertheless, being prepared for Java interviews can be difficult though having knowledge of common questions can make a big difference.
This blog will discuss the top Java interview questions for different experience levels. We will begin with freshers’ questions and then go on to intermediate coding issues and finally advanced concepts for experts. This guide will help you to prepare thoroughly and boost your confidence for your next Java interview.
Java is a high-level class-based object-oriented programming language, specially designed to reduce the number of dependencies while program implementation. Java was developed by Sun Microsystems in 1995 and is currently owned by Oracle.
Using the Java Virtual Machine (JVM), Java applications can be easily compiled into bytecode that can run on any computer architecture. Hence, portability can be said to be one of the most important key strengths of Java.
Feature | Instance Variable | Class Variable |
Declaration | Inside a class but outside any method | Inside a class, using the static keyword |
Scope | Specific to an instance of the class | Shared among all instances of the class |
Memory Allocation | Allocated when an instance is created | Allocated once when the class is loaded |
Access | Accessed using an instance of the class | Accessed using the class name |
Object class in Java serves as the superclass for all other classes. Unless explicitly stated otherwise, every class in Java implicitly inherits from the Object class.
Constructors are special methods in Java that are used in instantiating objects which refers to creating an instance or occurrence of anything such as a class or struct., It has no return type and must have the same name as the class itself i.e., the constructor name should be the same as its class name including case letter sensitivity. There exist two types of constructors:
Access Specifier | Visibility | Class | Package | Subclass | Global |
private | Only within the same class | Yes | No | No | No |
default | (no modifier) | Within the same package | Yes | Yes | No |
protected | Within the same package and subclasses | Yes | Yes | Yes | No |
public | Anywhere | Yes | Yes | Yes | Yes |
Java is platform-independent due to the fact that it is compiled into bytecode, a kind of intermediate code. Java compiler transforms Java source code into JVM instructions which can then be executed directly by JVM just in time or saved as machine code before execution. Because there are many operating systems with JVMs, the same bytecode would run on any OS that has a compatible JVM. This ability to “write once and run anywhere” is one of the key features of Java.
Feature | FileInputStream | FileOutputStream |
Purpose | Reads raw byte data from a file | Writes raw byte data to a file |
Usage | Suitable for reading binary data like images | Suitable for writing binary data like images |
Methods | read(), read(byte[] b), close() | write(int b), write(byte[] b), close() |
Constructor | FileInputStream(String name) | FileOutputStream(String name) |
Example Usage | FileInputStream fis = new FileInputStream(“file.txt”); | FileOutputStream fos = new FileOutputStream(“file.txt”); |
This is the method used as the entry point of any Java application, written as a whole command line and we can break down each part as:
Method refers to a specific block of code that performs any specific tasks, commonly used to execute code to avoid any redundancy and to make the code more modular. It can be also called an instance of that class because a method can be defined within a class. Methods can accept parameters and return values. The syntax for defining a method is:
Feature | equals() | == |
Purpose | Checks the logical equality of two objects | Checks reference equality (if two references point to the same object) |
Method Type | The method from Object class can be overridden | Operator |
Usage | obj1.equals(obj2) | obj1 == obj2 |
Java does not support any type of destructors, unlike the destructors in C++, because Java primarily relies on automatic garbage collection to handle memory leaks and the efficiency of the program. The memory which is no longer in use is directly collected by an automatic garbage collector and deallocated.
Feature | this() | super() |
Usage | Calls another constructor in the same class | Calls a constructor in the parent class |
Position | It must be the first statement in a constructor | It must be the first statement in a constructor |
Use Case | Used to initialise the current class’s constructor | Used to initialise the parent class’s constructor |
Program:
Answer:
There are several ways to create objects in Java:
Example obj = new Example();
Example obj = (Example) Class.forName(“Example”).newInstance();
Example obj1 = new Example(); Example obj2 = (Example) obj1.clone();
Example obj = Example.createInstance();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“file.ser”)); Example obj = (Example) in.readObject();
Rather than any particular instance of a class, the static methods and variables can be directly associated with the class. They can be accessed directly with the help of a class name and do not create any instance of that class.
Feature | Instance Variables | Local Variables |
Declaration | Inside a class, outside any method | Inside a method, constructor, or block |
Scope | Belongs to an instance of the class | Belongs to the method, constructor, or block |
Default Value | Initialised to default value if not set | Must be explicitly initialised before use |
Lifespan | Exists as long as the object exists | Exists only during method execution |
Access Modifiers | Can use access modifiers | Cannot use access modifiers |
Classes in Java define a code block using methods, attributes, variables, and different data types that work on one single unit of logic. Hence classes are considered as blueprints in Java programming language and hold information to define the behaviour of the objects.
Syntax of a class:
Static classes do not have permission to access instance variables and methods of any outer class. Rather, static classes are nested classes which can access the static member of the outer class.
Syntax of a static class:
An object can be considered as an instance of a class, which is created from classes, representing different entities that have the behaviour patterns defined by that class. Here each object can have its own set of values for the variables and methods defined in the class.
In Java, there are four types of scopes:
One of the important parts of java.util package is the collection module which can provide many different classes and interfaces for manipulation of objects, ArrayList, HashSet, HashMap, LinkedList, etc.
Feature | Array | ArrayList |
Size | Fixed-size | Dynamic size (can grow and shrink) |
Type | Can hold primitive types and objects | Can hold only objects |
Performance | Faster due to fixed size | Slower due to dynamic resizing |
Methods | Does not provide built-in methods for manipulation | Provides methods like add(), remove(), get() |
Syntax | int[] arr = new int[10]; | ArrayList<Integer> list = new ArrayList<>(); |
Program:
Program:
JVM(Java Virtual Machine): The abstract machine that enables Python applications to run on any device or operating system; this reads and interprets Python bytecode instructions
JRE (Java Runtime Environment): JRE can provide many different libraries by executing Python programs, but the compilers and debuggers do not exist as they only support Python interpreters.
JDK (Java Development Kit): JDK is the complete kit for software development that includes JRE, a loader/interpreter (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) and many other different tools.
Feature | HashMap | HashTable |
Synchronisation | Not synchronised (thread-unsafe) | Synchronized (thread-safe) |
Null keys/values | Allows one null key and multiple null values | Does not allow null keys or values |
Performance | Faster due to lack of synchronisation | Slower due to synchronisation |
Iteration | Uses fail-fast iterator | Uses fail-safe iterator |
Legacy | Part of Java Collections Framework | Legacy class, part of earlier versions |
Program:
Answer:
The JVM divides memory into several distinct areas for efficient management:
Type | Data Type | Size (bits) | Default Value |
Primitive | byte | 8 | 0 |
short | 16 | 0 | |
int | 32 | 0 | |
long | 64 | 0L | |
float | 32 | 0.0f | |
double | 64 | 0.0d | |
char | 16 | ‘u0000’ | |
boolean | 1 | false | |
Non-primitive | String, Arrays, Classes, Interfaces | – | null |
Byte data is generally used to save memory in data types like large arrays. Also, this can help when you work with different streams of data from a network or I/O file. A byte data represents 8-bit signed integers, ranging from -128 to 127.
A class variable is declared outside any method or constructor and also declared as a static variable using a static keyword. The class variable is shared among all the instances of that class, making it only one copy of the static variable per class. Example:
Local variables do not have a default value. Local variables can only be explicitly initialised before they can be used.
Program:
Answer:
Feature | System.out | System.err | System.in |
Purpose | Standard output stream | Standard error stream | Standard input stream |
Usage | Used to display output to the console | Used to display error messages to the console | Used to read input from the console |
Stream Type | PrintStream | PrintStream | InputStream |
Buffering | Buffered | Buffered | Buffered |
Typical Use | Normal program output | Error messages and diagnostics | Reading user input |
To perform the input and output operations in Java, the IO stream library is used because it can represent the input source or the output destination, which can be a disk file, current device or another program.
Java supports a wide range of operators:
Program:
Feature | >> (Signed Right Shift) | >>> (Unsigned Right Shift) |
Usage | Shifts bits to the right, preserving the sign bit (sign-extended) | Shifts bits to the right, zero-filling the leftmost bits (zero-filled) |
Behaviour with Negative Numbers | Preserves the sign bit (negative numbers remain negative) | Does not preserve the sign bit (negative numbers become positive) |
Example | -8 >> 2 results in -2 | -8 >>> 2 results in 1073741822 |
Array in Java helps to store, manage, rearrange and sort data elements in a single variable as a list. You can store the same data type elements in one array which will act as a whole one variable, mainly helping in data handling and data manipulating. We do not have to assign each element as a new variable, as it would be a very unprofessional method of pruning errors.
Example:
A sequence of characters put together can be represented whole as a string. In Java, the strings are immutable, hence once a String object is created, its value cannot be changed again.
Example:
String message = “Hello, World!”;
Java supports two types of comments:
There are several ways to copy an array in Java:
Hare, Java cannot be called a purely object-oriented language because it supports primitive data types such as int, char, and byte which cannot be called class objects. Everything must be treated as an object in any purely object-oriented learning language.
Constructors are special methods used to initialise objects. There are two main types of constructors in Java:
Constructor Type | Description | Syntax Example |
Default Constructor | No arguments are provided by the compiler if no other constructors are defined. | public Example() {} |
parameterised Constructor | Takes arguments to initialise fields with specific values. | public Example(int value) { this.value = value; } |
If no other constructors are created by us, a default constructor is created by the compiler automatically in Java, which helps to provide a default initialisation to an object. Default constructors do not require any parameters and automatically set the fields to their default values.
Program:
Feature | Array | Collection |
Type | Fixed-size holds elements of a single type | It can be dynamically resized and can hold different types |
Data Structures | Only linear data structures | Includes List, Set, Queue, Map |
Methods | Limited methods for manipulation | Rich API for manipulation (add, remove, iterate) |
Syntax | int[] arr = new int[10]; | Collection<Integer> collection = new ArrayList<>(); |
The super keyword in Java is used to refer to the immediate parent class object. It is commonly used to:
Program:
Answer:
Feature | HashSet | TreeSet |
Order | Does not guarantee any order of elements | Maintains elements in ascending order |
Performance | Offers constant time performance for basic operations like add, remove, and contains | Offers log(n) time performance for basic operations |
Null Elements | Allows one null element | Does not allow null elements |
Backed By | Backed by a HashMap | Backed by a TreeMap |
Usage | Use it when you don’t need a sorted order | Use when you need elements in sorted order |
Program:
The final keyword in Java is used to restrict the modification of variables, methods, and classes. It can be applied in three contexts:
Feature | break | continue |
Usage | Exits the loop or switch statement immediately | Skips the current iteration and proceeds to the next iteration |
Control Flow | Transfers control outside the loop | Transfers control to the beginning of the loop |
Use Case | Use to terminate a loop or switch statement early | Use to skip certain iterations within a loop |
Program:
Answer:
Feature | Static Methods | Non-static Methods |
Access | It can be called without creating an instance | Requires an instance of the class to be called |
Usage | Used for operations that don’t require data from an instance | Used for operations that work on the instance data |
Memory Allocation | Allocated memory only once when the class is loaded | Allocated memory every time an instance is created |
Access to Members | Can access static variables and other static methods directly | Can access all variables and methods (including static) |
Packages in Java provide several advantages:
Program:
Answer:
Program:
Answer:
Feature | C++ | Java |
Platform Dependency | Platform-dependent (compiled to machine code) | Platform-independent (compiled to bytecode) |
Memory Management | Manual (using pointers) | Automatic (using garbage collection) |
Multiple Inheritance | Supported (using classes) | Not supported (achieved using interfaces) |
Operator Overloading | Supported | Not supported |
Pointers | Supported | Not supported |
Global Variables | Supported | Not supported |
Templates/Generics | Templates | Generics |
A ClassLoader in Java is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. It is a subsystem used to load class files. Java provides three built-in class loaders:
Feature | Heap Memory | Stack Memory |
Storage | Stores objects and instance variables | Stores method frames and local variables |
Memory Management | Managed by the Garbage Collector | Managed by the Java Virtual Machine (JVM) |
Lifespan | Exists as long as the application runs | Exists only for the duration of a method call |
Memory Allocation | Dynamic (size can grow or shrink) | Static (fixed size) |
Access Speed | Slower access | Faster access |
Java has several types of memory allocations:
Feature | Constructors | Destructors |
Purpose | Initialise new objects | Clean up resources before an object is destroyed (not present in Java) |
Invocation | Called automatically when an object is created | Called when an object is destroyed (not applicable in Java) |
Parameters | Can have parameters (parameterised Constructors) | N/A (Java uses finalize() for cleanup, but it is not recommended) |
Overloading | Can be overloaded (multiple constructors) | N/A |
Example Language | Java, C++ | C++ (Java does not have destructors) |
Program:
Answer:
Program:
Answer:
Program:
Answer:
Feature | Set | List |
Order | Does not maintain any order | Maintains the insertion order |
Duplicates | Does not allow duplicate elements | Allows duplicate elements |
Access Methods | No methods to access elements by index | Allows access to elements by index |
Common Implementations | HashSet, TreeSet, LinkedHashSet | ArrayList, LinkedList |
Usage | Ideal for unique elements | Ideal for an ordered collection of elements |
If you do not use the static modifier with the main method, the Java Virtual Machine (JVM) will not be able to invoke it as the entry point for the program. When you are using the main method, it must be public, static, and void for the JVM to start the execution of the program. Without using the static keyword, the main method would require an instance of the class to be created before it can be called. This will hinder the purpose of having a standard entry point to start the program execution, resulting in a runtime error.
Answer:
Yes, we can overload the main() method in Java. However, as the entry point of the program will be the public static void main(String[] args), the JVM will only call this main method with this exact signature. Any other overloaded versions of the main can be called from within the program using any other method but it will not be called by JVM.
Feature | Python | Java |
Typing | Dynamically typed | Statically typed |
Syntax | Easier and more concise | More verbose |
Memory Management | Automatic (Garbage Collection) | Automatic (Garbage Collection) |
Use Cases | Web development, scripting, data science | Enterprise applications, Android development |
Inheritance | Supports multiple inheritance directly | Supports multiple inheritance via interfaces |
Packages can be defined as a set of different but related classes and interfaces that can provide any access protection in Java. It can also handle namespace management, making it an overall way to manage large codebases and their internal conflicting names.
Program:
Answer:
The Wrapper class in Java provides a way to use primitive data types (int, char, etc.) as objects. Each primitive type has a corresponding wrapper class:
Wrapper classes are used in collections, where only objects are allowed, and to utilise utility methods provided by these classes.
There are several ways to take input from the console in Java:
Method | Description | Example Usage |
Prints the text without a newline at the end | System.out.print(“Hello”); | |
println | Prints the text with a newline at the end | System.out.println(“Hello”); |
printf | Prints formatted text using format specifiers | System.out.printf(“Hello, %s!”, “World”); |
The main concepts of Object-Oriented Programming (OOP) in Java are:
Feature | Constructors | Methods |
Purpose | Initialise new objects | Define the behaviour and operations of objects |
Name | Same as the class name | Can have any name |
Return Type | No return type | Must have a return type (void or other) |
Invocation | Called automatically when an object is created | Called explicitly using the object |
Overloading | Can be overloaded | Can be overloaded |
An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. They are used to specify a set of methods that one or more classes must implement, promoting a form of multiple inheritance and providing a way to achieve abstraction.
Example:
Wrapping the data or variables and the code that is acting upon the data methods together to form a single unit is called encapsulation in Java. The main advantage of encapsulation is to protect the data from any unauthorised access.
So that no one can modify the data without permission, which is a very important part of the project, it can be achieved through declaring variables as private using private keywords and also providing public getter and setter methods to access and update the values of those variables.
This can be understood as a form of association where there is a class reference to any other class, but both classes can exist without depending on each other. It represents a “has-a” relationship. For example, a Library has Books, but Books can exist independently of the Library.
Feature | StringBuffer | StringBuilder |
Synchronisation | Synchronized (thread-safe) | Not synchronised (not thread-safe) |
Performance | Slower due to synchronisation overhead | Faster due to lack of synchronisation |
Use Case | Used in multi-threaded environments | Used in single-threaded environments |
Availability | Available since JDK 1.0 | Available since JDK 1.5 |
The ‘IS-A’ relationship in Java refers to inheritance or implementation. It signifies that a subclass is a type of the superclass. This relationship is implemented using the extends keyword for class inheritance or the implements keyword for interface implementation. For example, if Dog extends Animal, Dog IS-A Animal.
No, Java does not support multiple inheritance with classes to avoid complexity and simplify the design. However, for the betterment of multiple inheritance, Java allows a class to implement multiple interfaces.
Feature | C++ | Java |
Multiple Inheritance | Supports multiple inheritance with classes | Does not support multiple inheritance with classes, only with interfaces |
Access Specifiers | Supports public, protected, and private inheritance | Only public and protected inheritance |
Virtual Keyword | Requires virtual keyword for virtual inheritance | Not applicable (uses interfaces for multiple inheritance) |
Method overriding refers to the situation where a subclass provides a specific implementation for a method which is already defined in its superclass. In method overloading, the method in the subclass must have the same return type, name and parameters as of the method in its superclass.
Example:
Method overloading in Java allows a class to have more than one method with the same name, but different parameters (different type or number of parameters). It is a compile-time polymorphism.
Example:
Feature | ArrayList | LinkedList |
Data Structure | Dynamic array | Doubly linked list |
Access Time | Faster access time (O(1) for get) | Slower access time (O(n) for get) |
Insertion/Deletion | Slower for insertion and deletion (O(n)) | Faster for insertion and deletion (O(1)) |
Memory Usage | Less memory overhead | More memory overhead due to node storage |
Iteration Performance | Faster iteration | Slower iteration |
Use Case | Best for read-heavy operations | Best for write-heavy operations |
No, static methods cannot be overridden in Java. They are associated with the class, not instances of the class. If a subclass defines a static method with the same signature as a static method in the superclass, it hides the superclass method rather than overriding it.
No, private methods cannot be overridden in Java. Any private method cannot be visible to subclasses. If a subclass defines a method with the same name and parameters as a private method in the superclass, it will be treated as a new method in the subclass, and not considered an override.
Feature | int array[] | int[] array |
Syntax | An older style, often seen in C/C++ | The preferred and modern style in Java |
Readability | Less readable, especially for complex types | More readable and clearer intent |
The LinkedList class in Java is a part of the Java Collections Framework. It implements the List and Deque interfaces, providing a doubly-linked list data structure. Elements in a LinkedList are not stored in contiguous memory locations; instead, each element is a node that contains a reference to the next and previous node. This allows for efficient insertions and deletions at both ends of the list.
Example:
Iterator in Java helps to iterate over a collection of objects like sets, lists, maps, etc. The iterator allows the traversal of the collection and removal of elements during iteration. The key methods in the Iterator interface are hasNext(), next(), and remove().
Feature | Collection | Collections |
Definition | Interface in the Java Collections Framework | Utility class in the Java Collections Framework |
Purpose | Provides standard methods to manipulate a group of objects | Provides static methods to operate on or return collections |
Example | List, Set, Queue | Collections.sort(), Collections.unmodifiableList() |
Exceptions in Java are handled using a combination of try, catch, finally, and throw keywords:
Important operations such as cleanup operations, and cleaning resources like files, databases, etc. can be done using the final block, whether an exception is thrown or not.
Feature | Iterator | Enumeration |
Interface | Part of the java.util package | Part of java.util package |
Methods | hasNext(), next(), remove() | hasMoreElements(), nextElement() |
Removal of Elements | Can remove elements during iteration | Cannot remove elements |
Fail-fast | Yes | No |
Use Case | Preferred for modern collections | Legacy interface, mainly for older classes like Vector and Hashtable |
A special area in Java heap memory where String literals are stored is the Java String Pool. When a String is created using double quotes, the JVM checks the String Pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If not, a new string object is created and placed in the pool.
Java Strings are immutable for several reasons:
There are four types of inheritance in Java:
There are two main types of exceptions in Java:
Feature | Comparable | Comparator |
Interface | Part of java.lang | Part of java.util |
Method | compareTo(Object o) | compare(Object o1, Object o2) |
Implementation | Must be implemented by the class to be sorted | Can be implemented in separate classes |
Sorting Logic | Defines natural ordering | Defines custom ordering |
Use Case | A single way of sorting | Multiple ways of sorting |
To mark any variable as “stored in main memory”, a volatile keyword is used. Hence every read and write operation on a volatile variable will be directly performed within the main memory and also ensure the visibility of changes across threads.
A lambda expression allows for the functional interfaces implementation i.e. those interfaces with a single abstract method in a concise way. The lambda expression is a part of Java 8 and next updates, helps primarily in representing a single-method interface.
Feature | ArrayList | Vector |
Synchronisation | Not synchronised (not thread-safe) | Synchronized (thread-safe) |
Performance | Faster due to no synchronisation overhead | Slower due to synchronisation overhead |
Growth Rate | Increases its size by 50% if it runs out of space | Doubles its size when it needs more space |
Legacy | Part of the Java Collections Framework | Considered a legacy class |
Autoboxing is the process of automatic conversion of primitive data types to their corresponding wrapper class. For example, changing int to Integer. Unboxing is the reverse process, converting wrapper class objects to their corresponding primitive types.
Program:
Answer:
Pointers are not used in Java to maintain simplicity and security. One of the primary reasons for this is that most of the time, pointers can lead to complex code which is difficult for error handling. Situations like memory leaks and pointer arithmetic errors can occur due to pointers. Hence by eliminating pointers, Java provides a safer programming environment.
Program:
Answer:
This is the mechanism which has shared control access according to resources to better manage the permission. It allows only one thread to access a synchronised block of code or any synchronised method block while executing a program, providing mutual exclusion.
Multi-threading in Java is a feature that allows concurrent execution of two or more threads for maximum utilisation of the CPU. Each thread runs parallel to others, enabling multiple tasks to be performed simultaneously within a single program. Multi-threading is commonly used in applications where tasks are independent and can run simultaneously, such as web servers, GUI applications, and real-time systems.
Feature | Pros | Cons |
Thread Safety | Ensures data consistency and prevents corruption | This can lead to contention, reducing performance |
Predictability | Provides controlled access to shared resources | Increases complexity in code |
Consistency | Guarantees that critical sections are executed in a controlled manner | It can cause deadlocks if not handled properly |
Simplified Access | Simplifies reasoning about concurrent code | Can reduce scalability in highly concurrent systems |
Program:
Answer:
The covariant return type allows a method in a subclass to override a method in its superclass and return a type that is a subclass of the return type declared in the superclass method. This enhances flexibility and reusability in method overriding.
Example:
To showcase if the field should not be serialised, the transient keyword is used. When any object is serialised, transient fields are skipped and then they will not be a part of the object’s persistent state. This is useful for fields that contain sensitive information or are not needed after deserialization.
Example:
Feature | sleep() | wait() |
Class | Thread class | Object class |
Purpose | Pauses the current thread for a specified time | Causes the current thread to wait until another thread invokes notify() or notifyAll() |
Synchronisation | Do not release the lock | Releases the lock on the object |
Usage | Thread.sleep(milliseconds) | object.wait() |
Exception | Throws InterruptedException | Throws InterruptedException |
Association in Java is a relationship between two classes that enables one class to use functionalities provided by another class. It represents a “uses-a” relationship. Association can be one-to-one, one-to-many, many-to-one, or many-to-many. It describes how objects of different classes interact with each other.
Program:
Answer:
Polymorphism refers to the ability of object-oriented programming to represent any object in many forms. It allows one interface to be used for a general class of actions and its types are:
Feature | Composition | Aggregation |
Relationship Type | Strong ownership and lifecycle dependency | Weak ownership and an independent life cycle |
Lifespan | The contained object’s lifespan depends on the container object | Contained objects can exist independently |
Example | A Car has an Engine (composition) | A Library has Books (aggregation) |
Implementation | Contained object created within the container | Contained object passed to the container |
Use Case | Use when contained objects should not exist independently | Use when contained objects can exist independently |
The main interfaces of the Java Collection framework are:
Program:
Answer:
A vector can be a dynamic array that does not have any fixed size, i.e. it can grow or shrink in size according to the data input. Vectors are generally synchronised and thread-safe, hence they can be applied safely in multi-threaded environments. However one of the drawbacks of this is slow performance speed because of synchronisation.
Features of Vector:
Here you should use the Collections.unmodifiableList to make a Java ArrayList read-only. This method helps prevent any unnecessary modifications by returning an unmodified view of the specified list.
Example:
This is a type of queue where you can put each element with a certain order or criteria, natural ordering or also by a comparator ordering at the time of queue construction. In the queue, the last element will be the head according to the specified ordering and elements are dequeued in the same order.
Features of PriorityQueue:
Feature | Iterator | ListIterator |
Applicable Collections | All Collection types | Only List types |
Traversal Direction | One-way traversal (forward) | Two-way traversal (forward and backwards) |
Add Elements | Cannot add elements | Can add elements |
Modify Elements | Can remove elements | Can remove and set elements |
Methods | hasNext(), next(), remove() | hasNext(), next(), hasPrevious(), previous(), add(), set(), remove() |
The Stack class in Java represents a last-in, first-out (LIFO) stack of objects. It extends Vector and provides methods to push, pop, peek, and check if the stack is empty.
Features of Stack:
LinkedHashSet is a subclass of HashSet that can maintain a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion order).
Features of LinkedHashSet:
The Map represents a combination of key-value pair collections and each key will be a unique one. It is not a subtype of the Collection interface. Common implementations include HashMap, TreeMap, and LinkedHashMap.
Features of Map:
EnumSet is a specialised Set implementation for use with enum types. All elements in an EnumSet must come from a single enum type specified when the set is created. EnumSet is very efficient and faster than other Set implementations because it uses bit vectors to represent the elements.
Features of EnumSet:
Program:
Answer: 2
A marker interface in Java is an interface with no methods or fields. It is used to mark or tag a class that possesses certain properties. The most common examples of marker interfaces are Serializable, Cloneable, and Remote. The marker interface allows Java to provide additional metadata to the objects at runtime.
Example:
public class MyClass implements Serializable {
// This class is marked as Serializable
}
Unlike C++, Java does not support any built-in copy constructor, but you can create your own copy constructor in Java to initialise any object using another provided object in the same class. Hence a copy constructor will reference an object of the same class and copy all its values.
Example:
A software component which can enable any type of Java application to interact and link with a database. It converts Java calls to database-specific calls.
Feature | Abstract Class | Interface |
Methods | Can have both abstract and concrete methods | Can only have abstract methods (until Java 8, which introduced default and static methods) |
Fields | Can have instance variables | Can only have constants (static final variables) |
Multiple Inheritance | Does not support multiple inheritance | Supports multiple inheritance |
Access Modifiers | Can have various access modifiers | Methods are public by default |
Use Case | Used when classes share common behaviour | Used to define a contract for classes |
The JDBC API components include:
It is one of the open-source frameworks which helps in developing Java applications and its comprehensive infrastructure support. It provides features like dependency injection, aspect-oriented programming, transaction management, and more and simplifies enterprise application development.
Key features of Spring Framework:
Unchecked exceptions that can occur during compilation are the runtime exceptions in Java. They are not checked at compile-time, and thus, do not require explicit handling. These exceptions usually indicate programming errors, such as logic mistakes or improper use of APIs.
Throw keyword allows the programmer to create and explicitly throw any type of custom exceptions based on specific conditions in the code.
Feature | Process | Thread |
Definition | Using its own memory space, this is an independent program. | Like a process, a thread is a smaller unit of a process sharing the same memory space. |
Memory | Each process has its own memory space. | Threads share the memory space of the process they belong to. |
Communication | Inter-process communication (IPC) is complex and slower. | Communication between threads is easier and faster. |
Overhead | Higher overhead due to memory allocation and management. | Lower overhead, more lightweight. |
Isolation | Processes are isolated from each other. | Threads are not isolated and can interfere with each other. |
Example | Running a web server and a database server simultaneously. | Multiple threads handling client requests in a web server. |
The states in the lifecycle of a thread in Java are:
For the execution of the current thread until the specified thread has finished executing, the join() method is used. Using this, we often check if one thread waits for the completion of another thread before any proceeding.
Feature | String | StringBuffer |
Mutability | Immutable | Mutable |
Thread Safety | Not thread-safe | Thread-safe |
Performance | Faster for read-only operations | Slower due to synchronisation overhead |
Methods | Many methods for string manipulation | Fewer methods for string manipulation |
Usage | Used for constant strings | Used for strings that require modifications |
An atomic action in Java concurrency is an operation that is performed completely independently of any other operations and cannot be interrupted or observed in an incomplete state. Atomic actions ensure that a particular set of operations execute without interference from other threads, thereby avoiding inconsistencies.
Examples of atomic operations:
The FutureTask class in Java is a concrete implementation of the Future interface. It represents a cancellable asynchronous computation. A FutureTask can be used to wrap a Callable or Runnable object. Hence it provides methods for starting and cancelling the computation, checking if the result is retrieved or not.
Key features of FutureTask:
Program:
Answer:
In conclusion, exercising these concepts is very essential for you to prepare for a Java interview. Starting from all the basic concepts like data types, and loops and taking it further to more advanced topics such as concurrency, stream API collections, etc. are very crucial for your preparation for the Java developer role.
Hope this extensive post for providing different Java interview questions helped you prepare for your next Java interview. Keep practising and stay updated regarding new technologies and advancements in Java like new tools or frameworks, updates in Java version and focus on clean code writing which is efficient.
The DevOps Playbook
Simplify deployment with Docker containers.
Streamline development with modern practices.
Enhance efficiency with automated workflows.
Popular
Data Science
Technology
Finance
Management
Future Tech
Accelerator Program in Business Analytics & Data Science
Integrated Program in Data Science, AI and ML
Certificate Program in Full Stack Development with Specialization for Web and Mobile
Certificate Program in DevOps and Cloud Engineering
Certificate Program in Application Development
Certificate Program in Cybersecurity Essentials & Risk Assessment
Integrated Program in Finance and Financial Technologies
Certificate Program in Financial Analysis, Valuation and Risk Management
© 2024 Hero Vired. All rights reserved