33 Java Interview Questions for Beginners in 2021: Part – 1

33 Java Interview Questions for Beginners in 2021: Part - 1
33 Java Interview Questions for Beginners in 2021: Part - 1

Introduction

The Java programming language created by James Gosling in the early 1990s is one of the most popular programming languages. No wonder Java is the second most demanded programming language with around 70K job postings in January 2020, as per Indeed.com.

Over 90% of the Fortune 500 companies still rely on Java for their development projects, and globally there are over 8 million Java developers.

So if you get an interview call for a Java developer role and are looking for a quick guide before your interview, then you have come to the right place. The whole blog consists of 100 interview questions and is divided into three parts: Beginner, Intermediate and Advanced.

This blog is Part 1 of the Java Interview Questions and Answer Series covering beginner-level questions.

Java Interview Questions for Beginners

Question 1) What are the core features of Java?

Answer 1) Following are the main features of the Java programming language:

  • Platform-Independent: The java program is first compiled to the platform-independent bytecode. The byte code is distributed over the web, which the Java Virtual Machine then interprets.
  • Object-Oriented: Java supports the concepts of Object-Oriented Programming Language such as Inheritance, Encapsulation, Polymorphism, and Abstraction. 
  • Multi-threaded: Using multithreading in Java, it is possible to write programs that can deal with many tasks concurrently. All the threads share a shared memory area.
  • Secured: Java is one of the most secure programming languages, as the java programs run inside a virtual machine (called a sandbox). Java does not support explicit pointers. In addition, the bytecode verifier is responsible for checking the code fragments for illegal code that can violate access rights to objects.

You may also mention that Java is a high-performance and robust programming language.

Question 2) Is Java a compiled or an interpreted language?

Answer 2) Java is considered as both a compiled and interpreted language. The javac compiler first compiles the .java program. A class file (.class) is generated, which contains the binary byte code. The byte code is then interpreted by the Java Virtual Machine(JVM), which is  a software-based interpreter. 

The use of compiled byte code allows the JVM to be nearly as fast as the CPU running native compiled code.

Question 4) What is the difference between classes and interfaces in Java?

Answer 4) A class in Java is a blueprint that includes all the data. It represents the set of properties or methods that are common to all objects of one type. In general, a class declaration has the following components:- Modifiers, Class Name, and the body of the class.

A class contains variable declarations, constructors, and methods. A class is created using the keyword class.

An interface is a blueprint of the class. It also contains methods and variables, but the methods should always be abstract, and the variables should always be static and final. Interfaces do not support constructors. An interface is created using the keyword interface.

Question 5) Can you save a Java program by .java only?

Answer 5) Yes, it is possible to save a Java program by .java only. The program can be compiled by javac.java and run by java classname.

The program will be compiled by javac .java and run by java Demo.

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

Answer 6) JDK or Java Development Kit is a software development kit used to develop Java applications. It comprises JRE, JavaDoc, compiler, debuggers. JDK is equivalent to JRE + Development Tools.

JRE or Java Runtime Environment is a software package providing Java class libraries and JVM and other components to run applications written in Java programming language. JRE is equivalent to JVM + Libraries to execute the Java application.

JVM or Java Virtual Machine is an abstract machine that is platform-independent and comprises of three specifications:-

  • The document describing the JVM implementation requirements
  • Computer program meeting the JVM requirements.
  • Instance object for executing the Java  byte code

JVM is equivalent to the runtime environment to execute Java byte code.

Question 7) Explain public static void main(String[] args) in Java?

Answer 6) The entry point of the Java programs or the point at which the program starts execution is the main() Method,

Every word in the main method declaration has a meaning to the JVM.

  1. public -> It is an access modifier. As the main Method is public, it means that it can be accessed globally. 
  2. static -> static is a keyword in Java. Since the main method is static, the JVM can invoke it without instantiating the class.
  3. void -> It is a keyword in Java. The main Method is void, which means that the method does not return anything. Also, the Java program stops execution as and when the main Method terminates, so there is no sense to return anything from the main() Method.
  4. main -> It is the name of the Method. When a Java program is being executed, JVM looks for the main Method as the starting point.
  5. String[] args-> It stores Java command line arguments. It is an array of type java.lang.String class.

Question 8) What is the difference between the equals() method and equality operator(==) in Java?

Answer 8) equals() Method checks the equality of contents between two objects as per the logic specified. The default implementation of equals() Method uses the == operator to compare two objects, and the equal Method can, however, be overridden in the class.

The == operator is a binary operator for comparing the addresses or references. It checks whether the two objects are pointing to the same memory location or not.

Question 9) What are instance variables and static variables?

Answer 9) The variables declared inside a class but outside a method, constructor, or block of code are called instance variables. They are created when an object is created using the new keyword and destroyed when the object is destroyed. They can be accessed directly within the class, but within static methods, they are accessed using the fully qualified name, Object.VariableName.

Static variables or Class variables are declared in a class with the static keyword outside a method, constructor, or block of code. They are created when the program starts execution and are destroyed when the program stops executing.

In simple words, the instance variables belong to the object whereas static variables belong to the class. Static variables can be used without instantiating the object of the class.

The below program demonstrates how to access static and instance variables inside the main Method.

public class Demo{
        
     // Instance Variable
     int a = 10;
     
     // Static variable
     static int b = 20;
     
     public static void main(String []args){
        System.out.println("Java Interview Questions | Set 1");
        // Accessing Instance Variable using the object of a class
        Demo obj = new Demo();
        System.out.println("Value of instance variable: " + obj.a);
        
        // Accessing Instance variable using the class name
        System.out.println("Value of static  variable: " + Demo.b);
        
     }
}

The output of the above program will be:

Java Interview Questions | Set 1
Value of instance variable: 10
Value of static variable: 20

Question 10) Explain the difference between static and non-static methods.

Answer 10) A static method also called the class method belongs to a class and not to an instance of that class. A static method can be called without the instance or object of the class. The static keyword must be used before the method name.

Every Method in Java without the static keyword preceding it is by default non-static. They can access any static method and variables without creating an instance of the object.

The below program illustrates how to invoke the static and non-static methods in Java.

public class Demo{
    
    // Static Method for the addition of two numbers
    public static int sum(int a, int b)
    {
        return a + b;
    }
    
    // Non static method for the multiplication of two numbers
    public int multiply(int a, int b, int c)
    {
        return a * b * c;
    }
    public static void main(String []args){
    System.out.println("Java Interview Questions | Set 1");
    
    // Calling the non-static method using the object of the class
    Demo obj = new Demo();
    int res = obj.multiply(10, 20, 30);
    System.out.println("Non-Static Method: " + res);

    // Calling the static method using the class name
    int result = Demo.sum(100, 200);
    System.out.println("Static Method: " + result);
    
    }
}

The output of the above program is:

Java Interview Questions | Set 1
Non-Static Method: 6000
Static Method: 300

Question 11) Why is the main method static?

Answer 11) The main Method is static so that the compiler can call it without creating any object. If the main() method is not static, then while calling the main Method JVM has to instantiate its class.

If the static modifier is not included in the main Method, then there will not be any compilation error, but upon runtime, NoSuchMethodError error will be thrown. The following program on runtime will give an error as shown below:

public class Demo {
    public void main(String args[]) {
      
      System.out.println("Java Interview Questions");
    }
}

Question 12) What is the default value of the local variables?

Answer 12) The local variables are not initialized to any default value in Java.In java it is mandatory to initialize local variables else it will result in compile-time errors.

Question 13) Can the static methods be overloaded?

Answer 13) Yes, the static methods can be overloaded. Two or more static methods with the same name but different input parameters can be there in a class, as illustrated in the following example.

public class Demo{
    
    // Static Method for the addition of two numbers
    public static int sum(int a, int b)
    {
        return a + b;
    }
    
    // Overloading the static method sum by passing three parameters
    public static int sum(int a, int b, int c)
    {
        return a + b + c;
    }
    public static void main(String []args){
    System.out.println("Java Interview Questions");

    // Calling the static method using the class name
    int result1 = Demo.sum(100, 200);
    System.out.println("Calling the sum() method by passing two parameters: " + result1);
    
    // Calling the overloaded method
    int result2 = Demo.sum(100, 200, 300);
    System.out.println("Calling the sum() method by passing three parameters: " + result2);
    }
}

The output of the above program will be:

Java Interview Questions
Calling the sum() method by passing two parameters: 300
Calling the sum() method by passing three parameters:  600

Question 14) Can the static methods be overridden?

Answer 14) Static methods cannot be overridden as Method overriding is based on dynamic binding at runtime, and the static methods are bonded using static binding at compile time.

Question 15) Can you write static public void instead of the public static void as the main method signature?

Answer 15) The general convention is to write the access specifier at the beginning of the method declaration. However, we can write static public void instead of public static void in the main method signature as well. The program will compile and run successfully.

Question 16) What are constructors in Java? How are they different from Methods in Java?

Answer 16) Constructors in Java are used to initialize an object’s state. A constructor is called implicitly when an instance of the class is created. If you do not specify a constructor for the class, the java compiler creates a default constructor itself.

The differences between constructor and methods in Java are summarized in the below table:

ConstructorMethod
They are used to initialize an object’s state and does not return any valueMethods are used to exhibit the functionality of an object and may or may not return any value.
A constructor is invoked implicitly when an instance of the class is created using the new keywordA method is invoked explicitly by the programmer as and when required.
A constructor cannot be inherited by the subclassesA method is inherited by the subclasses.

Question 17) Are strings mutable or immutable in Java?

Answer 17) Strings in Java are immutable. Once the string is declared using a string literal(“”), it cannot be modified. The reason is that once the strings are created, the strings are cached in the String Pool. String literals are shared among multiple clients accessing the same java program, so in order to provide security as the action of one user may affect the rest, hence strings are immutable.

Question 18) What are Packages in Java?

Answer 18) A package in Java is a group of related classes, interfaces, enumerations, and annotations that is used to provide access protection and namespace management.

There are two types of Packages in Java:

  1. Built-in Packages
  2. User-defined Packages

Question 19) What is the purpose of a default constructor?

Answer 19)  A constructor is called a default constructor when it does not have any parameters. The default constructor is generally used to initialize the variables of the class with the respective default values, i.e., null for objects, 0.0 for float and double, false for boolean, 0 for byte, short, int, and long.

Question 20) What platforms are supported by the Java programming language?

Answer 20) Java runs on almost all the major platforms, including Windows, Mac OS, various versions of Linux/UNIX.

Question 21) Can we make a constructor static?

Answer 21)  The static context (Method, block, or variable) belongs to the class, not to the object. If you want to invoke a member of a class before instantiating the class, you need to use static before it. A constructor is invoked implicitly or when the object is created. So there is no point in making a constructor static.

Also, if you try to make a constructor static, the compiler will show the compile error.

public class Demo {
     static Demo()
      {
          System.out.println("Static Constructor");
      }
      
    public static void main(String args[]) {
      
     Demo obj = new Demo();
    }
}

Question 22) What is constructor chaining?

Answer 22) Calling one constructor from another constructor of the same class with respect to the current class object is called constructor chaining. It is used when we want to invoke a number of constructors one after another using a single instance. The keywords this() and super() are used in constructor chaining.

The below program illustrates constructor chaining using this() keyword.

public class Demo{
   
   // Default Constructor
    Demo()
    {
        this("Coding Ninjas");
        System.out.println("Constructor with no parameters is called");

    }
    
    // Parameterized Constructor
    Demo(String str)
    {
        System.out.println("Constructor with String parameters called");
        System.out.println(str);
    }
    public static void main(String []args){
        System.out.println("Java Interview Questions");
        Demo obj = new Demo();
    }
}

The output of the above program will be:

Java Interview Questions
Constructor with String parameters called
Coding Ninjas
Constructor with no parameters is called

Question 23) What is the use of the final keyword in Java?

Answer 23) The final keyword in Java is used to define something as constant and represents the non-access modifier.

The below table illustrates the usage of the final keyword in variables, methods, and class.

VariableWhen a variable is declared as final, its value cannot be modified. If the value is not assigned to the final variable, then it can only be assigned using the constructor of the class.
MethodA final method cannot be overridden by the child classes.
ClassA final class cannot be inherited by other classes. However, the final class can extend other classes for usage.

Question 24) Explain the difference between error and exception?

Answer 24) Both errors and exceptions are the subclasses of the Java.lang.Throwable class. An error causes the termination of the program abnormally and occurs at runtime. Some of the examples of errors are system crash errors and out-of-memory errors.

Exceptions are the problems that can occur at runtime and compile time. It mainly occurs in the code written by the developers.  Exceptions are divided into two categories such as checked exceptions and unchecked exceptions

Example of Error:

public class Demo 
{
    public static void testMethod(int i)
    {
        if(i == 0){
            return;
        }
        else{
            testMethod(i++);
        }
    }
    public static void main(String args[]) 
    {
        Demo.testMethod(18);
        
    }
}

The above program on runtime will give the following error

Example of Exception

public class Demo 
{
    public static void testMethod(int i, int j)
    {
       try{
           int k = i/j;
       } 
       catch (ArithmeticException e){
           e.printStackTrace();
       }
    }
    public static void main(String args[]) 
    {
        Demo.testMethod(18, 0);
        
    }
}

The above program will raise an exception as shown below:

For a clear understanding, you may refer to this blog.

Question 25) What is type casting in Java?

Answer 25) Assigning the value of one primitive data type to another primitive data type either manually or automatically is called type casting in Java.

There are two types of casting in Java:-

Widening Casting: Converting a lower data type into a higher data type is called widening casting or implicit conversion or casting down.

byte -> short -> char -> int -> long -> float -> double 

Narrowing casting: Converting a higher data type into a lower data type is called narrowing casting or explicit conversion or casting up.

double -> float -> long -> int -> char -> short -> byte 

The below program illustrates the casting in Java

public class Demo {
public static void main(String args[]) {
   // Widening Casting
   int myInt = 10;
   double myDouble = myInt; // Automatic casting from integer to double will be done here
   System.out.println(myInt); // 10
   System.out.println(myDouble);  // 10.0
   
   // Narrowing Casting
   double a = 1.13d;
   int b = (int) a;  // Manual casting from double to integer
   System.out.println(a); // 1.13
   System.out.println(b); // 1
}
}
}}

The output of the above program is:

10
10.0
1.13
1

Question 26) How is an infinite loop declared in Java?

Answer 26) A loop that runs infinitely without any breaking condition is called an infinite loop. The following examples illustrate infinite loops in Java.

for loopwhile loopdo-while loop
for(;;){     // Statements}while(true){    // Statements}do{
} while(true);

Question 27) What is the difference between Method overloading and Method overriding in Java?

Answer 27) The difference between Method overloading and overriding are summarized in the following table:

Method OverloadingMethod overriding
When a class has multiple methods with the same name but different in  parameters in the same class.The derived/child class provides a different implementation of the Method from the Parent class
Method overloading is done within a single class.Method overriding is done using two classes that have an Is-A or inheritance relation.
Parameters must be differentParameters must be same
It is an example of compile-time polymorphism.It is  an example of run time polymorphism

Question 28) What are the main concepts of OOPs in Java?

Answer 28) Object-oriented programming is a methodology to design a program using classes and objects. Java supports the following concepts of OOPs:

Question 29) Can you override a private method?

Answer 29) Private methods cannot be overridden in Java. The reason is that private methods are only visible to the class in which they are declared.

Upon overriding a private method, a compile-time error occurs saying that the Method has private access in the parent class.

Question 30) What is the use of the ‘this’ and ‘super’ keywords in Java?

Answer 30) The super keyword is used to access the hidden fields and the overridden methods or attributes of the parent class

“this” keyword refers to the current class instance variable, invoking a current class method, the current class constructor, etc.

Question 31) What is a singleton class?

Answer 31) A Java class that can have only one instance at a time is called a singleton class. The new variable also points to the first instance created if you try to instantiate a singleton class again. To design a singleton class:-

  • Make the constructor private.
  • A static method that has a return type object of the singleton class.

The below program illustrates that only a single instance can be created of a singleton class. If you to try to instantiate Singleton class multiple times it will point to the first instance only.

class SingletonDemo{
    // Static variable reference
    private static SingletonDemo single_instance = null;
    
    // Private class Constructor
    private SingletonDemo()
    {
        
    }
    public static SingletonDemo getInstance()
    {
        if(single_instance == null)
        {
            single_instance = new SingletonDemo();
        }
        
        return single_instance;
    }
}

public class MyClass {
    public static void main(String args[]) {
        SingletonDemo a = SingletonDemo.getInstance();
        SingletonDemo b = SingletonDemo.getInstance();
        SingletonDemo c = SingletonDemo.getInstance();
        
        
        System.out.println("Hashcode of a is "  + a.hashCode());
        System.out.println("Hashcode of b is "  + b.hashCode());
        System.out.println("Hashcode of c is "  + c.hashCode());
        
        if(a == b && b == c)
        {
            System.out.println("Three objects are pointing to the same memory location");
        }
        
        else{
            System.out.println("Three objects do not point to the same memory location");
        }
    }
}

The output of the above program is:

Question 32) What is the Java String Pool?

Answer 32) String Pool or String Intern Pool or String Constant Pool is a storage area in java heap where string literals are stored.

Whenever a new string is created, the JVM first checks that literal in the string pool, if the literal is already present in the pool, a reference to the pooled instance is returned, else a new String object is created.

Question 33) What are the differences between stack and heap memory in Java?

Answer 33) Stack Memory:- A physical space allocated to threads at run time follows the LIFO(Last in first out) structure. Variables, References to objects and partial results are stored in the stack memory.

Heap Memory: The memory is created when the Java Virtual Machine starts and is used as long as the application runs. Java runtime uses heap memory to allocate memory to objects and Java Runtime Environment classes.

In addition to the above questions, questions related to Input and Output, Packages, In-built methods may also be asked. 

Tips

It is always recommended to do good research on the company and your interview role. In addition, the following tips are useful for beginners when preparing for your next big tech interview:

  1. Get your Basics Right: You cannot build a great building on a weak foundation. First of all, have a solid grip on Java fundamentals. You may refer to our free guided path.
  2. Explaining concepts using examples: Anyone can theoretically answer the difference between static and non-static methods or the meaning of typecasting in Java, but explaining the concept using a program will set you apart from others. The interviewer will understand that you know the concepts well.
  3. OOPs: OOPs concepts are one of the most frequently asked questions in Java interviews. It’s recommended to have a clear understanding of the various concepts like Inheritance, Encapsulation etc.
  4. Data Structures and Algorithms: Have a good understanding of the various data structures and algorithms in the Java programming language. You may practice questions asked in top product based companies on Codestudio.

Key Takeaways

The article discussed frequently asked Java interview questions for freshers with little or no experience. Once you are done with this, you may check out our Interview Preparation Course to level up your programming journey and to get placed at your dream company.