Blogs  

Top 40 Core Java Interview Questions You Must Prepare

To become a proficient Core Java developer, it's essential to understand that Java is a powerful language, widely used for data processing, application development, and large-scale systems. Java offers robust tools and frameworks that enable complex computational tasks and the creation of sophisticated models to manage and analyze data efficiently.

Why Choose Java?

  1. Industry Proven: Java has been a dominant force in the software development industry, trusted by many organizations for building scalable and secure applications. It has established itself as a reliable toolkit for enterprise-level application development.

  2. Open-Source Libraries: Java boasts a vast array of open-source libraries, providing various approaches to achieving similar outcomes. This flexibility allows developers to select the best tools for their specific needs.

  3. Competitive Edge: In today’s competitive technology landscape, developers and engineers are constantly looking for ways to process information efficiently, extract meaningful insights, and build models that handle massive datasets. Java’s performance and scalability make it an ideal choice for these tasks.

  4. Versatility: Java is a versatile platform that supports a wide range of libraries and frameworks, enabling developers to tackle various tasks, from data processing to application development. Being well-versed in these libraries will enhance the robustness and speed of your development work.

 

  1. What is Java Language?

Java is a Object Oriented programming language and platform independent. So, java is secure and reliable for coding mobile apps and enterprise software to big data applications and server-side technologies.

  1. What is java virtual machine?

Java virtual machine is known as JVM, it allows to run java programs on any device or operating system based on “write once run anywhere” principal and all the java programs are compiled for the JVM.

  1. Is Java Platform Independent?

Yes, Java is Platform Independent because all APIs compiled into bytecodes and the virtual machine taking care of bytecode form different platforms. 

  1. Explain difference between Heap and Stack memory in Java?

Basically, stack memory is small in size when compared to heap size and stack having temporary variables and data but heap used large amount of data. If stack having no space to create new object it throws an error message like java.lang.StackOvreflowError but if heap size is full it throws java.lang.OutOfMemoryError.

  1. Explain difference between Instance variable and Local variable?

Instance variables are declared out side of the class but local variables are declared inside of method or constructor.

  1. What is marker interface?

Marker Interface does not have any method inside. JDK having built in marker interfaces are Serializable interface, Cloneable interface and Remote interface.

  1. What is functional interface?

Functional interface means it allows only one abstract method and it provides from the java version 1.8 onwards. We use @FunctionalInterface annotation to make an interface into fuctional interface.
We have four type of functional interfaces and these are applied at multiple situations

  • Consumer
  • Predicate
  • Function
  • Supplier

Example for user defined functional interface

@FunctionalInterface
interface A
{
    int a();
}
  1. What is singleton class?

Singleton class allows only one instance of class exist.
Follow some rules for Singleton class
Declare Access modifier must be private for all construtors and static method returns a reference to the instance.
The instance must be stored into private static variable.
Example:

class NIT // class NIT to make singleton
{
    private static NIT instance_var = null; // Here static variable instance_var refers to NIT  
    public String str;
   
    public NIT() {
        str = "Welcome to NareshIT";
    }
   
   
    public static NIT getInstance_var() {
        if(instance_var ==null)
            instance_var = new NIT();
       
        return instance_var;
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit1 = NIT.getInstance_var();
        NIT nit2 = NIT.getInstance_var();
        if(nit1==nit2)
        {
            System.out.println("Singleton");
        }
       
        else
            System.out.println("No instance");
    }
}
  1. What is subclass?

A class that derived from another class or parent/super class is known as subclass.

class NIT
{
   
}
class Naresh extends NIT // Naresh is subclass of NIT
{
   
}
  1. What is constructor in java?

A construcor is special method of class and the declare same name of class if required. Whenever object is created the constructor automatically called.
Construcor does not have any return rype and it calls only once at the time of object creation.

class NIT
{
    //Constructor
    public NIT() {
        System.out.println("Constructor");
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit = new NIT(); // object creation for NIT class
    }
}
  1. What are the various types of interfaces in java?

There are mainly three types of interfaces
1.    Noramal interface
Examples: List, Set, Map
2.    Functional interface
Example: Runnable
3.    Marker interface
Example: Serilizable interface

  1. What is the difference between Set and List?

The major difference is List allows duplicate values but Set does not allows duplicate values and List allows multiple null values but set allows only one null value.
Example for List and Set interface difference

class NIT
{
    public void nit() {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(1);
        list.add(2);
        list.add(null);
        list.add(null);
        System.out.println(list);
       
        Set<Integer> set = new HashSet<Integer>();
        set.add(1);
        set.add(2);
        set.add(1);
        set.add(2);
        set.add(null);
        set.add(null);
        System.out.println(set);
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit = new NIT();
        nit.nit();
    }
}
  1. What is linked list?

Linked list is one of linear data structure and data and next node consider as single node. Where single node stores the data and address of the next node and the last node is contains NULL value.
Different types of Linked list
1.    Single Linked list
2.    Double Linked List
3.    Circular Linked List

  1. What is ArrayList?

ArrayList is a class implemented by using List interface. The functionality of ArrayList is dynamic array and there is no fixed size of an array. ArrayList is found in java.util package. It contains duplicate values and maintain insertion order. By using add() method to add new elements into ArrayList
Syntax:
ArrayList<E> al = new  ArrayList<E>();
Example:
ArrayList<String> al = new  ArrayList<String>();

  1. What is Deque?

DeQue stands for Double-ended-queue, it is linear data structure which allows the data manipulation the data from both the ends.

  1. What is TreeSet?

TreeSet is a class which provides an implementation of Set interface and stored the elements or objects in ascending order.
Syntax:
TreeSet<E> tree = new  TreeSet<E>();
Example:

class NIT
{
    public void nit() {
        TreeSet<Integer> tree = new TreeSet<Integer>();
        tree.add(2);
        tree.add(5);
        tree.add(1);
        System.out.println(tree);
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit = new NIT();
        nit.nit();
    }
}
  1. What is Iterator in java?

Iterator is a loop for collection framework to retrieve the elements one after other by using iterator method. In Iterator we have three methods called as
next() : It prints next element if present otherwise it throws NoSuchElementException
hasNext() : It return all the elements available in the collection
remove() : It remove next element in the in iterator.
Example:

class NIT
{
    public void nit() {
        ArrayList<String> al = new ArrayList<String>();
        al.add("Java");
        al.add("Python");
        al.add("Angular");
        Iterator<String> iterator = al.iterator();
        System.out.println(iterator.next());
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
  1. What is hash map?

HashMap is the implementation of Map interface and it stores the data in the form if key and value pair.
It is availabe in java.util package. If we try to insert duplicate key and it will replace the element of correspondent key.
Example of HashMap:

class NIT
{
    public void nit() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("Java", "Language");
        map.put("Java", "Computer Language");
        System.out.println(map);
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit = new NIT();
        nit.nit();
    }
}
  1. What is the super class of Object?

Object is a parent class of all classes in java.

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

Method overloading is compile time polymorphism and method overriding run time polymorphism.
Method overloading shares more than one method with different arguments in the class but method overriding is based on inheritance which develops from parent class.

  1. What is the difference between method interface and abstract class?

Abstract class having abstract and non-abstract methods but interface having abstract, default and static methods.
Abstract class does not support multiple inheritance but Interface supports multiple inheritance.

  1. Explain Constructor overloading?

Constructor overloading is more than one Constructor with different parameters of same class name.
Example:

class NIT
{
    public NIT() {
       
    }
    public NIT(int a) {
       
    }
    public NIT(String a) {
       
    }
    public NIT(String a, int b) {
       
    }
}
  1. Can main() method is overloaded in java?

main() method is overloaded but according to java syntax first jvm calls main method like “public static void main(String[] args)” only

public class InterviewTest {
    public static void main(String[] args) {
        System.out.println("main method");
    }
   
    public static void main(char[] args) {
        System.out.println("Char main method");
    }
   
    public static void main(int[] args) {
        System.out.println("int main method");
    }
}
  1. What is Lambda function?

Lambda function is commonly known as anonymous function and it is user defined function without name. In java we have lambda expression for express instances of functional interfaces.
Lambda Expression are divided into three parts one is Arguments next Arrow token and Body of Lambda expression
Syntax:
Lambda operator -> body

  1. What is polymorphism?

Polymorphism in general known as many forms and we have two types of polymorphism
1.    Run time polymorphism (method overriding) : same name from different class and this is called as “Late binding”.
2.    Compile polymorphism (method overloading) : Same name with different parameters

  1. What is encapsulation?

Encapsulation is one of the fundamental concept of Object-Oriented-Programming language and we encapsulate both variables(data) and data(method) in class, In other words this is a process of wrapping the data and code  together in single unit.
Binding the data by using private keyword for variables and to access the data from setter and getter method.
Syntax:
<Access_Modifier> class <Class_Name> {
private <Data_Members>;
private <Data_Methods>;
}
Example:

class NIT
{
    private int id;
    private String course;
    private String faculty;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCourse() {
        return course;
    }
    public void setCourse(String course) {
        this.course = course;
    }
    public String getFaculty() {
        return faculty;
    }
    public void setFaculty(String faculty) {
        this.faculty = faculty;
    }
   
}
  1. What is String pool?

String pool means Object allocation of String and it stores in java heap memory and which is maintained by String class, by default it is empty.
When create the String, JVM checks in string pool if the same string object is available or not and if not available the string it returns new String Object otherwise it return reference of the same String.
Example:

public class InterviewTest {
    public static void main(String[] args) {
        //Java is case sensitive
        String a = "Java";
        String b = "java";
        String c = "Java";
        if(a==b) //false
            System.out.println("a equals b");
        else if(a == c) // true
            System.out.println("a equals c");
        else
            System.out.println("false");
    }
}
  1. What the difference is between extends and implements keywords in java?

Extends keyword is used to inherit classes or interfaces and implements keyword is used to implement the interfaces.
Extends keyword may override some of the methods from superclass to subclass but a class must implement all the methods from interfaces.
Examples:

class NIT
{
   
}
class Naresh extends NIT
{
   
}
interface INIT
{
   
}
interface INaresh extends INIT
{
    void min();
    void max();
}
class Test implements INaresh
{
    @Override
    public void min() {
       
    }
    @Override
    public void max() {
       
    }
   
}
  1. Can we use single try block and multiple catch blocks in java?

Yes, we have multiple catch blocks for single try block but it does not allows once you declare ‘Exception’ in catch block, it is end of the catch block because Exception class is parent class of all type of Exceptions.
Example:

class NIT
{
    void test()
    {
        try {
           
        }catch (ArrayIndexOutOfBoundsException e) {
           
        } catch (Exception e) {
           
        }
       
        }
}
  1. Can we define private and protected modifiers for data members (fields) in interfaces?

We cannot define private and protected modifiers for data members (fields) in interfaces because in java interfaces by default it allows public modifier and static and final are permitted.

interface INIT
{
    public int a;
    private int b; //error
    protected String i; //error
}

  1. Is it possible to define a class inside an interface?

Yes, it possible to define a class inside an interface
Example 1

interface INIT
{   
    class Faculty implements INIT
    {
       
    }
}


Example 2

class NIT implements INIT {
   
}
interface INIT {
    class Faculty {
    }
}
  1. Is interface have a constructor?

Interfaces cannot have constructors. Because interface attributes are by default public,   static and final.

  1. What is nested interface?

Nested interface is nothing but we declare interface within class or interface. Nested interface cannot access directly it must be referred by outer class or interface and it must be public.
Example 1

interface INIT {
    interface inside_INIT
    {
       
    }
}


Example 2

class NIT{   
    interface INIT
    {
       
    }
}
  1. What are the modifiers are allowed for methods in an interface?

Public and abstract are the modifiers are allowed for methods in an interface
Example:

interface INIT {
    abstract void test();
    public void end();
    private void start(); // error
}
  1. Can an interface have instance and static blocks?

Interfaces does not allow static block but it allows public final static members.
Example 1:

interface INIT {
    static {}//error
}


Example 2:

interface INIT {
    public static void test() {
       
    }
}
  1. Can an interface be final?

Interface cannot declare as final because all the methods are abstract and only public and abstract are allowed.

final interface INIT { // error
    public static void test() {
       
    }
}
  1. Can abstract classes have constructors in Java?

Abstract classes can have constructors, but they cannot be instantiated directly. The constructors are used when a concrete subclass is created.

abstract class NIT{   
    //constructor
    public NIT() {
       
    }
    NIT nit = new NIT(); // error: cannot instantiated
}
  1. Can an abstract class be final in Java?

Abstract class cannot be final in java because abstract methods are not to be final but abstract class has final methods.
Example 1:

final abstract class NIT{ // error
   
   
}


Example 2:

abstract class NIT{
    final abstract void info(); //error
   
    final void test(){}
}
  1. Is it necessary for an abstract class to have an abstract method?

An abstract class does not required to have an abstract method but any class or super class have abstract method it must be implement abstract for the class.
Example 1: not required abstract method when declare class as abstract

abstract class NIT{
   
}


Example 2: when abstract method is created you must declare class as abstract

class NIT{ //error
   
    private void test() {
       
    }
   
    abstract void info(); // here you must declare abstract as class   
}


Example 3:

abstract class NIT{
   
    private void test() {
       
    }
    abstract public void til();
}
class NIT1 extends NIT // NIT1 must implement the inherited abstract method NIT.til()
{
   
}
  1. Can an abstract method be declared with private modifier?

Abstract methods are to be declare as private, it allows can be public, default and public
Example:

abstract class NIT{
    private abstract void test(); //error
    public abstract void test1();
    abstract void test2();
    public abstract void test3();
}  

Scope @ NareshIT:

NareshIT's Core Java Online Training program offers extensive hands-on training across front-end, middleware, and back-end technologies.

  • Real-World Projects: The program equips you with practical skills through phase-end and capstone projects based on real business scenarios.

  • Expert Guidance: You'll learn from leading industry experts, with content meticulously structured to ensure relevance to current industry needs.

  • Comprehensive Learning: The program covers end-to-end application development, enabling you to build applications with exciting and practical features.

  • Certification: Upon completion, you'll earn an industry-recognized course completion certificate, validating your expertise in Core Java development.

 

What is Modulus in Java and how does it work

Modulus in Java

Most of you must have heard about the Modulus term. You will find a question related to it in your interview for C, C++, Python, or Java always. In this artifact, we will discuss the modulus and then will implement it through a program in Java. The topics we will cover in this article are what a modulus operator is, its syntax, and an example of the Modulus. So, let us begin our article. And you can contact us for your Java training. Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. 

Modulus Operator

This operator returns the remainder when a dividend is divided by a divisor, and we term it as X mod Y. Let us have a technical syntax of this modulus operator.

X%Y 

Here X is the dividend and the divisor is Y. And you can use it for finding the remainder when a dividend is divided by a divisor.

Hope now you have the complete details of the Modulus operator, and now let us use it in a Java program.

Program sample

class Main{
public static void main(String[] args){
int a,b,res;
a=30;
b=10;
System.out.println(a+" "+b);
res=a%b;
System.out.println("The modulus is : "+res);
}
}	
Output:
30 10
The modulus is: 0

And, hence, it is quite easy to implement the modulus operator in Java.

We can also make use of the modulus operator in java to find whether a given number is divisible by 3. Let us have a look below:

public class Main 
 {
public static void main(String[] args) 
{
int a = 453;
isDivisibleBythree(a);
}
public static boolean isDivisibleBythree(int a)
{
if(a%3 == 0)
{
System.out.println("Number is divisible by 3");
}
return true;
}
}

Hence, the modulus operator is being used in various cases. And it can be used for finding each digit of a number, as well as in finding the prime numbers. There is a long list of applications of the modulus operator. And that is why the modulus operator is a very useful operator in Java or any programming language.

Let's have a look at the program that uses the modulus operator to find out each digit of a given number. The trick is, we divide the number by 10, and store the remainders in a dynamic array in Java. 

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
	public static void main(String[] args) {
		System.out.println("Enter Number:");
		Scanner s =new Scanner(System.in);
		int num=s.nextInt();
		ArrayList<Integer> myList = new ArrayList<>();
		while(num!=0)
		{
myList.add(num%10);
		    num=num/10;
		}
		System.out.println(myList);
	
	}
}
Let's have another program in which we reverse a number using a modulus operator. Remember we are using here ArrayList as we need here a dynamic array for storing the digits of a number. The program code is as below:
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
		System.out.println("Enter Number:");
		Scanner s =new Scanner(System.in);
		int num=s.nextInt();
		ArrayList<Integer> myList = new ArrayList<>();
		while(num!=0)
		{
myList.add(num%10);
		    num=num/10;
		}
		System.out.println(myList);
		System.out.println("The Reverse of the number is:");
		for(Integer p: myList)
		{
		  System.out.print(p);
		}
	
	}

You need to know that there is a very deep implementation of the Data structure in Java. And if you want to learn all that, you can contact us anytime. And apart from these, various web technologies are implemented using Java. There is J2EE, J2ME, and J2SE. And java is used extensively in Android as well. And we teach all that. You can find an online form on our site, and send us your queries. Do not forget to add your phone number and email address, so that we can reply to you. And feel free to contact us anytime. 

And this we have reached the end of the article. Hope you now know the modulus operator.

Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let us have a look at what you will get with this Java training package:

  • You need to pay a nominal fee.

  • You can choose any Java certification, as per your skills and interest.

  • You have the option to select from online and classroom training.

  • A chance to study at one of the best Java training institutes in India 

  • We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.

  • Naresh I technologies cater to one of the best Java training in India.

  • And a lot more is waiting for you.

Contact us anytime for your complete Java online training.

 

What is a Static Keyword in Java?

Static Keyword in Java

In Java, the keywords happen to be the reserved words that we cannot use in the form of Identifiers. And we have in total 57 such in Java. Amongst them is the Static keyword. In this artifact, we are going to discuss deeply the static keyword, and check how we can use it in Java programming. The topics covered in this blog are The Introduction to it, and its various applications like a static variable, static block, static classes, and Static methods. And you can contact us for your Java training. Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training.

What Static keyword is in Java?

When we talk of the static keyword in Java, we mainly deal with memory management. We can use it as a variable, block, method, or as nested classes. Through this keyword, we can share a variable or methods of a class. Generally, we make use of the static to define the constant methods and variables for all class instances. And the main method of the class is always static. You can easily understand why is it so.

To make the static member which can be a block, method, variable, or a nested class, you require preceding the declaration with the static keyword. If we add a static keyword to a member of a class, we can access them before the object of the class gets created, and there is no need for the object reference.

In the Java program, the static keyword happens to be a non-access modifier, and we can make use of it as below:

  • The static Block

  • Static Classes

  • Static method

  • Static variable

And now, we detail each of the above with a proper example.

Static keyword application

We need to first realize how the static block is being used in Java.

  Static Block

For doing the computation for initializing the static variables, you can do the static block declaration which is executed only once, on the class loading. Have a guise at the beneath Java program for understanding the Static block usage.

// Java program for explaining the use of the static block
import java.util.*;
public class Main{
static String a = "Naresh I";// This is static variable
static String b= "Technologies";// This is static variable
static String c = a + b;
// This is static block
static {
System.out.println("Static block");

}
 
public static void main(String[] args)
{
System.out.println("We are inside main");
System.out.println("Welcome to"+" "+a+" "+b);
System.out.println("Welcome: "+" "+c);
}
}

When you implement the above sample, you will get the below output. And you will find in the below output that the static block executes exactly once and that on the class load.

Output:

Static block                                                                                                                  

We are inside main 

Welcome to Naresh I Technologies                                                                                              

Welcome:  Naresh I Technologies

Now you have an idea of how the static block works. Now let us move ahead and check what the static variables are, and how they can help us.

Static Variable

When we place in front of the variable static, then only one copy of the variable is made and it is divided in between all the class level objects. They are essential, the global variables. And generally, each instance of the class has the same copy of variables that are declared static. The static variable gets created at the class level.

Let us now have an example on the above.

// Java program demonstrating the execution of the static variables and the static blocks 

 
import java.util.*;
 
public class Main
{
// this is the static variable
static int a =10;
static int b =20;
static int c = sum(a,b);
 
// static-block
static {
System.out.println("We are in static block");
}
// this is the static-method
static int sum(int a, int b) {
System.out.println("The Sum is: "+ (a+b));
return a+b;
}
 
// This is the main method which is always static 
public static void main(String[] args)
{
System.out.println("The exact c value of c is: "+c);
System.out.println("We are inside the main");
}
}

On execution of the above code, we see that the static block is executed once, and the variables are executed in the order they are defined in the code.

Output:

The exact value of c is: 30                                                                                                       

We are in static block Value of i: 30                                                                                                                

We are inside the main

Now with the above knowledge, we dive deeper into the static keyword and see what are the nested classes and static methods.

Static Method

When we declare the method with a static keyword, that method is known as the static method. And the most appropriate example of the static method happens to be the main() method. And such methods have some restrictions, which are as below:

  • Such methods can call the static methods only directly.

  • And static data are directly accessed through them.

Now let us have a look at the static method through an example:

// see the restrictions on static methods in this program
public class Main
{
// this is static variable
static String a = "Naresh I";
 
// This is an instance variable
String b= "Technologies";
 
// This is static method
static void concatenate()
{
static String a = "Welcome";// This will result in error as a is static
System.out.println("Print"+a);
 
// We cannot make a static reference to nonstatic method a
a = "Narendra"; // This will result in compilation error
 
// We cannot make the static reference to
// concatenate() through the test type
concatenate(); // This will result in compilation error
 
// Super cannot be used in the static context
System.out.println(super.a); // This results in compilation error
}
// This is the instance method
void concatenate()
{
System.out.println("Inside concatenate");
}
 
public static void main(String[] args)
{
// This is the main method
}
}

In this example, you see that there are restrictions on the static method., and how the static methods can use the super in the static context. This is all related to a static method. Now let us have a look at the nested classes.

Static Classes

We can make the class static only if happens to be a nested class. They do not need any references from the Outer class.  And here, the nonstatic members cannot be accessed by the static classes of the outer class. Let us see below how this is executed.

public class MainClass{
private static String a="NareshIT";
//This is a static class
static class NestedClass
{
//This is non static AbstractMethodError
public void PrinttheString(){
System.out.println(a);
}
}
public static void main(String args[]){
MainClass.NestedClass obj = new MainClass.NestedClass();
obj.PrinttheString();
}
}

When this code gets executed, the following output is fetched.

NareshIT

And that is all about the Static keyword in Java. And we have reached the end of our article on the static keyword. However, you now know what is the static keyword, and everything we discussed about it. And do join our Java training classes. We have a lot to offer to you through our training program.

Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let's have a look at what you will get with this Java training package:

  • You need to pay a nominal fee.

  • You can choose any Java certification, as per your skills and interest.

  • You have the option to select from online and classroom training.

  • A chance to study at one of the best Java training institutes in India 

  • We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.

  • Naresh I technologies cater to one of the best Java training in India.

  • And a lot more is waiting for you.

Contact us anytime for your complete Java online training.