Olibr Blogs

Blog > All Engineering Topics > what is backend development

150 Java Interview Questions for Freshers

150 Java interview questions and answers for freshers

by Snehal Naik
java interview questions

Table of Contents

Pointer image icon

Introduction

Cracking your first Java job interview can be challenging, but not if you have access to the most commonly asked interview questions. Java is one of the top programming languages used among developers worldwide in 2024. It is used to build a variety of applications by top companies and businesses. This blog covers the top JAVA interview questions you can expect during your initial interviews.

best software companies

Don't miss out on your chance to work with the best

Apply for top global job opportunities today!

Pointer image icon

150 Java Interview Questions for Freshers

1. Is Java Platform Independent?

Yes, Java is a Platform-Independent language. Unlike many programming languages, Java compiles the program to form a bytecode or .class file. Although this file is independent of the software or hardware running, it needs a JVM (Java Virtual Machine) file preinstalled in the operating system for further execution of the bytecode. JVM is platform-dependent, but the bytecode can be created on any system. It can be executed in any other system irrespective of the hardware or software used, making Java platform-independent.

2. What are the top features of Java?

Java is one of the most used languages in the real world. Many features in Java make it better than any other language:

 

Simple: Java is a simple language with easy-to-understand syntax.

Platform Independent: Java is platform independent, which means we can run the same program in any software and hardware and will get the same result.

Interpreted: Java is interpreted as well as a compiler-based language. 

Robust: Java offers features like garbage collection and exception handling that make the language robust.

Object-Oriented: Java is an object-oriented language that supports the concepts of class,  objects, four pillars of OOPS, etc. 

Secure: Java allows users to share an application directly with the user without sharing the actual program, making it a secure language. 

High Performance:  Java is faster than other traditional interpreted programming languages.

Dynamic: supports dynamic loading of classes and interfaces.

Distributed: It is possible to access files by calling the methods from any machine connected.

Multithreaded: Java developers can deal with multiple tasks at once by defining multiple threads.

Architecture Neutral: Java is not dependent on any specific architecture.

3. What is JVM?

JVM stands for Java Virtual Machine, which acts as a Java interpreter. It is responsible for loading, verifying, and executing the bytecode generated by Java. The JVM is platform-dependent, meaning its software varies across different operating systems, but it plays a crucial role in making Java platform-independent.

4. What memory areas are available in the JVM?

The JVM consists of several memory areas, including:

  • Class (Method) Area: Stores class-level data such as the runtime constant pool, field and method data, and method code.
  • Heap: Allocates memory to objects during runtime.
  • Stack: Stores data and partial results needed for method returns and dynamic linking.
  • Program Counter Register: Holds the address of the currently executing Java virtual machine instruction.
  • Native Method Stack: Stores all native methods used in the application.

5. What is a classloader?

A classloader is part of the JRE (Java Runtime Environment). It dynamically loads Java classes and interfaces into the JVM while executing bytecode or a .class file. Classloaders enable the Java runtime system to operate without the need to know about files and file systems.

6. What are the differences between JVM, JRE, and JDK?

  • JVM (Java Virtual Machine): An interpreter that converts bytecode into machine-readable code. It is platform-dependent but interprets platform-independent bytecode, making Java platform-independent.
  • JRE (Java Runtime Environment): An installation package that provides an environment to run Java programs or applications on any machine.
  • JDK (Java Development Kit): A package that includes development tools for creating Java programs and the JRE for executing them.

7. What are the differences between Java and C++?

Basis C++ Java
Platform Platform Dependent Platform Dependent
Application Mainly used for System Programming Mainly used for Application Programming
Hardware Closer to hardware Less interactive with hardware
Global Scope Supports global and namespace scope Does not support global scope
Not Supporting Java supports thread support, documentation comments, and unsigned right shift (>>>), which C++ does not. C++ supports goto, pointers, call by reference, structures and unions, multiple inheritance, and virtual functions, which Java does not.
OOPS Object-oriented but not a single root hierarchy Object-oriented with a single root hierarchy (everything derives from java.lang.Object)
Inheritance Tree Creates a new inheritance tree Uses a single inheritance tree (all classes are children of the Object class)

8. Explain public static void main(String args[]) in Java..

In Java, the main function is declared as public static void main(String args[]).

Here’s what each term means:
public: An access modifier that makes the main function globally accessible. It allows the JVM to invoke the method from outside the class.
static: A keyword indicating that the method can be called without creating an instance of the class, avoiding unnecessary memory allocation.
void: Specifies that the method does not return any value.
main: The name of the method that serves as the entry point for the program.
String args[]: An array of java.lang.String that stores command-line arguments.

9. What is JIT?

JIT stands for Just-in-Time compiler, a component of the JRE (Java Runtime Environment) that enhances the performance of Java applications during runtime. The JIT compiler works as follows:

  • The source code is compiled with javac to produce bytecode.
  • The bytecode is passed to the JVM.
  • The JIT compiler, part of the JVM, compiles the bytecode into native machine code at runtime.
  • The JIT compiler is always enabled but activates when a method is invoked. For compiled methods, the JVM directly calls the compiled code instead of interpreting it.
  • This process increases the performance and speed of execution.

10. What is the Java String Pool?

The Java String Pool is a special area in heap memory where all the strings defined in a program are stored. A separate area in the stack stores the variable holding the string. When a new string object is created, the JVM checks if the string already exists in the pool. If it does, the same object reference is shared with the variable; otherwise, a new object is created.

Example:

String str1 = "Hello";
// "Hello" will be stored in the String Pool
// str1 will be stored in stack memory

11. What will happen if we declare the main as static?

You can declare the main method without the static keyword, and it won’t produce any errors. However, the main method will not be recognized as the entry point of the application or program.

12. What are Packages in Java?

In Java, packages are a way to organize classes, interfaces, and sub-packages into namespaces, which makes the code easier to manage and avoid naming conflicts. Packages serve as containers for a group of related classes and are used to categorize the classes logically, allowing for better structure and organization of large projects.

13. Why are Packages used in Java?

Packages in Java are essential for organizing code, managing namespaces, and controlling access, making it easier to work on complex applications.

14. What are the advantages of using Packages in Java?

The benefits of using packages in Java include:

  • Preventing naming conflicts
  • Easier access control
  • Organizing code
  • Reusability
  • Namespace management
  • Allowing hidden classes
  • Simplifying the location of related classes

15. How many types of packages are there in Java?

There are two types of packages in Java:

  • User-defined packages
  • Built-in packages

16. Explain the different data types in Java.

Java has two categories of data types:

Primitive Data Types: These are single values with no special capabilities. There are eight primitive data types:

    • boolean: stores true or false values.
    • byte: stores an 8-bit signed two’s complement integer.
    • char: stores a single 16-bit Unicode character.
    • short: stores a 16-bit signed two’s complement integer.
    • int: stores a 32-bit signed two’s complement integer.
    • long: stores a 64-bit two’s complement integer.
    • float: stores a single-precision 32-bit IEEE 754 floating-point number.
    • double: stores a double-precision 64-bit IEEE 754 floating-point number.

Non-Primitive Data Types: These reference data types contain memory addresses of the variable’s values. Types include:

    • Strings
    • Arrays
    • Classes
    • Objects
    • Interfaces

17. When is the byte data type used?

The byte data type is an 8-bit signed two- complement integer with a range from -128 to 127. It is used when memory savings are important, and the range of values needed is between -128 and 127.

18. Can we declare pointers in Java?

No, Java does not support pointers. This is to enhance security, as pointers can lead to unsafe code.

19. What is the difference between Set and Map?

Set Map
Implemented using java.util package. Implemented using java.util package.
Can extend the Collection interface. Does not extend the Collection interface.
Does not allow duplicate values. Allows duplicate values.
Can store only one null value. Can store multiple null values.

20. What are the default values of byte data type, and the float and double data types in Java?

The default value of the byte data type in Java is 0. The default value of the float data type is 0.0f, and the default value of the double data type is 0.0d.

21. What is a Wrapper class in Java?

A wrapper class in Java is an object class that encapsulates primitive data types. Java has eight wrapper classes: Boolean, Byte, Short, Integer, Character, Long, Float, and Double. Custom wrapper classes can also be created, similar to structures in the C programming language.

22. Why do we need wrapper classes?

Wrapper classes are needed for several reasons:

  • They are final and immutable.
  • They provide methods like valueOf() and parseInt().
  • They support autoboxing and unboxing.

23. What is the difference between instance and local variables?

Instance Variable Local Variable
Declared outside the method, directly invoked by the method. Declared within the method.
Has a default value. No default value.
It can be used throughout the class. The scope is limited to the method.

24. What are the default values assigned to variables and instances in Java?

In Java, if instance variables are not initialized, the compiler assigns them default values based on their data types:

  • Numeric types (byte, short, int, long, float, double): 0
  • Boolean type: false
  • Object types (classes, interfaces, arrays): null
  • Char type: ‘\u0000’ (null character)

Example: 

// Java Program to demonstrate use of default values
import java.io.*;
class GFG {
    // static values
    static byte b;
    static int i;
    static long l;
    static short s;
    static boolean bool;
    static char c;
    static String str;
    static Object object;
    static float f;
    static double d;
    static int[] Arr;
    public static void main(String[] args) {
        // byte value
        System.out.println("byte value: " + b);
        // short value
        System.out.println("short value: " + s);
        // int value
        System.out.println("int value: " + i);
        // long value
        System.out.println("long value: " + l);
        System.out.println("boolean value: " + bool);
        System.out.println("char value: " + c);
        System.out.println("float value: " + f);
        System.out.println("double value: " + d);
        System.out.println("string value: " + str);
        System.out.println("object value: " + object);
        System.out.println("Array value: " + Arr);
    }
}

Output

byte value: 0
short value: 0
int value: 0
long value: 0
boolean value: false
char value: 
float value: 0.0
double value: 0.0
string value: null
object value: null
Array value: null

25. What is a Class Variable?

In Java, a class variable (also known as a static variable) is a variable declared within a class but outside any method, constructor, or block. Class variables are declared with the static keyword and are shared by all instances of the class and by the class itself. Regardless of how many objects are created from a class, each class variable exists only once.

Example:

// Java program to demonstrate use of Class Variable
class GFG {
    public static int ctr = 0;
    public GFG() { ctr++; }
    public static void main(String[] args) {
        GFG obj1 = new GFG();
        GFG obj2 = new GFG();
        GFG obj3 = new GFG();
        System.out.println("Number of objects created are " + GFG.ctr);
    }
}

Output

Number of objects created are 3

26. What is the default value stored in Local Variables?

Local variables do not have a default value. Both primitive variables and objects must be explicitly initialized before use.

27. Explain the difference between an instance variable and a class variable.

Instance Variable: An instance variable is a class variable without the static modifier and is typically unique to each instance of the class. These variables can have different values for different objects, as they are tied to specific instances of the class.

Example:

// Java Program to demonstrate Instance Variable
import java.io.*;
class GFG {
    private String name;
    public void setName(String name) { this.name = name; }
    public String getName() { return name; }
    public static void main(String[] args) {
        GFG obj = new GFG();
        obj.setName("John");
        System.out.println("Name: " + obj.getName());
    }
}

Output

Name: John

Class Variable: A class variable is declared with the static keyword and is shared among all instances of the class. These variables have a single value that is shared across all objects of the class.

Example:

// Java Program to demonstrate Class Variable
import java.io.*;
class GFG {
    // class variable
    private static final double PI = 3.14159;
    private double radius;
    public GFG(double radius) { this.radius = radius; }
    public double getArea() { return PI * radius * radius; }
    public static void main(String[] args) {
        GFG obj = new GFG(5.0);
        System.out.println("Area of circle: " + obj.getArea());
    }
}

Output

Area of circle: 78.53975

28. What is a static variable?

A static variable is a class-level variable declared with the static keyword. It is shared among all instances of the class, meaning only one copy of the variable exists, regardless of how many objects are created.

29. What is the difference between System.out, System.err, and System.in?

System.out: A PrintStream used for standard output, typically to display results on the console.

Example:

// Java Program to implement System.out
import java.io.*;
// Driver Class
class GFG {
    // Main Function
    public static void main(String[] args) {
        // Use of System.out
        System.out.println("Hello, World!");
    }
}

System.err: A PrintStream used for standard error output, typically to display error messages.

Example:

// Java program to demonstrate System.err
import java.io.*;
// Driver Class
class GFG {
    // Main function
    public static void main(String[] args) {
        // Printing error
        System.err.println("This is an error message.");
    }
}

Output

This is an error message.

System.in: An InputStream is used to read input from the console. It is often used with the Scanner class to take user input.

Example:

// Java Program to demonstrate System.in
import java.util.*;
// Driver Class
class Main {
    // Main Function
    public static void main(String[] args) {
        // Scanner class with System.in
        Scanner sc = new Scanner(System.in);
        // Taking input from the user
        int x = sc.nextInt();
        int y = sc.nextInt();
        // Printing the output
        System.out.printf("Addition: %d", x + y);
    }
}

Output

3
4
Addition: 7

30. What do you understand by an IO stream?

Java’s I/O package provides various streams to perform input-output operations. These streams support handling different types of data, including objects, data types, characters, and files, to facilitate comprehensive I/O operations.

31. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The primary difference is that InputStream and OutputStream classes handle byte stream data, while Reader and Writer classes handle character data. InputStream/OutputStream methods accept byte arrays, whereas Reader/Writer methods accept character arrays. Reader/Writer classes are more efficient for handling Unicode characters and are useful for internationalization. Use Reader/Writer classes for character data and InputStream/OutputStream classes for binary data.

Example:

// Java Program to demonstrate Reading and Writing Binary Data
// with InputStream/OutputStream
import java.io.*;

class GFG {
    public static void main(String[] args) {
        try {
            // Writing binary data to a file using OutputStream
            byte[] data = {(byte) 0xe0, 0x4f, (byte) 0xd0, 0x20, (byte) 0xea};
            OutputStream os = new FileOutputStream("data.bin");
            os.write(data);
            os.close();

            // Reading binary data from a file using InputStream
            InputStream is = new FileInputStream("data.bin");
            byte[] newData = new byte[5];
            is.read(newData);
            is.close();

            // Printing the read data
            for (byte b : newData) {
                System.out.print(b + " ");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

-32 79 -48 32 -22

32. What are the super most classes for all the streams?

Stream classes in Java are divided into ByteStream and CharacterStream classes. ByteStream classes include InputStream and OutputStream, while CharacterStream classes include Reader and Writer. The superclass for all InputStream classes is java.io.InputStream, and for all OutputStream classes, it is java.io.OutputStream. Similarly, the superclass for all Reader classes is java.io.Reader, and for all Writer classes, it is java.io.Writer.

33. What are FileInputStream and FileOutputStream?

Java provides I/O Streams to read and write data. A Stream represents an input source or an output destination, such as a file, an I/O device, or another program. FileInputStream in Java is used to read data from a file as a stream of bytes, commonly used for reading binary data like images, audio files, or serialized objects.

Example:

File file = new File("path_of_the_file");
FileInputStream inputStream = new FileInputStream(file);

FileOutputStream in Java is used to write data byte by byte into a specified file or file descriptor. It is typically used for writing raw byte data, such as images, into a file.

Example:

File file = new File("path_of_the_file");
FileOutputStream outputStream = new FileOutputStream(file);

34. What is the purpose of using BufferedInputStream and BufferedOutputStream classes?

When working with files or streams, using BufferedInputStream and BufferedOutputStream classes can enhance the I/O performance of a program. These classes provide buffering, meaning data is stored in a buffer before being written to a file or read from a stream. This reduces the number of interactions with the network or disk, allowing programs to write large amounts of data at once instead of in small chunks, thereby reducing overhead.

BufferedInputStream(InputStream inp); // Creates a buffered input stream
BufferedOutputStream(OutputStream output); // Creates a buffered output stream with default size

35. What are FilterStreams?

FilterStreams are streams that filter data as it is read or written. They return a stream consisting of elements that match a given predicate. When using filter(), it doesn’t perform the filtering immediately but creates a new stream that, when traversed, contains the elements of the initial stream that match the predicate.

Example:

FileInputStream fis = new FileInputStream("file_path");
FilterInputStream filterStream = new BufferedInputStream(fis);

36. What is an I/O filter?

An I/O filter is an object that reads from one stream and writes data to input and output sources. It uses the java.io package to perform these operations.

37. How many ways can you take input from the console?

There are several methods to take input from the console in Java:

  • Using Command Line Arguments
  • Using BufferedReader Class
  • Using Console Class
  • Using Scanner Class

Examples:

Using Command Line Arguments:

// Java Program to implement input using Command line argument
import java.io.*;
class GFG {
    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println("The command line arguments are:");
            for (String val : args)
                System.out.println(val);
        } else {
            System.out.println("No command line arguments found.");
        }
    }
}
// Use below commands to run the code
// javac GFG.java
// java GFG XYZ

Using BufferedReader Class:

// Java Program to implement BufferedReader Class
import java.io.*;
class GFG {
    public static void main(String[] args) throws IOException {
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        String x = read.readLine();
        System.out.println(x);
    }
}

Using Console Class:

// Java program to implement input using Console Class
public class GfG {
    public static void main(String[] args) {
        String x = System.console().readLine();
        System.out.println("You entered string " + x);
    }
}

Using Scanner Class:

// Java program to demonstrate working of Scanner in Java
import java.util.Scanner;
class GfG {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        System.out.println("You entered string " + str);
    }
}

38. What is the difference between print, println, and printf?

  • print: Prints the text and keeps the cursor on the same line.
  • println: Prints the text and moves the cursor to the next line.
  • printf: Prints formatted text using format specifiers.

39. What are operators?

Operators are special symbols used to perform operations on variables and values.

40. How many types of operators are available in Java?

Java provides several types of operators:

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators
  • Instance of Operator

Postfix operators have the highest precedence according to Java operator precedence.

41. Explain the difference between >> and >>> operators.

The >> operator shifts the bits to the right, preserving the sign bit, while the >>> operator shifts the bits to the right, filling the leftmost bits with zeros.

Example:

import java.io.*;
// Driver
class GFG {
    public static void main(String[] args) {
        int a = -16, b = 1;
        // Use of >>
        System.out.println(a >> b);
        a = -17;
        b = 1;
        // Use of >>>
        System.out.println(a >>> b);
    }
}

Output

-8
2147483639

42. Which Java operator is right associative?

The assignment operator = is right associative.

43. What is the dot operator?

The dot operator in Java is used to access the instance variables and methods of class objects. It is also used to access classes and sub-packages from a package.

44. What is covariant return type?

A covariant return type allows an overriding method to return a type that is a subclass of the return type declared in the original method. This feature enhances code readability, usability, and maintainability by avoiding confusing type casts and preventing runtime ClassCastException.

45. What is the dot operator?

In Java, the dot operator is used to access the instance variables and methods of class objects. It is also utilized to access classes and sub-packages within a package.

46. What are the benefits of using covariant return type?

The benefits of using covariant return types include:

  • Avoiding confusing type casts within the class hierarchy, making the code more readable, usable, and maintainable.
  • Allowing more specific return types when overriding methods.
  • Preventing runtime ClassCastException on returns.

47. What is the transient keyword?

The transient keyword in Java is used during serialization to indicate that a particular variable should not be saved. When the JVM encounters a transient keyword, it ignores the original value of the variable and saves the default value for that variable’s data type.

48. What’s the difference between the methods sleep() and wait()?

Sleep() Wait()
Belongs to the Thread class. Belongs to the Object class.
Does not release the lock held by the current thread. Releases the lock, allowing other threads to acquire it.
Is a static method. Is not a static method.
Does not throw InterruptedException unless the thread is interrupted while sleeping Throws InterruptedException if the thread is interrupted while waiting.
Used to delay a thread for a specific duration. Used to pause a thread until it is notified by another thread.
Has two overloaded methods: sleep(long millis)and sleep(long millis, int nanos). Has three overloaded methods: wait(), wait(long timeout), and wait(long timeout, int nanos).

49. What are the differences between String and StringBuffer?

String StringBuilder
Provides functionality to work with strings. Used to build a mutable string.
Thread-safe (two threads cannot call the methods of StringBuffer simultaneously). Not thread-safe (two threads can call the methods concurrently).
Comparatively slow due to synchronization. Faster due to lack of synchronization.

50. Which among String or StringBuffer should be preferred when there are a lot of updates required to be done in the data?

StringBuilder is preferred over StringBuffer for performance reasons, as it is faster. However, if thread safety is a concern, StringBuffer should be used.

51. Why is StringBuffer called mutable?

The StringBuffer class in Java represents a modifiable sequence of characters. Unlike the immutable String class, StringBuffer allows you to change the contents of a string without creating new objects. This makes it mutable.

Example:

// Java Program to demonstrate use of StringBuffer
public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer s = new StringBuffer();
        s.append("X");
        s.append("Y");
        s.append("Z");
        String message = s.toString();
        System.out.println(message);
    }
}

Output

XYZ

52. How is the creation of a String using new() different from that of a literal?

Creating a string using new() allocates memory in the heap, even if an identical string already exists. In contrast, string literals are stored in the string pool within the stack memory.

Syntax:

String x = new String("ABC");

53. What is an array in Java?

An array in Java is a data structure used to store a fixed-size sequence of elements of the same type. Elements are accessed by their index, starting from 0 up to the length of the array minus one. Arrays are declared using square brackets, and their size is specified during declaration.

Syntax:

int[] Arr = new int[5];

54. On which memory are arrays created in Java?

Arrays in Java are created in heap memory. When an array is instantiated using the new keyword, memory is allocated in the heap to store its elements. The Java Virtual Machine (JVM) manages heap memory, which is shared among all threads of the Java program. The JVM’s garbage collector reclaims memory that is no longer in use. Arrays are created dynamically, meaning their size is determined at runtime and cannot be changed once set.

55. What are the types of arrays?

There are two types of arrays in Java: Primitive arrays and Reference arrays.

Single-Dimensional Arrays: Arrays with only one dimension, such as an array of integers or strings.

Syntax

data_type[] Array_Name = new data_type[ArraySize];

Multi-Dimensional Arrays: Arrays with two or more dimensions, such as two-dimensional or three-dimensional arrays.

56. Why does the Java array index start with 0?

The index of an array represents the distance from the start of the array. The first element has a distance of 0, hence the starting index is 0.

Syntax:

[Base Address + (index * no_of_bytes)]

57. What is the difference between int array[] and int[] array?

Both int array[] and int[] array are used to declare an array of integers in Java. The difference lies in their syntax, with no functional difference between them.

  • int arr[] is a C-style syntax for declaring an array.
  • int[] arr is a Java-style syntax for declaring an array.

It is generally recommended to use the Java-style syntax (int[] arr) as it is easier to read and understand and is more consistent with other Java language constructs.

58. How to copy an array in Java?

In Java, there are several methods to copy an array depending on the requirements:
  • clone() method: This method creates a shallow copy of the array, meaning the new array shares the same memory as the original.
int[] Arr = {1, 2, 3, 5, 0};
int[] tempArr = Arr.clone();
  • arraycopy() method: This method creates a deep copy of the array, producing a new array with the same values as the original.
int[] Arr = {1, 2, 7, 9, 8};
int[] tempArr = new int[Arr.length];
System.arraycopy(Arr, 0, tempArr, 0, Arr.length);
  • copyOf() method: This method creates a new array with a specified length and copies the contents of the original array into it.
int[] Arr = {1, 2, 4, 8};
int[] tempArr = Arrays.copyOf(Arr, Arr.length);
  • copyOfRange() method: Similar to the copyOf() method, but allows specifying a range of elements to copy from the original array.
int[] Arr = {1, 2, 4, 8};
int[] tempArr = Arrays.copyOfRange(Arr, 0, Arr.length);

59. What do you understand by the jagged array?

A jagged array in Java is a two-dimensional array where each row can have a different length. Unlike a regular 2D array where all rows have the same length, a jagged array provides flexibility in the size of each row, which is useful when dealing with data of varying lengths or optimizing memory usage.

Syntax:

int[][] Arr = new int[][] {
    {1, 2, 8}, 
    {7, 5}, 
    {6, 7, 2, 6}
};

60. Is it possible to make an array volatile?

In Java, it is not possible to make an array volatile. The volatile keyword can only be applied to individual variables, not to arrays or collections. When a variable is declared as volatile, its value is always read from and written to the main memory, ensuring that all threads accessing the variable see the most recent value.

61. What are the advantages and disadvantages of an array?

Advantages of Arrays:

  • Arrays provide direct and efficient access to any element with an O(1) operation time.
  • They store data efficiently in contiguous memory regions, known at compile time.
  • Arrays allow for quick data retrieval due to contiguous memory storage.
  • They are simple to implement and understand, making them ideal for beginners.

Disadvantages of Arrays:

  • Arrays have a fixed size determined at creation, requiring a new array and data copying if resizing is needed.
  • If not fully utilized, arrays can waste memory space.
  • Arrays can be rigid compared to other data structures like linked lists and trees, with limited support for complex data types.
  • All elements in an array must be of the same data type, limiting support for complex data types like objects and structures.

62. What is an object-oriented paradigm?

An object-oriented paradigm is a programming approach where objects are used as the base entities upon which methods are applied. This paradigm involves concepts like encapsulation, inheritance, and polymorphism, making it a method for solving problems using objects.

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

The main concepts of Object-Oriented Programming (OOP) in Java are:

  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

64. What is the difference between an object-oriented programming language and an object-based programming language?

Object-Oriented Programming Language Object-Based Programming Language
Covers larger concepts like inheritance, polymorphism, and abstraction. Limited to the usage of objects and encapsulation.
Supports all built-in objects. Does not support all built-in objects.
Examples: Java, C#. Examples: JavaScript, Visual Basic.

65. How is the ‘new’ operator different from the ‘newInstance()’ operator in Java?

The new operator is used to create objects, but it cannot determine the type of object to create at runtime. The newInstance() method, on the other hand, allows for the creation of objects where the type is decided at runtime.

66. What are Classes in Java?

Classes in Java are collections of objects that share similar characteristics and attributes. They serve as blueprints or templates from which objects are created. While classes are not real-world entities, they help in creating objects that represent real-world entities.

67. What is the difference between static (class) method and instance method?

Static (Class) Method Instance Method
Associated with a class rather than an object. Associated with an object rather than a class.
Can be called using the class name without creating an instance. Called on a specific instance using the object reference.
Does not have access to the this keyword. Has access to the this keyword.
Can access only static members of the class. Can access both static and non-static members of the class.
Cannot be overridden because they are resolved at compile time. Can be overridden because they are resolved at runtime.

68. What is the this keyword in Java?

The this keyword in Java is used to reference the current object within a method or constructor.

69. What are access specifiers and their types in Java?

Access specifiers in Java restrict the scope of a class, constructor, variable, method, or data member. The four types of access specifiers are:

  • Public
  • Private
  • Protected
  • Default

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

The initial value of an object reference defined as an instance variable is null.

71. What is an object?

An object is a real-world entity with certain properties and methods associated with it. In Java, an object is an instance of a class and can be created using the new keyword.

72. What are the different ways to create objects in Java?

There are several methods to create objects in Java:

  1. Using the new keyword
  2. Using Class.newInstance()
  3. Using the clone() method
  4. Using deserialization
  5. Using the newInstance() method of the Constructor class

73. What are the advantages and disadvantages of object cloning?

Advantages:

  • The = assignment operator cannot be used for cloning as it only copies reference variables. The clone() method of the Object class can be used to create a copy of an object.
  • The clone() method is protected, meaning only the class itself can clone its objects, ensuring encapsulation.
  • Reduces code size by avoiding repetitive initialization.
  • Allows for quick replication of complex objects, similar to the prototype pattern.

Disadvantages:

  • Since Object.clone() is protected, you need to provide your own clone() method and call Object.clone() from it.
  • If no methods are provided, you need to implement the Cloneable interface to inform the JVM that cloning is allowed.
  • The default clone() method performs a shallow copy, which can be problematic if deep copying is required.

74. What are the advantages of passing this into a method instead of the current class object itself?

  • this is a final variable, meaning it cannot be reassigned, whereas the current class object might not be final and can be changed.
  • this can be used within synchronized blocks to ensure thread safety.

75. What is a constructor?

A constructor is a special method used to initialize objects. It is called when an object is created and has the same name as the class.

Example:

// Class Created
class XYZ {
    private int val;
    
    // Constructor
    XYZ() {
        val = 0;
    }
}

76. What happens if you don’t provide a constructor in a class?

If no constructor is provided in a class, the Java compiler automatically generates a default constructor with no arguments and no operations.

77. How many types of constructors are used in Java?

There are two types of constructors in Java:

Default Constructor: Does not accept any parameters and sets default values for object attributes.

class_Name();

Parameterized Constructor: Accepts parameters to assign values to instance variables during object initialization.

class_Name(parameter1, parameter2, ...);

78. What is the purpose of a default constructor?

A default constructor initializes objects with default values. It is called during the creation of an object when no parameters are provided.

79. What do you understand by copy constructor in Java?

A copy constructor creates a new object by copying the properties of another object. It takes another object as a parameter and duplicates its attributes.

80. Where and how can you use a private constructor?

A private constructor is used to prevent other classes from instantiating the object, often to implement the Singleton pattern.

Example:

// Java program to demonstrate Singleton pattern using private constructors.
class GFG {
    static GFG instance = null;
    public int x = 10;
    
    // Private constructor
    private GFG() {}
    
    // Factory method to provide instances
    public static GFG getInstance() {
        if (instance == null)
            instance = new GFG();
        return instance;
    }
}

// Driver Class
class Main {
    public static void main(String args[]) {
        GFG a = GFG.getInstance();
        GFG b = GFG.getInstance();
        a.x += 10;
        System.out.println("Value of a.x = " + a.x);
        System.out.println("Value of b.x = " + b.x);
    }
}

Output

Value of a.x = 20
Value of b.x = 20

81. What are the differences between constructors and methods?

  • Constructors are used to initialize objects and are called only once when the object is created. They do not have a return type.
  • Methods can be called multiple times during the object’s lifecycle and have a return type, which can be void or any other type.

Constructors set up the initial state of an object, while methods perform specific actions.

82. What is an Interface?

An interface in Java is a collection of abstract methods and static final variables that define a contract for a set of related classes. Any class that implements an interface must provide implementations for its methods.

Syntax:

interface InterfaceName {
    // constant fields
    // abstract methods
}

Example

// Java Program to demonstrate Interface
interface Shape {
    double getArea();
    double getPerimeter();
}

class Circle implements Shape {
    private double radius;
    
    public Circle(double radius) {
        this.radius = radius;
    }
    
    public double getArea() {
        return Math.PI * radius * radius;
    }
    
    public double getPerimeter() {
     return 2 * Math.PI * radius;
    }
}

class GFG {
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);
        System.out.println("Area of circle is " + circle.getArea());
        System.out.println("Perimeter of circle is " + circle.getPerimeter());
    }
}

Output

Area of circle is 78.53981633974483
Perimeter of circle is 31.41592653589793

83. Give some features of the Interface.

An interface in Java is an abstract type used to specify the behavior of a class. It contains static constants and abstract methods.

Features of an interface include:

  • Achieving total abstraction.
  • Allowing multiple inheritance in Java.
  • Enabling a class to implement multiple interfaces.
  • Facilitating loose coupling.

84. What is a marker interface?

A marker interface is an empty interface with no fields or methods. Examples include Serializable, Cloneable, and Remote interfaces.

85. What are the differences between abstract class and interface?

Abstract Class Interface Class
Can contain both abstract and non-abstract methods. Contains only abstract methods.
Supports final methods. Does not support final methods.
Does not support multiple inheritance. Supports multiple inheritance.
Declared using the abstract keyword. Declared using the interface keyword.
Extended using the extends keyword. Implemented using the implements keyword.
Can have members with different access levels like protected, private, etc. All members are public by default.

86. What is method overriding?

Method overriding, also known as runtime polymorphism, occurs when a subclass provides a specific implementation for a method already defined in its superclass. The method in the subclass must have the same name, parameters, and return type as the method in the superclass.

87. What is method overloading?

Method overloading in Java allows multiple methods to have the same name but different parameters (different signatures). It is also known as compile-time polymorphism, static polymorphism, or early binding.

88. What is the primary benefit of encapsulation?

Encapsulation in Java protects the internal state of an object from external modification or access. It hides the implementation details and exposes only a public interface for interaction, thus controlling and managing the state and behaviour of an object while protecting it from unauthorized access.

Example:

// Java Program to demonstrate use of Encapsulation
class Person {
    private String name;
    private int age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("John");
        p.setAge(19);
        System.out.println("Name is " + p.getName());
        System.out.println("Age is " + p.getAge());
    }
}

Output

Name is John
Age is 19

89. What is Aggregation?

Aggregation is a type of association that represents a “has-a” relationship between two classes. It is a unidirectional relationship where one class contains a reference to another class and is said to own that class.

90. What is the ‘IS-A’ Relationship in OOPs Java?

The ‘IS-A’ relationship in OOPs Java refers to inheritance, where one class inherits the properties and methods of another class.

91. Define Inheritance

Inheritance is an OOP concept where a subclass inherits the properties and behaviors of a superclass. The subclass is more specific, while the superclass is more general. Inheritance promotes code reusability.

92. Types of Inheritance in Java

  • Single Inheritance: A subclass inherits from one superclass.
  • Multilevel Inheritance: A subclass inherits from another subclass, creating a hierarchy.
  • Hierarchical Inheritance: Multiple subclasses inherit from the same superclass.
  • Multiple Inheritance: A subclass inherits from multiple superclasses (only supported for interfaces in Java).

93. What is multiple inheritance? Does Java support it?

Multiple inheritance allows a class to inherit properties from multiple parent classes. Java does not support multiple inheritance for classes due to potential conflicts but supports it for interfaces.

Example:

// Java Program to show multiple Inheritance
interface Animal {
    void eat();
}

interface Mammal {
    void drink();
}

class Dog implements Animal, Mammal {
    public void eat() { System.out.println("Eating"); }
    public void drink() { System.out.println("Drinking"); }
    void bark() { System.out.println("Barking"); }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
        d.drink();
        d.bark();
    }
}

Output

Eating
Drinking
Barking

94. How is inheritance in C++ different from Java?

Inheritance in C++ Inheritance in Java
Supports multiple inheritance. Does not support multiple inheritance.
Classes do not inherit from the Object class by default. All classes inherit from the Object class.

95. What are the limitations of using inheritance?

Inheritance can lead to a subclass inheriting everything from the superclass, which can make the subclass too complex and error-prone, especially when dynamic overriding or overloading is involved.

96. Is there any limitation to using Inheritance?

Yes, inheritance in Java has limitations. It can lead to subclasses inheriting everything from the superclass, which can make the subclass overly complex and prone to errors, especially when dynamic overriding or overloading is involved.

97. Although inheritance is a popular OOP concept, it is less advantageous than composition. Explain.

Inheritance is a common OOP concept where a class inherits properties and methods from another class, known as the superclass. In contrast, composition involves a class containing an instance of another class as a member variable. Here are some reasons why composition is often more advantageous:

  • Tight Coupling: Changes in the superclass can affect all its subclasses, making the code less flexible and harder to maintain.
  • Fragile Base Class Problem: Modifications to the base class can break the functionality of derived classes, making it difficult to add or modify features.
  • Limited Reuse: Inheritance can lead to limited code reuse and unnecessary code in subclasses, resulting in a less maintainable codebase.

98. What is an association?

Association is a relationship between two separate classes established through their objects. It represents a “has-a” relationship.

99. What do you mean by aggregation?

Aggregation is a form of association where one class contains a reference to another class. It represents a “part-of” relationship but allows the contained object to exist independently of the container.

100. What is composition in Java?

Composition implies a relationship where the child cannot exist independently of the parent. For example, a human heart cannot exist separately from a human.

101. What is the difference between composition and aggregation?

Aggregation Composition
Defines a “has-a” relationship. Represents a “part-of” relationship.
Objects are independent. Objects are dependent on each other.
Represented by an empty diamond. Represented by a filled diamond.
Child objects do not have a lifecycle. Child objects have a lifecycle.

102. Can the constructor be inherited?

No, constructors cannot be inherited.

103. What is Polymorphism?

Polymorphism is the ability of an object to take on many forms. It is of two types:

  • Compile-time polymorphism (method overloading): Methods with the same name but different parameters.
  • Run-time polymorphism (method overriding): A method in a subclass overrides a method in the superclass.

104. What is runtime polymorphism or dynamic method dispatch?

Dynamic method dispatch is the process of resolving method calls at runtime. When a method is overridden in a subclass, the JVM determines which method to execute based on the object’s runtime type, not the reference type.

105. What is data encapsulation?​

Data encapsulation is an OOP concept that binds together the data and the methods that manipulate that data. It is achieved by declaring the instance variables of a class as private, restricting access to them from outside the class.

106. What is the difference between Comparable and Comparator?

Comparable Comparator
Interface present in java.lang package. Interface present in java.util package.
Provides compareTo() method for sorting. Provides compare() method for sorting.
Supports single sorting sequence. Supports multiple sorting sequences.
Sorting logic must be in the same class whose objects are being sorted. Sorting logic should be in a separate class to allow different sorting based on various attributes.
Sorts data according to a fixed order. Sorts data according to a customized order.
Affects the original class. Does not affect the original class.
Frequently implemented in API by Calendar, wrapper classes, Date, and String. Used to sort instances of third-party classes.

107. Can we override the static method?

No, static methods belong to the class rather than an instance, so they cannot be overridden.

108. Can we override the overloaded method?

Yes, overloaded methods can be overridden. Overloading and overriding are different concepts; overloading is resolved at compile time, while overriding is resolved at runtime.

109. Can we overload the main() method?

Yes, the main method can be overloaded in Java, but the JVM will only call the standard main method with the signature public static void main(String[] args).

110. What are method overloading and method overriding?

Method Overloading: Also known as Compile Time Polymorphism, method overloading occurs when two or more methods in the same class share the same name but have different parameters.

Example:

// Java Program to demonstrate Method Overloading
class GFG {
    static int multiply(int a, int b) { return a * b; }
    static int multiply(int a, int b, int c) { return a * b * c; }
    static int multiply(int a, int b, int c, int d) { return a * b * c * d; }

    public static void main(String[] args) {
        System.out.println("multiply() with 2 parameters: " + multiply(4, 5));
        System.out.println("multiply() with 3 parameters: " + multiply(2, 3, 4));
        System.out.println("multiply() with 4 parameters: " + multiply(2, 3, 4, 1));
    }
}

Output:

multiply() with 2 parameters: 20
multiply() with 3 parameters: 24
multiply() with 4 parameters: 24

Method Overriding: Method overriding happens when a subclass provides a specific implementation for a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameters as the method in the superclass.

Example:

// Java Program to demonstrate Method Overriding
class Vehicle {
    void drive() {
        System.out.println("drive() method of base class");
        System.out.println("driving the Car.");
    }
}

class Car extends Vehicle {
    void drive() {
        System.out.println("drive() method of derived class");
        System.out.println("Car is driving.");
    }
}

public class GFG {
    public static void main(String[] args) {
        Car c1 = new Car();
        Vehicle v1 = new Vehicle();
        c1.drive();
        v1.drive();
        Vehicle vehicle = new Car();
        vehicle.drive();
    }
}

Output:

drive() method of derived class
Car is driving.
drive() method of base class
driving the Car.
drive() method of derived class
Car is driving.

111. What is the difference between method overloading and method overriding?

Method overloading Method overriding
Occurs when two or more methods in the same class have the same name but different parameters. Occurs when a subclass provides a specific implementation for a method already defined in its superclass.
Can happen within the same class or between a subclass and a parent class. Can only happen in a subclass.
Errors are caught at compile time. Errors are caught at runtime.
Example of Compile Time Polymorphism. Example of Run Time Polymorphism.
May or may not require inheritance. Always requires inheritance.
Happens within a single class. Happens between two classes with an inheritance relationship.

112. Can we override private methods?

No, private methods cannot be overridden in Java. Private methods are only accessible within the class they are declared in and are not visible to subclasses.

113. Can we change the scope of the overridden method in the subclass?

No, the scope of an overridden method in the subclass must be the same or broader than the scope of the method in the superclass. For example, if the superclass method is public, the overridden method in the subclass can be public or protected but not private.

114. Can we modify the throws clause of the superclass method while overriding it in the subclass?

Yes, but with limitations. The subclass method can only specify unchecked exceptions if the superclass method does not declare any exceptions. If the superclass method declares an exception, the subclass method can declare the same exception, a subclass exception, or no exception at all. However, it cannot declare a broader exception than the superclass method.

115. Can you have virtual functions in Java?

Yes, Java supports virtual functions. By default, all non-static methods in Java are virtual and can be overridden unless they are declared as final.

116. What is Abstraction?

Abstraction is the concept of hiding the complex implementation details and showing only the essential features of an object. For example, when you drive a car, you do not need to understand the internal workings of the engine.

117. What is an Abstract class?

An abstract class is a class that cannot be instantiated and may contain abstract methods, which are methods without a body. If a class has at least one abstract method, it must be declared abstract.

Example:

// Java Program to implement an abstract method
abstract class Fruits {
    abstract void run();
}

class Apple extends Fruits {
    void run() {
        System.out.println("Abstract class example");
    }

    public static void main(String args[]) {
        Fruits obj = new Apple();
        obj.run();
    }
}

Output

Abstract class example

118. When are Abstract methods used?

Abstract methods are used when you want to define a method in a parent class but leave the implementation to the child classes.

119. How can you avoid serialization in the child class if the base class is implementing the Serializable interface?

To avoid serialization in the child class when the base class implements the Serializable interface, you can define the writeObject() method in the child class and throw a NotSerializableException.

120. What is the collection framework in Java?

The Collection Framework in Java is a set of classes and interfaces that provide various ways to store and manipulate groups of objects. It includes classes like ArrayList, Vector, LinkedList, PriorityQueue, and TreeSet, as well as interfaces such as Set, List, Queue, and Deque. Each interface is designed to handle a specific type of data structure.

121. Explain various interfaces used in the ollection framework.

The Collection Framework in Java includes several key interfaces:

  • Collection Interface: The root interface for most collection classes.
  • List Interface: Represents an ordered collection (also known as a sequence).
  • Set Interface: Represents a collection that does not allow duplicate elements.
  • Queue Interface: Represents a collection designed for holding elements prior to processing.
  • Deque Interface: Represents a double-ended queue that allows element insertion and removal at both ends.
  • Map Interface: Represents a collection of key-value pairs.

Collection Interface Syntax: public interface Collection<E> extends Iterable<E>

122. How can you synchronize an ArrayList in Java?

An ArrayList can be synchronized using two methods:

  1. Using Collections.synchronizedList()

public static List<T> synchronizedList(List<T> list

  1. Using CopyOnWriteArrayList:
  • Create an empty list.
  • It implements the List interface.

It is a thread-safe variant of ArrayList.

123. Why do we need a synchronized ArrayList when we have Vectors (which are synchronized) in Java?

  • Despite having Vector, a synchronized ArrayList is still needed because:
  • ArrayList is faster than Vector.
  • ArrayList supports multithreading, whereas Vector supports only single-threaded use.
  • ArrayList is safer to use in a multithreaded environment, as Vector operations are less safe and take longer to synchronize.
  • Vector is considered outdated due to its synchronized nature.

124. Why can’t we create a generic array?

Creating generic arrays is not allowed because arrays carry type information of their elements at runtime. This can lead to ArrayStoreException if the elements’ types do not match. Since generics’ type information is erased at compile time (Type Erasure), the array store check would pass when it should fail.

125. How are elements stored in memory for both regular arrays and ArrayLists in Java?

  • Regular Arrays: Elements are stored in contiguous memory locations, allowing easy access by index.
  • ArrayLists: Elements are also stored in contiguous memory locations. When an ArrayList exceeds its capacity, a new, larger array is created, and the elements are copied to this new array, allowing the ArrayList to grow dynamically.

126. Explain the method to convert ArrayList to Array and Array to ArrayList.

Conversion of Array to ArrayList:

  • Use the asList() method of the Arrays class.
List<String> list = Arrays.asList(array);

Example:

String[] array = { "Abc", "Def", "Ghi", "Jkl" };
List<String> list = Arrays.asList(array);
System.out.println(list);

Output:

[Abc, Def, Ghi, Jkl]

Conversion of ArrayList to Array:

  • Use the toArray() method.
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Object[] array = list.toArray();

Example:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Object[] array = list.toArray();
for (Object obj : array) {
    System.out.print(obj + " ");
}

Output

1 2 3

127. How does the size of ArrayList grow dynamically? How is it implemented internally?

An ArrayList grows dynamically to ensure there is always enough room for new elements. Initially, it has a default capacity (typically 10-16 elements). When this capacity is exceeded, a new, larger array is created, and the elements are copied to this new array. This process, known as resizing, allows the ArrayList to grow dynamically.

128. What is a Vector in Java?

A Vector in Java is similar to an ArrayList but is synchronized. It can store multiple elements and follows these rules:

  • Imported using java.util.Vector.
  • Implemented using a dynamic array, with size increasing or decreasing based on the number of elements.
  • Elements are accessed using index numbers.
  • Synchronized, meaning it supports single-threaded operations.
  • Contains methods not part of the collections framework.

Syntax:

Vector<E> vector = new Vector<>(size, increment);

129. What is the syntax to make a Java ArrayList Read-Only?

The syntax to ake to make a Java ArrayList Read-Only is:

List<T> readOnlyList = Collections.unmodifiableList(arrayList);

130. What is a priority queue in Java?

A priority queue is an abstract data type similar to a regular queue or stack, but where each element has a priority. Elements are dequeued in order of their priority, from lowest to highest. The PriorityQueue class in Java is based on a priority heap.

Syntax:

import java.util.*;

class PriorityQueueDemo {
    public static void main(String[] args) {
        // Creating an empty priority queue
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        // Adding items to the priority queue
        pq.add(10);
        pq.add(20);
        pq.add(15);
        // Printing the top element of the priority queue
        System.out.println(pq.peek());
    }
}

Output

10

131. Explain the LinkedList Class.

The LinkedList class in Java uses a doubly linked list to store elements. It extends the AbstractList class and implements the List and Deque interfaces. Key properties of the LinkedList class include:

  • Non-synchronized.
  • Maintains insertion order.
  • Can be used as a list, stack, or queue.

Syntax:

LinkedList<ClassType> listName = new LinkedList<>();

132. What is the Stack Class in Java and What Are the Various Methods Provided by It?

The Stack class in Java represents a Last-In-First-Out (LIFO) data structure. It extends the Vector class and includes methods specific to stack operations:

  • peek(): Returns the top item without removing it.
  • empty(): Checks if the stack is empty.
  • push(): Adds an item to the top of the stack.
  • pop(): Removes and returns the top item.
  • search(): Returns the 1-based position of an object from the top of the stack, or -1 if the object is not found.

133. What is a Set in the Java Collections Framework and List Down Its Various Implementations?

A Set is a collection that does not allow duplicate elements and does not maintain any specific order. The Java Collections Framework provides several implementations of the Set interface:

  • HashSet: Stores elements in a hash table, providing fast lookups and insertions. It does not maintain any order.
  • LinkedHashSet: An implementation of HashSet that maintains the insertion order of elements.
  • TreeSet: Stores elements in a sorted order, either by their natural ordering or by a custom comparator provided at the time of creation.

134. What is the HashSet class in Java and how does it store elements?

The HashSet class in Java is part of the Java Collections Framework and implements the Set interface. It stores a collection of unique elements, meaning no duplicates are allowed. Each element is mapped to an index in an array using a hash function, which allows for quick access. The hash function generates an index based on the element’s value, and this index is used to store the element in the array. Assuming the hash function distributes elements evenly, the HashSet class provides constant-time performance for basic operations like adding, removing, and checking for elements.

135. What is LinkedHashSet in the Java Collections Framework?

LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked list across all elements. This ensures that the iteration order is the same as the insertion order, making it useful when the order of elements is important.

Syntax:

LinkedHashSet<E> hs = new LinkedHashSet<E>();

Example:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Declare a LinkedHashSet
        LinkedHashSet<Integer> hs = new LinkedHashSet<>();
        // Add elements to the LinkedHashSet
        hs.add(1);
        hs.add(2);
        hs.add(5);
        hs.add(3);
        // Print the values
        System.out.println("Values: " + hs);
    }
}

Output

Values: [1, 2, 5, 3]

136. What is a Map interface in Java?

The Map interface in Java is part of the Java Collections Framework and is used to map keys to values. Each key can map to at most one value, and all keys must be unique. The Map interface provides methods for adding, removing, and accessing elements based on their keys.

There are several types of maps in the Map interface, including:

  • SortedMap
  • TreeMap
  • HashMap
  • LinkedHashMap

137. Explain TreeMap in Java

TreeMap is a type of map that stores data in key-value pairs and is implemented using a red-black tree. Key features of TreeMap include:

  • Only unique elements are allowed.
  • It does not allow a null key.
  • It can have multiple null values.
  • It is not synchronized.
  • It maintains elements in ascending order.

138. What is EnumSet?

EnumSet is a specialized implementation of the Set interface designed for use with enumeration types. Key features of EnumSet include:

  • It is not synchronized.
  • It is faster than HashSet.
  • All elements must come from a single enumeration type.
  • It does not allow null elements and throws NullPointerException if a null element is added.
  • It uses a fail-safe iterator.

Syntax:

public abstract class EnumSet<E extends Enum<E>>

139. What is BlockingQueue?

A BlockingQueue is a type of queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element. 

Syntax:

public interface BlockingQueue<E> extends Queue<E>

140. What is ConcurrentHashMap in Java and how is it implemented?

ConcurrentHashMap is a thread-safe implementation of the Map interface. It is implemented using a hash table and provides concurrent access to its elements.

Syntax:

public class ConcurrentHashMap<K, V> 
    extends AbstractMap<K, V> 
    implements ConcurrentMap<K, V>, Serializable

141. Can you use any class as a Map key?

Yes, any class can be used as a Map key if it adheres to certain rules:

  • The class must override the equals() method.
  • The class must also override the hashCode() method.
  • ConcurrentHashMap is thread-safe.
  • The default concurrency level of ConcurrentHashMap is 16.
  • null keys and values are not allowed in ConcurrentHashMap.

142. What is an Iterator?

The Iterator interface provides methods to iterate over any collection in Java. It replaces the older Enumeration interface in the Java Collections Framework. An iterator can be obtained from a collection using the iterator() method and allows the caller to remove elements from the underlying collection during the iteration.

143. What is an Enumeration?

An enumeration is a user-defined data type that assigns names to integral constants, making a program easier to read and maintain. The main purpose of an enum is to define a set of named values.

Example:

enum Color {
    RED, GREEN, BLUE;
}

144. What is the difference between Collection and Collections?

Collection Collections
It is an Interface. It is a utility class.
Provides standard functionality for data structures. Provides static methods for sorting, synchronizing, and other operations on collections.
Defines methods for data structure manipulation. Contains static methods for various operations on collections.

145. What is the difference between Array and ArrayList in Java?

Array ArrayList
Fixed size Dynamic size
Elements stored in contiguous memory locations. Elements not necessarily stored contiguously.
Can store both objects and primitive data types. Can only store objects.
Manual resizing required. Automatic resizing.
Basic methods for manipulation. Advanced methods for manipulation and iteration.
Available since the beginning of Java. Introduced in Java 1.2.

146. What is the difference between ArrayList and LinkedList?

ArrayList LinkedList
Implemented as an expandable array. Implemented as a doubly-linked list.
Elements stored in contiguous memory locations. Elements stored in non-contiguous memory locations.
Faster for random access. Faster for insertion and deletion.
More memory efficient. Less memory efficient.
Uses more memory due to maintaining array size. Uses less memory as it only has references to elements.
Faster search operations. Slower search operations.

147. What is the difference between ArrayList and Vector in Java?

ArrayList Vector
Implemented as a resizable array. Implemented as a synchronized, resizable array.
Not synchronized. Synchronized.
Faster for non-concurrent operations. Slower for non-concurrent operations due to synchronization overhead.
Introduced in Java 1.2. Introduced in JDK 1.0.
Recommended for single-threaded environments. Recommended for multi-threaded environments.
Default initial capacity is 10. Default initial capacity is 10, with the default increment being twice the size.
High performance. Lower performance.

148. What is the difference between Iterator and ListIterator?

Iterator ListIterator
Can traverse elements in a collection only in the forward direction. Can traverse elements in both forward and backward directions.
Used to traverse Map, List, and Set. Can only traverse List.
Cannot obtain indexes. Has methods like nextIndex() and previousIndex() to obtain indexes.
Cannot modify or replace elements. Can modify or replace elements using set(E e).
Cannot add elements and throws ConcurrentModificationException. Can add elements to a collection at any time.
Methods include next(), remove(), and hasNext(). Methods include next(), previous(), hasNext(), hasPrevious(), and add(E e).

149. What is the difference between HashMap and HashTable?

HashMap HashTable
Not synchronized. Synchronized.
Allows one null key. Does not allow null keys.
Uses an iterator for traversal. Can use both Iterator and Enumeration.
Faster. Slower compared to HashMap.

150. What is the difference between Iterator and Enumeration?

Iterator Enumeration
Can traverse both legacy and non-legacy elements. Can traverse only legacy elements.
Fail-fast. Not fail-fast.
Slower. Faster.
Can perform remove operations while traversing. Can only perform traversal operations.
Pointer image icon

Conclusion

A solid understanding of Java concepts, regulaly practicing Java coding problems, and a godd grasp of common design patterns are key to cracking your Java interview. The questions and answers and coding examples in this blog will help you prepare for your Java interview as a fresher. Of course, these questions are not all that could be asked by your interviewers. Remember to stay updated with the latest happening in the Java community. Most importantly, be sure that you find jobs that align with your skillset and offer competitive compensation packages. Sign up with Olibr now to learn more! 

Take control of your career and land your dream job

Sign up with us now and start applying for the best opportunities!

FAQs

Yes. Learning languages such as Python, JavaScript, C#, Golang, Kotlin, Rust, and SQL would broaden your prospects of getting a good job.
JavaScript is essential for web development. Combining Java for backend development with JavaScript for frontend development makes you a full-stack developer.
Some profiles you can apply for include Junior Java Developer, Java Web Developer, Java Mobile Developer, Java Data Engineer, and Java Game Developer.
The starting salary for a Java developer in India typically ranges from INR 2.5 to 5 lakhs per annum in India and $55,100 to $66,945 per year in the US.

You may also like

Leave a Comment