Java is everywhere! Over 10 million developers across the world use Java to develop applications for 15 billion Java-supporting devices. Developers have been using it to create applications having a myriad of applications, starting from Big Data to DTH boxes. Usability and scalability make Java Certification a high in-demand certification in the programming domain.

We have compiled a list of the most popular Java interview questions and answers to help you understand the basic concepts of Java programming for interview purposes. Here, the basic concepts of Java are explained with examples. It covers all the important topics which are asked in the interview such as features, OOPs concepts, collections, access specifiers, threads, exceptions, and more with programing codes to provide you with a better understanding and make you ready for the interview in any organization.

Q1. What are the main features of Java?

Ans. Java has exclusive features that make the language very powerful. Some of the notable Java features are given below:

  •     It is an object-oriented language, and because of this, it can be extended easily.
  •     It is Platform independent having the ability to Write Once and Run Anywhere (WORA)
  •     Secured programming language because it has no explicit pointer and runs inside a virtual machine sandbox
  •     Interpreted
  •     Robust in terms of memory management, automatic garbage collection,
  •     It is a high performing language when compared to other traditional interpreted programing language because it uses Just in Time compiler
  •     It is multi-threaded, and it shares a common memory area to deal with multiple tasks in a single go.

Q2. What do you mean by JVM?

Ans. JVM stands for Java virtual machine. It enables Java bytecode to be executed as an operating system on any system irrespective of the operating system.

Q3. Is null, delete or exit keyword in Java?

Ans. No.

Q4. What is Data Encapsulation?

Ans. One of the four fundamental object-oriented programming concepts, Data Encapsulation is a process of wrapping code and data into a single unit.

Q5. What are primitive data types?

Ans. There are 8 data types (Boolean, byte, char, long, float, double, short and int) that serve as the building blocks of data manipulation in Java.

Q6. When Super () keyword is used?

Ans. Super () keyword is used to call the main methods and also access the superclass constructor. It is also used to differentiate between the methods with the same name of superclasses and subclasses.

Q7. What is the difference between object-based programming language and object-oriented programming language?

Ans. Object-based programming language doesn’t support the features of OOPs except inheritance. Object-oriented languages are java, C and C++.

Q8. What is the name of the package used for matching with regular expressions?

Ans. Java.util.regex package

Q9. What are the four principles upon which object-oriented programming rest?

Ans. Easily known as A-PIE: Abstraction, Polymorphism, Inheritance and Encapsulation

Q10. What do you mean by method overriding?

Ans. If child class has the same method as declared in the parent class, this is called method overriding.

Q11. When throws keyword can be used?

Ans. Providing information to the programmer that there may happen an exception so that the normal flow can be maintained, Throws keyword is used to declare an exception.

Syntax of java throws

return_type method_demo() throws exception_class_demo{ 

//method code 

}

Q12. What is an abstract method?

Ans. It is a function that is declared but no implementation.  It lies in the heart of inheritance when you define certain tasks functions that are dealt with within the child’s classes differently.

Syntax

modifier abstract class demo {

//declare fields

//declare methods

abstract dataType methodName();

}

modifier class childClass extends demo {

dataType methodName(){}

}

Q13. What are the different types of loops?

Ans. Loops are used in a program to perform a similar task repeatedly. It also performs iterations in the program. There are three types of loops:

  •     Do while loop: Do while loop is executed by checking the condition of the end loop, i.e. if the condition is true, then the loop will execute; otherwise, it will come out of it.

do

{

statements.

}

while (condition);

  •     For loop: For loop is executed when it has all three conditions in it, i.e., initialization, condition, and increment/decrement operator.

 for (initialization; testing condition; increment/decrement)

{

         statement(s)

}

  •     While loop: While loop is executed continuously if the boolean statement is true. It will check the body of the loop before execution.

while (boolean condition)

{

   loop statements…

}

Q14. What is a constructor?

Ans. A constructor is a block of code that enables you to create an object of the class. It is called automatically when a new instance of an object is created.

Q15. Give an example of a class variable declaration?

Ans. Class variables are declared with static modifiers.

Public class product

{

Public static int Barcode;

}

Q16. What environment variables are required to run java programs?

Ans. PATH and CLASSPATH, JAVA_HOME and JRE_HOME are needed to run a simple java application and used to find JDK binaries which are used to run java programs on platforms like Windows and Linux.

Environment variables are used in the programs to know which directory is used to install files and where to store installed files.

Q17. What does JAXB stand for?

Ans. JAXB means Java API for XML binding. It is a fast and suitable way to bind Java representation to incorporate XML data in Java applications.

Q18. What are the new features for Java 8?

Ans. Java 8 is full of really interesting features at both the language level and the JVM level. Some of the features that are an absolute must to know about are:-

  • Parallel operations
  • Concurrent accumulators
  • Lambda Expressions
  • Generic type changes and improvements
  • Functional interfaces

Q19. What type of variables can a class consist?

Ans. A class comprises of an instance variable, class variable and local variable.

Q20. What is synchronization in Java?

Ans. Synchronization is used to control the access of multiple threads in the shared resources to provide better results. It also helps to prevent thread interference and solve consistent problems.

There are two types of synchronization:

  •     Process Synchronization
  •     Thread Synchronization

Example:

public class Syx{

  private static int c1 = 0;

  public static synchronized int getCount(){

return c1;

  }

  public synchoronized setCount(int c1){

this.c1 = c1;

  }

}

Q21. What is the default value of the local variable?

Ans. The class variables have default values. Local variables don’t have any default value.

Q22. What is a static keyword?

Ans. It is used for memory management to refer to the common property of all objects. If we apply java static keyword with any method is called as static method. Moreover, static can be used to class nested with another class, initialization block, process, and variable.

Example:

class Demo

{

static int x = 10;

static int y;  

// static block

static {

        System.out.println(“Static block initialized.”);

     y = x * 4;

}

public static void main(String[] args)

{

       System.out.println(“from main”);

       System.out.println(“Value of x : “+x);

       System.out.println(“Value of y : “+y);

}

}

Output:

Static block initialized.

from main

Value of x: 10

Value of y: 40

Q23. Is JVM platform independent?

Ans. No, JVM is not platform-independent as it is not written in Java.

Q24. Can a program be executed without main () method?

Ans. One can execute a program without a main method by using a static block.

Q25. What are the various access modifiers for Java sessions?

Ans. Java offers an array of access modifiers to aid you to set the amount of access you want for methods and fields in your classes. The types of access modifiers are:

  • Private
  • Default
  • Public
  • Protected

Q26. How do you avoid deadlock in Java?

Ans. We can achieve this by breaking the circular wait condition. For this, we need to arrange the code such that it imposes the ordering on acquisition and release of locks.

Q27. How can you implement to use an Object as key in HashMap?

Ans. To use any object as a Key in HashMap or Hashtable, it must implement equals and hashcode method in Java.

Q28. How do you convert bytes to a character in Java?

Ans. This is one of the most commonly asked Java interview questions; here is how you can frame the answer.

We can convert bytes to character or text data using character encoding. Incorrect choice of character encoding may change the meaning of the message as it interprets it differently.

Example:

public class Conv

{

  public static void main(String args[])

  {

byte b1 =70;

// char ch = b1;     

char ch = (char) b1;

    System.out.println(“byte value: ” + b1);     // prints 70

    System.out.println(“Converted char value: ” + ch);   // prints A (ASCII is 70 for F)

  }

}

Output:

byte value: 70

Converted char value: F

Q29. Can you override the static method?

Ans. No, a static method cannot be overridden because they are resolved in compile-time and not runtime.

Q30. How do you define Destructors in Java?

Ans. Generally, a destructor is a method that removes an object from the computer’s memory. Java lacks a destructor element, and instead, they make use of garbage collector for resource deallocation.

Q31. What is JSON?

Ans. JSON is an acronym for JavaScript Object Notation. Its format is text only and uses JavaScript syntax.

Also ReadTop Core Java Interview Questions and Answers

Q32. What is an Anonymous Class?

Ans. As the name suggests, an Anonymous Class is defined without a name in a single line of code using a new keyword.

Q33. What is the difference between Stack and Queue?

Ans. Stack is based on the Last in First out (LIFO) principle
Queue is based on FIFO (First In, First Out) principle.

Q34. What is a Package?

Ans. A package is a namespace of related classes and interfaces. They are similar to different folders on your computer.

Q35. How to access Java package from another package?

Ans. We can access the package from outside the package via three ways –

import package.*;

import package.classname;

fully qualified name

Example:

//save by X.java 

package p1; 

public class X{ 

  public void msg(){System.out.println(“Hey!”);} 

}

//save by Y.java 

package myp1; 

class Y{ 

  public static void main(String args[]){ 

   p1.X obj = new p1.X();

   obj.msg(); 

  } 

}

Output: Hey!

Q36. What is a pointer? Does Java support pointer?

Ans. A pointer helps to directly access the memory location using the address. Java does not have the concept of a pointer because improper handling of pointers results in memory leaks and other related problems. This makes Java a powerful language than C or C++,

Q37. What is an immutable object?

Ans. Immutable object cannot be modified once created. Software developers rely on immutable objects for creating simple and reliable codes.

Q38. What are wrapper classes?

Ans. Wrapper classes are used to convert or wrap Java primitives into the reference objects.

Features of java wrapper classes:

  •     Wrapper classes convert numeric strings into numeric values.
  •     They are used to store primitive data into the object.
  •     All wrapper classes use typeValue() method. It returns the object value and its primitive type.
  •     The wrapper classes use the valueOf() method.

Q39. What are the local variables?

Ans. A variable declared within the body of a method is a local variable. These variables need to be initialized before use.

Syntax

methodn1(){

<DataType> localvarName;

Q40. What are instance variables?

Ans. A variable declared inside a class, but outside a method is called an instance variable. These variables don’t need to be initialized before use, as they automatically initialized to their default values.

Key features of instance variables:

  •     They are declared in the class, i.e., outside the method.
  •     Instance, variables are created when the object is created, and it also destroys the purpose.
  •     Access modifiers are used in the instance variables.
  •     They are visible to all the methods, constructors, and blocks in the class.
  •     Default values are given to the instance variables. If the value is numeric, it will be ‘0’, and if the value is boolean then it will be ‘FALSE.’

Example:

class Taxes

{

int count; //Count is an Instance variable

/*…*/

}

Q41. What is the latest version of Java in 2020?

Ans. Java 14, released in March 2020, is the latest version of java available today.

Q42. How does Java handle integer overflows and underflows?

Ans. In java, overflow and underflow are handled by using low order bytes that can fit into the size of the type provided by the operation.

Q43. Why Java is not purely an object-oriented language?

Ans. In order to be a purely object-oriented language, Java must satisfy all the aspects of object-oriented. But because of the primitive data types, It is not a purely object-oriented language. Coders can work using primitive data types – byte, short, int, char, Boolean, and many more.

For example, both types will return the same value:

int i = 10; – Primitive Type

integer i = 10; Object Type

Another factor in Java is that we can always directly represent the static data without instantiation. Further, in Java, one can communicate with objects without actually calling their methods.

Also Read>>5 Latest Web Development Tools that you must know!

Q44. Name frequently used Java Tools.

Ans. Web developers know that Java is one of the most used commercial grade languages. Thus, it’s essential for developers to use Java tools like:

  • JDK (Java Development Kit)
  • Eclipse IDE
  • NetBeans
  • JRat
  • Junit

Q45. What is a Class in Java?

Ans. When talking about Java, a class represents a defined common set of properties and methods to all objects of the same type. Generally, a class includes components like a modifier, class name, superclass, interface, and body. For real-time java applications, several types of classes are used.

Few Ways to Create a Class in Java:

  • New keywords
  • forName method
  • Clone () method

Q46. What do you mean by JVM JRE and JVM and what is the major difference between the three?

Ans. Difference between JVM JRE and JVM are:

JDK JRE JVM
Full-Form Java Development Kit Java Run-Time Environment Java Virtual Machine
Comprises JRE + Development tools (debugger + compiler + JavaDoc Set of Libraries used by JVM at runtime JVM
Task It’s a full-featured SDK software development kit It is basically an implementation of JVM and it is essential to run any Java code It is used for Code loading, Verifying, Execution, and offers run time environment
Existence Exists Physically Exists Physically Doesn’t exists physically

Q47. Please introduce Java frameworks Spring.

Ans. Frameworks, a large body of pre-existing codes, is fast, efficient, and light-weighted. It is used to solve the coder’s specific problems very quickly. Java being fast-paced programming languages has widely used frameworks like JSF, Struts, and play!.

Among this, Spring framework is one of the most powerful and light-weighted frameworks used for Enterprise Java (JEE). Spring is widely used for developing Java-based applications.

Features of Java Framework – Spring

  • Extensible XML configuration
  • IoC container containing assembler code handling configuration management
  • Spring MVC framework
  • Support various dynamic languages
  • Supports recognized system modules
  • Compatible with various versions of Java
  • Simple to use, testable,
  • Loose coupling because of concepts like AOP

Note: Various hiring companies give special preference to candidates taking Java Certification courses. Enroll yourself now to fetch a handsome job as a Java Developer.

Q48. Define the Spring annotations that you use in projects.

Ans. Widely used Spring Annotations:

  • @Controller
  • @RequestMapping
  • @Qualifier
  • @Scope

Q49. What is Polymorphism?

Ans. Polymorphism, an ability to perform single tasks in multiple ways, in Java is divided into two parts – Compile-time and Runtime polymorphism.

Compile-time also called a static method is a process wherein the call during the overloading method is resolved at the same time of compilation.

Runtime polymorphism also known as dynamic dispatch has a provision to support the overriding of methods. This is done during the runtime.

Q50. What is the abstract class in Java? Is it similar or different when compared to C++?

Ans. The abstract class generally contains one or more than one abstract methods, and these abstract methods are declared, but they do not contain implementation. In Java, to make a class abstract, a separate keyword is required ‘abstract.’ But in C++, if any class comprises of at least one pure vital function, then the class automatically becomes abstract.

Example:

//Declare class using abstract keyword

abstract class X{

   //Define abstract method

   abstract void myMed();

   //This is concrete method with body

   void anotherMed(){

   //Does something

   }

}

Also ReadPython Vs Java – Which is better to learn

Q51. What is Java copy constructor?

Ans. Java has a special type of constructor called the Copy Constructor in Java that is used for delivering a copy of specified objects. This is mostly used when a coder wants to copy something that is heavy to instantiate. Also, it is recommended that in order to detach both objects, use the deep copy. Further, it also offers full control over object creation.

Q52. Define the advantage of Copy constructor over Object.clone().

Ans. Java experts pick copy constructor over the Object.clone() because copy constructor does not push to implement any specific interface but one can implement it as and when required. Similarly, it also allows modification in final fields.

Q53. Why Java doesn’t support multiple inheritances yet multiple interface implementation is possible?

Ans. Multiple inheritances refer to the process by which one inherits the properties and behaviour of multiple classes into one single class like in C++. But Java being a simple, robust, and secure language, it omits multiple inheritances usually called the Diamond Problem.

In Java 8, it supports default methods and that’s how a class can go ahead with the implementation of two or more interfaces.

Q54. What is a Java servlet?

Ans. Java developers when need to outspread the capabilities of a server, use Servlets. Basically, servlets are used in order to extend the applications that are hosted by a web server and it is deployed to design a dynamic web page as well by using Java. These servlets run on JVM and resist attacks. Unlike CGI (Common Gateway Interface) the servlets are portable.

Q55. Define the steps of creating a servlet in Java.

Ans. Servlet follows a lifecycle having four stages:

  • Loading
  • Initializing
  • Request Handling
  • Servlet destroying

So in order to go ahead with the process, first and foremost things is to create a servlet. Below is the process:

  • Develop a structured directory
  • Create the servlet
  • Compile
  • Add mappings into the web.xml file
  • Deploy the project by initiating server
  • Access it

Q56. What is a JSP in Java and are they better than servlets?

Ans. Java Server Pages (JSP) is a server-side technology that is used to create applications, dynamic web content, and independent web pages.

Yes, JSP is a better technology then servlets as they are very easy to maintain. Also, it doesn’t require any sort of recompilation or redeployment. JSP, being an extension to servlets, majorly covers most of its features.

Also ReadJava Certification Questions and Answers

Q57. A new version of Eclipse IDE for Java has arrived. Define something about it.

Ans. Recently in 2019, the latest version of Eclipse was launched – Eclipse IDE 2019-06. Some of the updated features are:

  • New themes and styling
  • Includes Support from Java 12 and Java editor benefiting Java developers
  • New Plug-in, API tools are included

Q58.  Explain the difference between equals() and == in Java?

Ans. equals() and == operator are used to compare objects and find the equality between two objects, but there is some difference between both of them:

  •     equals() is a method while == is an operator
  •     == operator is used for reference comparison( check whether both objects are in same memory) while equals() method is used for content comparison( compare values in an object)

Coding example:

public class Demo {

public static void main(String[] args)

{

String s1 = new String(“NICK”);

String s2 = new String(“NICK”);

System.out.println(s1 == s2);

System.out.println(s1.equals(s2));

}

}

Output:

false

True

Q59. What is an infinite loop?

Ans. The infinite loop is an instruction in which the loop has no exit function, so it repeats endlessly. The infinite loop will terminate automatically when the application ends.

Example:

public class InfiniteLoop

{

public static void main(String[] arg) {

for(;;)

System.out.println(“Hello Guys”);

}

}

Q60. What is the output of the following java code?

public

class Demo {

public static void main(String[] args)

{

     int a = 10;

     if (a) {

            System.out.println(“HELLO STUDENTS”);

     } else {

            System.out.println(“BYE”);

     }

}

}

Ans. Output: Compile time error

If statement should have argument of boolean type

Q61. What is a classloader in Java?

Ans. Classloader is a class in java that is used to load other class files from the network, file system, and other sources. Java code in classes is compiled by javac compiler and executed by JVM. Java stores three built-in classloaders:

  •     Bootstrap ClassLoader
  •     Extension ClassLoader
  •     System/Application ClassLoader

Q62. What is serialization in Java?

Ans. In this process, objects are converted into byte codes to store the object into memory space. The main task is to save the state of the object in order.

class X implements Serializable{

// Y also implements Serializable

// interface.

Y ob=new Y(); 

}

Q63. What is the purpose of garbage collection in Java, and when is it used?

Ans. Garbage collection is an automatic process. The memory is allocated to all the java programs. At the run time, there are some objects created at the heap and take the memory space. The garbage collectors delete these unwanted objects.

Q64. What is runtime polymorphism or dynamic method dispatch?

Ans. Runtime polymorphism or dynamic method dispatch is the process in which the overridden methods are resolved at runtime not at compile time.

class Car {

void run()

{

System.out.println(“car is running”);

} }

class Audi extends Car {

void run()

{

System.out.prinltn(“Audi is running safely with 100km”);

}

public static void main(String args[])

{

Car b= new Audi(); //upcasting

b.run();

} } 

 

Conclusion

We have created a collection of best Java interview questions to help you prepare for your upcoming interview questions. It is a vast topic and needs a thorough understanding and study of all the aspects. It is important to go through every Java interview question diligently and ensure that you leave no stone unturned to succeed in your interview. Just stay positive and go well-prepared.

 

In case you have recently completed a professional course/certification,

Click here to submit your review and get FREE certification highlighter worth Rs. 500.

4.50 avg. rating (90% score) - 8 votes