Tutorial Playlist

Java Tutorial for Beginners: A Step-by-Step Guide

Overview

What is Java: A Beginners Guide To Java

Lesson - 1

Arrays In Java: Declare, Define, and Access Array

Lesson - 2

One-Stop Solution for Java Installation in Windows

Lesson - 3

What Are Java Classes and Objects and How Do You Implement Them?

Lesson - 4

How to Get Started With Eclipse IDE?

Lesson - 5

What is Java API and The Need for Java APIs?

Lesson - 6

What Are Java Strings And How to Implement Them?

Lesson - 7

What is Encapsulation in Java and How to Implement It?

Lesson - 8

What is an Abstract Class in Java and How to Implement It?

Lesson - 9

Introduction To Java Servlets and Its Life-Cycle

Lesson - 10

What is Polymorphism in Java and How to Implement It?

Lesson - 11

What Is Java JDBC? The Complete Reference

Lesson - 12

What is Inheritance in Java and How to Implement It

Lesson - 13

Java EE Tutorial: All You Need To Know About Java EE

Lesson - 14

How to Implement the Revolutionary OOPs Concepts in Java

Lesson - 15

What is Exception Handling in Java?

Lesson - 16

What is Java Interface and Why it's Needed?

Lesson - 17

Top 25 Pattern Programs in Java For Printing Numbers

Lesson - 18

Java vs JavaScript: Know The 8 Major Differences

Lesson - 19

Java vs. Python: Which is the Best Programming Language?

Lesson - 20

10 Best Java Frameworks You Should Know in 2021

Lesson - 21

Top 10 Brilliant Java Project Ideas You Need to Know

Lesson - 22

What Are Java Collections and How to Implement Them?

Lesson - 23

What Is JDK? Why Do We Need It?

Lesson - 24

What is a Java Lambda Expression and How to Implement It?

Lesson - 25

Top 60 Java Interview Questions and Answers in 2021

Lesson - 26

Java Programming: The Complete Reference You Need

Lesson - 27

All You Need to Know to Implement JUnit Testing in Java

Lesson - 28
Top 60 Java Interview Questions and Answers in 2021

Java is the most widely used programming language in the current IT industry. One major reason for the vast number of beginners and professionals in the field of programming is the career potential that Java knowledge comes with. This article is dedicated to the same purpose. Here is a complete guide on how to help you crack the most frequently asked Java Interview questions.

This article is divided into three levels based on the complexity of the questions. It is as shown below.

  1. Basic Java Interview Questions and Answers
  2. Intermediate Java Interview Questions and Answers
  3. Advanced Java Interview Questions and Answers

Basic Java Interview Questions 

1. What do you get in the Java download file? How do they differ from one another?

We get two major things along with the Java Download file. 

JDK - Java Development Kit

JRE - Java Runtime Environment

JDK

JRE

Abbreviation for JavaDevelopment Kit

Abbreviation for Java Runtime Environment

JDK is a dedicated kit for solely software development

JRE is a set of software and library designed for executing Java Programs

Unlike JVM, JDK is Platform Dependent

Unlike JVM, JRE is also Platform Dependent

JDK package is a set of tools for debugging and Developing

JRE Package is one that only supports files and libraries for a runtime environment 

JDK package will be provided with an installer file

JRE Package does not get an installer but has only a runtime environment

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

2. What is a ClassLoader?

A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading class files when a program is executed; ClassLoader is the first to load the executable file.

Java has Bootstrap, Extension, and Application classloaders.

3. What are the Memory Allocations available in JavaJava?

Java has five significant types of memory allocations.

  • Class Memory
  • Heap Memory
  • Stack Memory
  • Program Counter-Memory
  • Native Method Stack Memory

4. Will the program run if we write static public void main?

Yes, the program will successfully execute if written so. Because, in Java, there is no specific rule for the order of specifiers

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

Neither the Local Variables nor any primitives and Object references have any default value stored in them. 

6. Explain the expected output of the following code segment?

public class Simplilearn   

{  

    public static void main (String args[])   

    {  

        System.out.println(100 + 100 +“Simplilearn");   

        System.out.println(“E-Learning Company" + 100 + 100);  

    }  

}

The answers for the two print statements are as follows.

  • 200Simplilearn
  • E-Learning Company100100

7. What is an Association?

An Association can be defined as a relationship that has no ownership over another. For example, a person can be associated with multiple banks, and a bank can be related to various people, but no one can own the other.

8. Define Copy Constructor in Java

A Copy Constructor in Java is a constructor that initializes an object through another object of the same class.

9. What is a Marker Interface?

An empty interface in JavaJava is referred to as a Marker interface. Serializable and Cloneable are some famous examples of Marker Interface. 

10. What is Object Cloning?

An ability to recreate an object entirely similar to an existing object is known as Object Cloning in Java. Java provides a clone() method to clone a current object offering the same functionality as the original object.

11. Why is Java not completely object-oriented?

Java is not considered as a 100% object-oriented programming language because it still makes use of eight or more primitive data types like int, float double, etc.

12. Define Wrapper Classes in Java.

In Java, when you declare primitive datatypes, then Wrapper classes are responsible for converting them into objects(Reference types). 

13. Define Singleton Classes in Java.

In Java, when you make the constructor of a class private, that particular class can generate only one object. This type of class is popularly known as a Singleton Class.

14. Define package in Java.

The package is a collective bundle of classes and interfaces and the necessary libraries and JAR files. The use of packages helps in code reusability.

15. Can you implement pointers in a Java Program?

Java Virtual Machine takes care of memory management implicitly. Java's primary motto was to keep programming simple. So, accessing memory directly through pointers is not a recommended action. Hence, pointers are eliminated in Java. 

16. Differentiate between instance and local variables.

For instance, variables are declared inside a class, and the scope is limited to only a specific object.

A local variable can be anywhere inside a method or a specific block of code. Also, the scope is limited to the code segment where the variable is declared.  

17. Explain Java String Pool.

A collection of strings in Java's Heap memory is referred to as Java String Pool. In case you try to create a new string object, JVM first checks for the presence of the object in the pool. If available, the same object reference is shared with the variable, else a new object is created.

18. What is an Exception?

An Exception in Java is considered an unexpected event that can disrupt the program's normal flow. These events can be fixed through the process of Exception Handling.

19. What is the final keyword in Java?

The term final is a predefined word in Java that is used while declaring values to variables. When a value is declared using the final keyword, then the variable's value remains constant throughout the program's execution.

20. What happens when the main() isn't declared as static?

When the main method is not declared as static, then the program may be compiled correctly but ends up with a severe ambiguity and throws a run time error that reads "NoSuchMethodError."

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Intermediate Java Interview Questions

21. What is JDK? Mention the variants of JDK?

JDK is an abbreviation for Java Development Kit. It is a combined Package of JRE and Developer tools used for designing Java Applications and Applets. Oracle has the following variants.

  • JDK Standard Edition
  • JDK Enterprise Edition
  • JDK Micro Edition

22. What are Brief Access Specifiers and Types of Access Specifiers?

Access Specifiers are predefined keywords used to help JVM understand the scope of a variable, method, and class. We have four access specifiers.

  • Public Access Specifier 
  • Private Access Specifier 
  • Protected Access Specifier 
  • Default Access Specifier

23. Can a constructor return a value?

Yes, A constructor can return a value. It replaces the class's current instance implicitly; you cannot make a constructor return a value explicitly.

24. Explain ‘this’ keyword in Java.

The term "this" is a particular keyword designated as a reference keyword. The "this" keyword is used to refer to the current class properties like method, instance, variable, and constructors.

25. Explain ‘super’ keyword in Java.

The term "super" is a particular keyword designated as a reference keyword. The "super" keyword refers to the immediate parent class object.

26. Explain Method Overloading in Java.

The process of creating multiple method signatures using one method name is called Method Overloading in Java. Two ways to achieve method overloading are:

  1. Varying the number of arguments
  2. Changing the return type of the Method 

27. Can we overload a static method?

No, Java does not support the Overloading of a static method. The process would throw an error reading "static method cannot be referenced."

28. Define Late Binding.

Binding is a process of unifying the method call with the method's code segment. Late binding happens when the method's code segment is unknown until it is called during the runtime. 

29. Define Dynamic Method Dispatch.

The Dynamic method dispatch is a process where the method call is executed during the runtime. A reference variable is used to call the super-class. This process is also known as Run-Time Polymorphism.     

30. Why is the delete function faster in the linked list than an array?

Delete Function is faster in linked lists as the user needs to make a minor update to the pointer value so that the node can point to the next successor in the list

31. Give a briefing on the life cycle of a thread.

The life cycle of a thread includes five stages, as mentioned below.

  1. New Born State
  2. Runnable State
  3. Running State
  4. Blocked State
  5. Dead State

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

Although they look similar, there is a massive difference between both.

  • >> operator does the job of right shifting the sign bits
  • >>> operator is used in shifting out the zero-filled bits

33. Brief the life cycle of an applet.

The life cycle of an applet involves the following.

  1. Initialization
  2. Start
  3. Stop
  4. Destroy
  5. Paint

34. Why are generics used in Java Programming?

Compile-time type safety is provided by using generics. Compile-time type safety allows users to catch unnecessary invalid types at compile time. Generic methods and classes help programmers specify a single method declaration, a set of related methods, or related types with an available class declaration. 

35. Explain the Externalizable interface.

The Externalizable interface helps with control over the process of serialization. An "externalisable" interface incorporates readExternal and writeExternal methods.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

36. What is the Daemon Thread?

The Daemon thread can be defined as a thread with the least priority. This Daemon thread is designed to run in the background during the Garbage Collection in Java.

The setDaemon() method creates a Daemon thread in Java.

37. Explain the term enumeration in Java.

Enumeration or enum is an interface in Java. Enum allows the sequential access of the elements stored in a collection in Java.

38. Why is Java is Dynamic?

Java is designed to adapt to an evolving environment. Java programs include a large amount of runtime information that is used to resolve access to objects in real-time. 

39. Can you run a code before executing the main method?

Yes, we can execute any code, even before the main method. We will be using a static block of code when creating the objects at the class's load time. Any statements within this static block of code will get executed at once while loading the class, even before creating objects in the main method.

40. How many times is the finalize method called?

The finalize method is called the Garbage collector. For every object, the Garbage Collector calls the finalize() method just for one time.

Advanced Java Interview Questions

41. Can "this" and "super" keywords be used together?

No, "this" and "super" keywords should be used in the first statement in the class constructor. The following code gives you a brief idea.

public class baseClass {  

     baseClass() {  

         super();   

         this();  

         System.out.println(" baseClass object is created");  

     }  

     public static void main(String []args){  

         baseClass bclass = new baseClass();  

     }  

}

42. What is a JSP page?

JSP is an abbreviation for Java Servlet Page. The JSP page consists of two types of text.

  • Static Data 
  • JSP elements

43. What is JDBC?

JDBC is an abbreviation for Java Database Connector.

JDBC is an abstraction layer used to establish connectivity between an existing database and a Java application

44. Explain the various directives in JSP.

Directives are instructions processed by JSP Engine. After the JSP page is compiled into a Servlet, Directives set page-level instructions, insert external files, and define customized tag libraries. Directives are defined using the symbols below:

start with "< %@" and then end with "% >" 

The various types of directives are shown below:

  • Include directive

It includes a file and combines the content of the whole file with the currently active pages.

  • Page directive

Page Directive defines specific attributes in the JSP page, like the buffer and error page.

  • Taglib

Taglib declares a custom tag library, which is used on the page.

45. What are the observer and observable classes?

Objects that inherit the "Observable class" take care of a list of "observers." 

When an Observable object gets upgraded, it calls the update() method of each of its observers. 

After that, it notifies all the observers that there is a change of state. 

The Observer interface gets implemented by objects that observe Observable objects.

46. What is Session Management in Java?

A session is essentially defined as the random conversation's dynamic state between the client and the server. The virtual communication channel includes a string of responses and requests from both sides. The popular way of implementing session management is establishing a session ID in the client's communicative discourse and the server.

47. Briefly explain the term Spring Framework.

Spring is essentially defined as an application framework and inversion of control containers for Java. The spring framework creates enterprise applications in Java. Especially useful to keep in mind that the spring framework's central features are essentially conducive to any Java application.

48. What is JCA in Java?

Java Cryptography Architecture gives a platform and provides architecture and application programming interfaces that enable decryption and encryption. 

Developers use Java Cryptography Architecture to combine the application with the security applications. Java Cryptography Architecture helps in implementing third party security rules and regulations. 

Java Cryptography Architecture uses the hash table, encryption message digest, etc. to implement the security.

49. Explain JPA in Java.

The Java Persistence API enables us to create the persistence layer for desktop and web applications. Java Persistence deals in the following:

  1. Java Persistence API
  2. Query Language
  3. Java Persistence Criteria API
  4. Object Mapping Metadata

50. Explain the different authentications in Java Servlets.

Authentication options are available in Servlets: There are four different options for authentication in servlet:

  • Basic Authentication: 

Usernames and passwords are given by the client to authenticate the user.

  • Form-based authentication: 

In this, the login form is made by the programmer by using HTML.

  • Digest Authentication: 

It is similar to basic authentication, but the passwords are encrypted using the Hash formula. Hash Formula makes digest more secure.

  • Client certificate Authentication:

It requires that each client accessing the resource has a certificate that it sends to authenticate itself. Client Authentication requires the SSL protocol.

Learn top skills demanded in the industry, including Angular, Spring Boot, Hibernate, Servlets, and JSPs, and SOA to build highly web scalable apps with the Full Stack Java Developer Masters Program.

51. Explain FailFast iterator and FailSafe iterator along with examples for each.

FailFast iterators and FailSafe iterators are used in Java Collections. 

FailFast iterators do not allow changes or modifications to the Java Collections, which means they fail when the latest element is added to the collection or an existing element gets removed from the collection. The FailFast iterators tend to fail and throw an exception called ConcurrentModificationException.

Ex: ArrayList, HashMap

Whereas, on the other hand, FailSafe iterators allow changes or modifications to be done on the Java Collections. It is possible, as the FailSafe iterators usually operate on the cloned copy of the collection. Hence, they do not throw any specific exception.

Ex: CopyOnWriteArrayList

52. How do we reverse a string?

The string can be reversed by using the following program.

package simplilearnJava;

public class StringReverse {

public static void main(String args[]) {

String str = "Simplilearn";

String reverse = new StringBuffer(str).reverse().toString();

System.out.printf("Actual Word: %s, Word after reversing %s", str, reverse);

}

public static String reverse(String source) {

if (source == null || source.isEmpty()) {

return source;

}

String reverse = "";

for (int i = source.length() - 1; i >= 0; i--) {

reverse = reverse + source.charAt(i);

}

return reverse;

}

}

Expected Output:

Actual Word: Simplilearn, Word after reversing nraelilpmiS

53. Write a program to find the square root of a number.

The Square root of a number can be found by using the following program.

package simplilearnJava;

import java.util.Scanner;

public class SRoot {

public static void main(String args[]) {

try (Scanner sc = new Scanner(System.in)) {

System.out.println("Input a number to find square root: ");

double square = sc.nextDouble();

double squareRoot = Math.sqrt(square);

System.out.printf("The square root is: %f \n", squareRoot);

}

}

}

Expected Output:

Input a number to find square root: 

25

The square root is: 5

54. Write a program that detects the duplicate characters in a string.

The program that finds the duplicate elements in a string is written below:

package simplilearnJava;

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

public class FindDuplicate {

public static void main(String args[]) {

printDuplicateCharacters("Simplilearn");

}

public static void printDuplicateCharacters(String word) {

char[] characters = word.toCharArray();

Map<Character, Integer> charMap = new HashMap<Character, Integer>();

for (Character ch : characters) {

if (charMap.containsKey(ch)) {

charMap.put(ch, charMap.get(ch) + 1);

} else {

charMap.put(ch, 1);

}

}

Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();

System.out.printf("List of duplicate characters in String '%s' %n", word);

for (Map.Entry<Character, Integer> entry : entrySet) {

if (entry.getValue() > 1) {

System.out.printf("%s: %d %n", entry.getKey(), entry.getValue());

}

}

}

}

Expected output:

List of duplicate characters in String 'Simplilearn.' 

i: 2 

l: 2 

55. Write a Program to remove duplicates in an ArrayList.

The following program can be implemented to remove duplicate elements in an ArrayList

package simplilearnJava;

import java.util.ArrayList;

import java.util.LinkedHashSet;

import java.util.List;

import java.util.Set;

public class ArrayDuplicate {

public static void main(String args[]) {

List<Integer> num = new ArrayList<Integer>();

num.add(1);

num.add(2);

num.add(3);

num.add(4);

num.add(5);

num.add(6);

num.add(3);

num.add(4);

num.add(5);

num.add(6);

System.out.println("Your list of elements in ArrayList : " + num);

Set<Integer> primesWithoutDuplicates = new LinkedHashSet<Integer>(num);

num.clear();

num.addAll(primesWithoutDuplicates);

System.out.println("list of original numbers without duplication: " + num);

}

}

Expected Output:

Your list of elements in ArrayList : [1, 2, 3, 4, 5, 6, 3, 4, 5, 6]

list of original numbers without duplication: [1, 2, 3, 4, 5, 6]

56. Find the word count in a string using HashMap Collection.

The following program can be used for word count.

package simplilearnJava;

import java.util.HashMap;

public class WordCount {

public static void main(String[] args) {

String str = "Hello World, Welcome to Simplilearn";

String[] split = str.split(" ");

HashMap<String, Integer> map = new HashMap<String, Integer>();

for (int i = 0; i < split.length; i++) {

if (map.containsKey(split[i])) {

int count = map.get(split[i]);

map.put(split[i], count + 1);

} else {

map.put(split[i], 1);

}

}

System.out.println(map);

}

}

Expected Output:

{Hello=1, Simplilearn=1, Welcome=1, to=1, World,=1}

57. Write a program to find the Second Highest number in an ArrayList

The following program can be used to find the second biggest number in an array list.

package simplilearnJava;

public class NextHighest {

public static void main(String[] args)

    {

        int array[] = { 1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32};

        int high = 0;

        int nextHigh = 0;

        System.out.println("The given array is:");

        for (int i = 0; i < array.length; i++)

        {

            System.out.print(array[i] + "\t");

        }

        for (int i = 0; i < array.length; i++)

        {

            if (array[i] > high)

            {

                nextHigh = high;

                high = array[i];

            }

            else if (array[i] > nextHigh)

            {

                nextHigh = array[i];

            }

        }

        System.out.println("\nSecond Highest is:" + nextHigh);

        System.out.println("Highest Number is: "  +high);

    }

}

Expected Output:

The given array is:

1 2 3 4 11 12 13 14 21 22 23 24 31 32

Second Highest is:31

The highest number is: 32

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

System.out and System.err represent the monitor by default and thus can be used to send data or results to the monitor. System.out is used to display normal messages and results. System.eerr is used to display error messages. System.in represents InputStream object which by default represents standard input device, i.e., keyboard.

59. Could you provide some implementation of a Dictionary having a large number of words?

The simplest implementation that can be given is that of a List wherein one can place ordered words and perform a Binary search. The other implementation with a better search performance is HashMap where the key is used as the first character of the word and the value as a LinkedList.

Up another level, there are HashMaps like:

hashmap {

a (key) -> hashmap (key-aa , value (hashmap(key-aaa,value)

b (key) -> hashmap (key-ba , value (hashmap(key-baa,value)

z (key) -> hashmap (key-za , value (hashmap(key-zaa,value)

}

Up to n levels where n is the average size of the word in the dictionary.

60. How would you tackle it if you might have to encounter pattern programs in Java?

Solution - Top 25 Most Frequently asked Pattern Programs in Java

With this, we have come to the end of this Java Interview Questions article. Moving ahead, we will look into the next crucial steps that you could pursue, to master Java.

Next Steps

Java Interview Questions are really important to go through before attending an interview. It helps you to put yourself on the safer side by getting you ready to be able to answer the questions asked in your interview. Now, the next step is to learn How to Become a Software Developer.

If you're looking for more in-depth knowledge about the Java programming language and information on how to get certified as a professional developer, explore our Java training and certification programs, which Simplilearn’s experienced industry experts offer in real-time. In particular, check out our Full Stack Java Developer Master’s Program today!

If you have any questions about this “Java Interview Questions” article, please leave them in the comments section, and our experts will answer them for you, at the earliest!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.