Open In App

Java Basics & Program Flow Interview Questions

Last Updated : 28 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Java is an object-oriented programming language used widely in enterprise applications android development and backend systems. Understanding Java fundamentals is essential for clearing interviews and building a strong programming foundation.

1. Is Java Platform Independent? If yes, how?

Yes, Java is a platform-independent language. Unlike many programming languages, the Java compiler (javac) compiles a program into bytecode (a .class file). This bytecode is not tied to any specific hardware or operating system but requires a Java Virtual Machine (JVM) to execute.

Although the JVM itself is platform-dependent, bytecode generated on one system can run on any other system that has a compatible JVM installed. This is what makes Java platform independent.

2. Difference between JVM, JRE and JDK.

  • JVM: JVM also known as Java Virtual Machine is a part of JRE. JVM is a type of interpreter responsible for converting bytecode into machine-readable code. JVM itself is platform dependent but it interprets the bytecode which is the platform-independent reason why Java is platform-independent. 
  • JRE: JRE stands for Java Runtime Environment, it is an installation package that provides an environment to run the Java program or application on any machine.
  • JDK: JDK stands for Java Development Kit which provides the environment to develop and execute Java programs. JDK is a package that includes two things Development Tools to provide an environment to develop your Java programs and, JRE to execute Java programs or applications.

To know more about the topic refer to the Differences between JVM, JRE and JDK.

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

FeatureJavaC++
Platform DependencyPlatform-independent (runs on JVM – “Write Once, Run Anywhere”).Platform-dependent (compiled to machine code, must recompile for each OS).
Memory ManagementAutomatic Garbage Collection (no need to explicitly free memory).Manual memory management using delete / destructors.
Object-Oriented ApproachPurely object-oriented (everything is a class, except primitives).Object-oriented but also supports procedural programming.
Multiple InheritanceNot supported with classes (handled using interfaces).Supported directly with classes.
PointersNo direct pointer support (references are used instead).Supports pointers explicitly.
Operator OverloadingNot supported.Supported.
Templates / GenericsSupports generics (type-safe, but less powerful than C++ templates).Supports templates (very powerful, can be used for metaprogramming).
Execution SpeedSlower than C++ (JVM overhead).Faster (closer to hardware, compiled directly).
Exception HandlingChecked and unchecked exceptions, must handle or declare checked exceptions.Exception handling exists but without checked exceptions.
Use CasesEnterprise apps, Android apps, web applications, distributed systems.System programming, game engines, high-performance apps, device drivers.

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

Main_function
main function in java

Unlike any other programming language like C, C++, etc. In Java, we declared the main function as a public static void main (String args[]). The meanings of the terms are mentioned below:

  1. public: the public is the access modifier responsible for mentioning who can access the element or the method and what is the limit.  It is responsible for making the main function globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.
  2. static: static is a keyword used so that we can use the element without initiating the class so to avoid the unnecessary allocation of the memory. 
  3. void: void is a keyword and is used to specify that a method doesn’t return anything. As the main function doesn't return anything we use void.
  4. main: main represents that the function declared is the main function. It helps JVM to identify that the declared function is the main function.
  5. String args[]: It stores Java command-line arguments and is an array of type java.lang.String class.

5. What will happen if we don’t declare the main method as static?

  • The main method in Java is declared as public static void main(String[] args) because the JVM needs to call it without creating an object.
  • If the main method is not static, it becomes an instance method, and the JVM cannot call it directly since no object exists at the start of execution.
  • The code will compile successfully, but at runtime, the JVM will throw an error like:

Error: Main method is not static in class Example, please define the main method as:

public static void main(String[] args)

6. What are Packages in Java, Why they used ?

Packages in Java can be defined as the grouping of related types of classes, interfaces, etc providing access to protection and namespace management. Packages are used in Java in order to prevent naming conflicts, control access and make searching/locating and usage of classes, interfaces, etc easier.

There are various reasons of using packages in Java.

  • Packages avoid name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and are used by the package.
  • It is easier to locate the related classes.

There are two types of packages in Java

  • User-defined packages
  • Built-in Packages

7. Does Java support pointers?

No, Java doesn't provide the support of Pointer. As Java needed to be more secure because which feature of the pointer is not provided in Java.

8. When is byte datatype used & What is its default value?

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.

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

9. What are Wrapper classes in Java & Why we need them?

A Wrapper classes encapsulate primitive data types (int, char, etc.). Java provides 8 built-in wrapper classes: Boolean, Byte, Short, Integer, Character, Long, Float and Double.

Why we need them:

  • They are immutable and final.
  • Provide useful methods like valueOf(), parseInt(), etc.
  • Support autoboxing (primitive -> object) and unboxing (object -> primitive).

10. Differentiate between instance and local, class variables & What are the default values assigned to variables and instances in Java?

1. Instance Variables

  • Declared inside a class but outside any method/constructor.
  • Belong to an object of the class (each object gets its own copy).
  • Accessed using object reference.
  • Default values: Assigned automatically (e.g., 0 for int, false for boolean, null for objects).

2. Local Variables

  • Declared inside a method, constructor, or block.
  • Exist only while the method is running (created when method is invoked, destroyed when method ends).
  • Must be explicitly initialized before use — they don’t get default values.
  • Belong only to the method scope.

3. Class (Static) Variables

  • Declared with the static keyword inside a class, but outside any method.
  • Shared by all objects of the class (only one copy exists in memory).
  • Can be accessed using the class name or object reference.
  • Default values: Same as instance variables (e.g., 0, false, null).

Default Values in Java

Data TypeDefault Value
byte, short, int, long0
float, double0.0
char'\u0000' (null character)
booleanfalse
Object referencesnull

11. 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

12. 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.

13. 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) 

14. What are the differences between StringBuffer and StringBuilder & Which one should be preferred when there are a lot of updates required to be done in the data?

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

15. Why is StringBuffer called mutable?

  • In Java, mutable means the content of an object can be changed after it is created.
  • StringBuffer is called mutable because you can modify the sequence of characters it holds without creating a new object in memory.
  • Operations like append(), insert(), delete(), and replace() update the same object, instead of generating a new one.
Java
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

16. On which memory arrays are created in Java?

  • In Java, arrays are objects. Therefore, arrays are always created in the heap memory, regardless of whether they are declared inside a method or as a member of a class.
  • The reference to the array (the variable name you use) may be stored in:
    • Stack memory, if it is a local variable inside a method.
    • Heap memory, if it is an instance variable of an object.
    • Method Area / Class area, if it is a static variable.

17. 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);

18. What is a static variable?

The static keyword is used to share the same variable or method of a given class. Static variables are the variables that once declared then a single copy of the variable is created and shared among all objects at the class level.

19. 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.


Explore