Open In App

Java Core Concepts Interview Questions

Last Updated : 11 Dec, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report

Java is one of the most popular programming languages, known for its simplicity and versatility. Mastering its core concepts is essential for any aspiring developer.

The following questions cover fundamental topics frequently asked in interviews to help you prepare effectively

1. What is a Variable in Java?

A variable is a container that stores data, which can be used and manipulated by a program.

  • It has a name, type, and value.
  • Variables are stored in memory during program execution.
Java
int age = 25;
String name = "Vishnu";

2. Differentiate 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.

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

In Java When we haven’t initialized the instance variables then the compiler initializes them with default values. The default values for instances and variables depend on their data types. Some common types of default data types are:

  • The default value for numeric types (byte, short, int, long, float, and double) is 0.
  • The default value for the boolean type is false.
  • The default value for object types (classes, interfaces, and arrays) is null.
  • The null character, "u0000, " is the default value for the char type.

Example:

Java
// 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 value0
short value0
int value0
long value0
boolean valuefalse
char value
float value0.0
double value0.0
string valuenull
object valuenull
Array valuenull

4. What is a Class Variable?

In Java, a class variable (also known as a static variable) is a variable that is declared within a class but outside of any method, constructor, or block. Class variables are declared with the static keyword, and they are shared by all instances (objects) of the class as well as by the class itself. No matter how many objects are derived from a class, each class variable would only exist once.

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

There is no default value stored with local variables. Also, primitive variables and objects don't have any default values.

6. Explain the difference between instance variable and a class variable.

Instance Variable: A class variable without the static modifier is called an instance variable. It is unique to each object (instance) of the class and is not shared between instances.

Java
// 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:  Class Variable variable can be declared anywhere at the class level using the keyword static. These variables can only have one value when applied to various objects. These variables can be shared by all class members since they are not connected to any specific object of the class.

Java
// 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

7. What is a static variable?

A static variable is a variable that belongs to the class rather than to any particular object of the class. It is declared using the static keyword inside a class but outside any method, constructor, or block.

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

FeatureSystem.outSystem.errSystem.in
PurposeUsed to display standard output (normal program output)Used to display error messagesUsed to take input from the user (keyboard)
TypePrintStreamPrintStreamInputStream
Output StreamWrites to console (stdout)Writes to console (stderr)Reads from console (stdin)
Typical Use CaseSystem.out.println("Hello")System.err.println("Error occurred")Scanner sc = new Scanner(System.in)
RedirectionCan be redirected to a file or another output streamCan be redirected separately from standard outputCan be redirected from a file or input stream

9. What is Java String Pool?

A Java String Pool is a place in heap memory where all the strings defined in the program are stored. A separate place in a stack is there where the variable storing the string is stored. Whenever we create a new string object, JVM checks for the presence of the object in the String pool, If String is available in the pool, the same object reference is shared with the variable, else a new object is created.

Java-String-Pool-768
Java String Pool

10. What do you understand by an IO stream?

2-768
Java Application

Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all types of objects, data types, characters, files, etc to fully execute the I/O operations.

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

FeatureReader/Writer HierarchyInputStream/OutputStream Hierarchy
Type of DataCharacter-oriented (text data)Byte-oriented (binary data)
Base ClassesReader (abstract) and Writer (abstract)InputStream (abstract) and OutputStream (abstract)
Data UnitWorks with 16-bit Unicode charactersWorks with 8-bit bytes
Use CaseReading/writing text files, strings, charactersReading/writing binary files, images, audio, etc.
Encoding HandlingSupports character encoding (Unicode, UTF-8, etc.)No encoding/decoding, raw bytes only

Example:

Java
// Java Program to demonstrate Reading 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 

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

In Java’s I/O system, the topmost (super) classes for all streams are:

  • InputStream - Superclass of all byte-oriented input streams.
  • OutputStream - Superclass of all byte-oriented output streams.
  • Reader - Superclass of all character-oriented input streams.
  • Writer - Superclass of all character-oriented output streams

13. What are the FileInputStream and FileOutputStream?

To read and write data, Java offers I/O Streams. A Stream represents an input source or an output destination, which could be a file, an i/o device, another program, etc. FileInputStream in Java is used to read data from a file as a stream of bytes. It is mostly used for reading binary data such as images, audio files, or serialized objects. 

Example:

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

In Java, the FileOutputStream function is used to write data byte by byte into a given file or file descriptor. Usually, raw byte data, such as pictures, is written into a file using FileOutputStream.

Example:

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

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

When we are working with the files or stream then to increase the Input/Output performance of the program we need to use the BufferedInputStream and BufferedOutputStream classes. These both classes provide the capability of buffering which means that the data will be stored in a buffer before writing to a file or reading it from a stream. It also reduces the number of times our OS needs to interact with the network or the disk. Buffering allows programs to write a big amount of data instead of writing it in small chunks. This also reduces the overhead of accessing the network or the disk. 

BufferedInputStream(InputStream inp);
// used to create the bufferinput stream and save the arguments.

BufferedOutputStream(OutputStream output);
// used to create a new buffer with the default size.

15. What are FilterStreams?

Stream filter or Filter Streams returns a stream consisting of the elements of this stream that match the given predicate. While working filter() it doesn't actually perform filtering but instead creates a new stream that, when traversed, contains the elements of initial streams that match the given predicate.

Example:

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

16. What is an I/O filter?

An I/O filter also defined as an Input Output filter is an object that reads from one stream and writes data to input and output sources. It used java.io package to use this filter.

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

There are two methods to take input from the console in Java mentioned below:

  1. Using Command line argument
  2. Using Buffered Reader Class
  3. Using Console Class
  4. Using Scanner Class

The program demonstrating the use of each method is given below.

Example 1:

Java
import java.io.*;
import java.util.*;

public class ConsoleInputExample {
    public static void main(String[] args) throws Exception {
        // 1. Using Scanner
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name (Scanner): ");
        String name1 = sc.nextLine();
        
        // 2. Using BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your age (BufferedReader): ");
        int age = Integer.parseInt(br.readLine());
        
        // 3. Using Console (may return null in IDEs, works in terminal)
        Console console = System.console();
        String name2 = "N/A";
        if (console != null) {
            name2 = console.readLine("Enter your city (Console): ");
        }
        
        // 4. Using DataInputStream (deprecated style, just for example)
        DataInputStream dis = new DataInputStream(System.in);
        System.out.print("Enter your country (DataInputStream): ");
        String country = dis.readLine(); // readLine() is deprecated
        
        // Displaying collected input
        System.out.println("\n--- User Input Summary ---");
        System.out.println("Name (Scanner): " + name1);
        System.out.println("Age (BufferedReader): " + age);
        System.out.println("City (Console): " + name2);
        System.out.println("Country (DataInputStream): " + country);
    }
}
  • Scanner: Easy and widely used.
  • BufferedReader: Faster for reading large text input.
  • Console: Useful for secure input (like passwords).
  • DataInputStream: Outdated, but still possible.

18. Difference in the use of print, println, and printf.

MethodDescriptionLine BreakUse Case
print()Prints the text/data as it is.No newline (cursor stays on the same line).When you want to continue output on the same line.
println()Prints the text/data and then moves cursor to the next line.Yes, adds newline.When you want each output on a new line.
printf()Prints formatted text (like C’s printf). Supports format specifiers (%d, %s, %.2f, etc.).No automatic newline unless specified (%n).When you need formatted output (numbers, strings, decimals).

Example:

Java
public class PrintExample {
    public static void main(String[] args) {
        // Using print()
        System.out.print("Hello ");
        System.out.print("World");


        System.out.println(); // just adds newline

        // Using println()
        System.out.println("Hello");
        System.out.println("World");

        // Using printf()
        int age = 22;
        double marks = 85.6789;
        String name = "abcd";

        System.out.printf("Name: %s, Age: %d, Marks: %.2f%n", name, age, marks);

    }
}

19. What are operators? 

Operators are the special types of symbols used for performing some operations over variables and values.

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

All types of operators in Java are mentioned below:

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operators
  9. instance of operator

Postfix operators are considered as the highest precedence according to Java operator precedence.

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

Operators like >> and >>> seem to be the same but act a bit differently. >> operator shifts the sign bits and the >>> operator is used in shifting out the zero-filled bits.

Java
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

22. Which Java operator is right associative?

There is only one operator which is right associative which is = operator.

23. What is 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 the package.

24. What are Data Types in Java?

Data types in Java define what kind of data a variable can hold. They tell the compiler how much memory to allocate and what operations can be performed on the variable.

25. Explain different data types in Java

There are 2 types of data types in Java as mentioned below:

1. Primitive Data Type: Primitive data are single values with no special capabilities. There are 8 primitive data types:

  • boolean: stores value true or false
  • 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
  • double: stores a double-precision 64-bit IEEE 754 floating-point

2. Non-Primitive Data Type: Reference Data types will contain a memory address of the variable's values because it is not able to directly store the values in the memory. Types of Non-Primitive are mentioned below:

  • Strings
  • Array
  • Class
  • Object
  • Interface

26. When a byte datatype is used?

A byte is an 8-bit signed two-complement integer. The minimum value supported by bytes is -128 and 127 is the maximum value. It is used in conditions where we need to save memory and the limit of numbers needed is between -128 to 127.

27. What is the default value of byte datatype in Java?

The default value of the byte datatype in Java is 0.

28. What is the default value of float and double datatype in Java?

The default value of the float is 0.0f and of double is 0.0d in Java.

29. What is the Wrapper class in Java?

A Wrapper Class in Java is a class that wraps (encapsulates) a primitive data type into an object. Since Java is object-oriented, wrapper classes allow primitives to be used where objects are required, like in Collections (ArrayList, HashMap, etc.).

PrimitiveWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

30. Why do we need wrapper classes?

The wrapper class is an object class that encapsulates the primitive data types, and we need them for the following reasons:

  • Wrapper classes are final and immutable
  • Provides methods like valueOf(), parseInt(), etc.
  • It provides the feature of autoboxing and unboxing.

31. What is autoboxing and unboxing?

Autoboxing: Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class object.

Example: converting int to Integer, double to Double, etc.

int num = 10;
Integer boxedNum = num; // Autoboxing happens here

Before Java 5, you would need to manually do this:

Integer boxedNum = Integer.valueOf(num);

Unboxing: Autoboxing and unboxing reduce boilerplate code. Can happen implicitly in expressions, assignments, and method calls.

Example with a collection:

List<Integer> numbers = new ArrayList<>();
numbers.add(5); // Autoboxing: int → Integer
int n = numbers.get(0); // Unboxing: Integer → int

32. What is covariant return type?

In method overriding, a subclass method can return a type that is a subclass of the parent method’s return type.

33. What is the transient keyword?

The transient keyword is used at the time of serialization if we don’t want to save the value of a particular variable in a file. When JVM comes across a transient keyword, it ignores the original value of the variable and saves the default value of that variable data type

34. What is a String in Java?

A String is an object in Java that represents a sequence of characters. Strings are immutable, meaning once created, their value cannot be changed.

String s = "Hello";

35. What does it mean that Strings are immutable?

Once a String object is created, it cannot be modified. Any operation that seems to modify a String creates a new String object.

String s1 = "Hello";
String s2 = s1.concat(" World"); // s1 remains "Hello"

36. What are the differences between String and StringBuffer?

String

StringBuffer

Store of a sequence of characters.            Provides functionality to work with the strings.
It is immutable.It is mutable (can be modified and other string operations could be performed on them.)
No thread operations in a string.                                                           It is thread-safe (two threads can't call the methods of StringBuffer simultaneously) 

37. What are the differences between StringBuffer and StringBuilder?

StringBuffer

StringBuilder

StringBuffer provides functionality to work with the strings.StringBuilder is a class used to build a mutable string.
It is thread-safe (two threads can't call the methods of StringBuffer simultaneously)It is not thread-safe (two threads can call the methods concurrently)
Comparatively slow as it is synchronized.Being non-synchronized, implementation is faster

38. Why is StringBuffer called mutable?

StringBuffer class in Java is used to represent a changeable string of characters. It offers an alternative to the immutable String class by enabling you to change a string's contents without constantly creating new objects. Mutable (modifiable) strings are created with the help of the StringBuffer class. The StringBuffer class in Java is identical to the String class except that it is changeable.

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

Output
GeeksforGeeks

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

String using new() is different from the literal as when we declare string it stores the elements inside the stack memory whereas when it is declared using new() it allocates a dynamic memory in the heap memory. The object gets created in the heap memory even if the same content object is present.

Syntax:

String x = new String("ABC");

String

40. Difference between == and .equals() for Strings

  • == -> compares references (memory addresses).
  • .equals() -> compares actual content of the String.

String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // true (same String pool object)
System.out.println(s1.equals(s2)); // true (same content)

41. What is an array in Java?

An Array in Java is a data structure that is used to store a fixed-size sequence of elements of the same type. Elements of an array can be accessed by their index, which starts from 0 and goes up to a length of minus 1.

42. On which memory arrays are created in Java?

In Java, arrays are always created in the Heap memory, regardless of whether:

  • They are declared inside a method (local variable)
  • They are declared as instance variables
  • They are declared as static variables

43. What are the types of an array?

There are two types of arrays i.e., Primitive arrays and References Arrays.

1. Single-Dimensional Arrays: Arrays that have only one dimension i.e., an array of integers or an array of strings are known as single-dimensional arrays.

Syntax:

data_type[] Array_Name = new data_type[ArraySize];

arr

2. Multi-Dimensional Arrays: Arrays that have two or more dimensions such as two-dimensional or three-dimensional arrays.

data_type[][] Array_Name = new data_type[][];

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

The index of an array signifies the distance from the start of the array. So, the first element has 0 distance therefore the starting index is 0.

Syntax:

[Base Address + (index * no_of_bytes)]

45. 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 only difference between them is on their syntax no functionality difference is present between them.

int arr[] is a C-Style syntax to declare an Array.

int[] arr is a Java-Style syntax to declare an Array.

However, it is generally recommended to use Java-style syntax to declare an Array. As it is easy to read and understand also it is more consistent with other Java language constructs.

46. How to copy an array in Java?

In Java, there are multiple ways to copy an array based on the requirements:

1. clone() Method (Shallow Copy)

  • The clone() method creates a new array with its own memory but contains references to the same objects for non-primitive data types.
  • For primitive arrays, it behaves like a deep copy since primitive values are directly copied.

int[] arr = {1, 2, 3, 5, 0};
int[] tempArr = arr.clone(); // Creates a new array with copied values

2. System.arraycopy() Method (Deep Copy)

  • This method creates a new array and copies elements from the original array.
  • It allows partial copying by specifying an offset and length.

int[] arr = {1, 2, 7, 9, 8};
int[] tempArr = new int[arr.length];
System.arraycopy(arr, 0, tempArr, 0, arr.length);

3. Arrays.copyOf() Method (Creates New Array)

  • This method creates a new array and copies the entire original array into it.
  • If the specified length is greater than the original array, extra elements are initialized with default values.

int[] arr = {1, 2, 4, 8};
int[] tempArr = Arrays.copyOf(arr, arr.length);

4. Arrays.copyOfRange() Method (Copying a Subset)

  • Similar to copyOf(), but allows copying a specific range of elements.

int[] arr = {1, 2, 4, 8};
int[] tempArr = Arrays.copyOfRange(arr, 0, arr.length);

47. What do you understand by the jagged array?

In Java, a jagged array (also called a ragged array) is an array of arrays where each inner array can have a different length.

int[][] Arr = new int[][] {

{1, 2, 8},

{7, 5},

{6, 7, 2, 6}

};

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

The advantages of Arrays are:

  • Direct and effective access to any element in the collection is made possible by arrays. An array's elements can be accessed using an O(1) operation, which means that the amount of time needed to do so is constant and independent of the array's size.
  • Data can be stored effectively in memory using arrays. The size of an array is known at compile time since its elements are stored in contiguous memory regions.
  • Due to the fact that the data is stored in contiguous memory areas, arrays provide quick data retrieval.

Disadvantages of Arrays are:

  • Arrays are created with a predetermined size that is chosen at that moment. This means that if the array's size needs to be extended, a new array will need to be made, and the data will need to be copied from the old array to the new array, which can take a lot of time and memory.
  • There may be unused memory space in an array's memory space if the array is not completely occupied. If you have poor recall, this can be a problem.
  • Compared to other data structures like linked lists and trees, arrays might be rigid due to their fixed size and limited support for sophisticated data types.

Explore