230+ Top Java Interview Questions in 2024

java interview questions

Everyone knows how Java has been a perennial contributor to software development. Anyone with a flair for IT & Development wants a career in Java. Are you also one of those aspiring Java professionals? Our set of Java Interview Questions has motivated many such aspirers, and the same can be done for folks like you. Understand what a recruiter is looking for in a Java professional and how you can impress them. By the end of this blog, you will gain hands-on Java knowledge and be able to ace Java interviews in job roles like Junior Developer, Senior Developer, Architect, Java Web Developer, Java Android Developer, and Java EE developer.

So, are you ready to have a career in Java? Let’s get started!

This article provides a list of Java Interview Questions that are categorized by level of difficulty and cover a range of topics related to Java.

  • Java Interview Questions for Freshers
  • Core Java Interview Questions
  • Java Interview Questions for Experienced

Java Interview Questions for Freshers

If you are starting with Java and wish to land a job in one go, this section is just for you. We will cover all the basic Java interview questions the hiring managers ask and the solutions they expect you to come up with. Start your preparation today!

1. What is Java?

Java is defined as an object-oriented general-purpose programming language.The design of the programming language allows programmers to write code anywhere and execute it everywhere without having to worry about the underlying computer architecture. Also known as “write once, run anywhere,” (WORA).

2. Write a program to print “Hello World” in Java?

Writing the “Hello World” program is easy in java. Here is a program to print Hello World:

Hello World in Java:

public class FileName {
  public static void main(String args[]) {
    System.out.println("Hello World!");
  }
} 

3. How to install Java?

This is one of the most basic Java interview questions. Install Java through command prompt so that it can generate necessary log files to troubleshoot the issue.

How to install java
Go to java.com and click on the Free Java Download button.
Click on the Save button and save Java software on the Desktop
Verify that Java software is saved on the desktop.
Open Windows Command Prompt window.
Windows XP: Click Start -> Run -> Type: cmd
Windows Vista and Windows 7: Click Start -> Type: cmd in the Start Search field.
cd <Java download directory> (for example Downloads or Desktop etc.)
IRun the installer and follow onscreen instructions.

Check out this Free Java Course, which explains the Java Installation Process in detail.

This second example shows how to reverse a string word by word. Check the below code


import java.util.*;
class ReverseString
{
  public static void main(String args[])
  {
    String original, reverse = """";
    Scanner in = new Scanner(System.in);

    System.out.println(""Enter a string to reverse"");
    original = in.nextLine();

    int length = original.length();

    for (int i = length - 1 ; i >= 0 ; i--)
      reverse = reverse + original.charAt(i);

    System.out.println(""Reverse of the string: "" + reverse);
  }
}

5. What is a thread in Java?

Threads allow a program to operate more efficiently by doing multiple things at the same time. A thread is a lightweight program that allows multiple processes to run concurrently. Every java program has at least one thread called the main thread, the main thread is created by JVM. The user can define their own threads by extending the Thread class (or) by implementing the Runnable interface. Threads are executed concurrently. It can be created by extending the Thread class and overriding its run() method:

Extend Syntax

public class MyClass extends Thread { 
  public void run() { 
    System.out.println("This code is running in a thread"); 
  } 
} 
OR 

public static void main(String[] args){//main thread starts here 
} 

6. How to take input in Java?

The below code explains how to take input in java using a scanner

Input in Java Code 1

Scanner in = new Scanner(System.in);
      System.out.print(""Please enter hour 1: "");
      int hour1 = in.nextInt();
      System.out.print(""Please enter hour 2: "");
      int hour2 = in.nextInt();
      System.out.print(""Please enter minute 1: "");
      int min1 = in.nextInt();
      System.out.print(""Please enter minute 2: "");
      int min2 = in.nextInt();

Input in Java Code 2

class MyClass {
    public static void main(String[ ] args) {
        Scanner a = new Scanner(System.in);
        //Scanner b = new Scanner(System.in);       
        System.out.println (a.nextLine());
        System.out.println(a.nextLine());
    }
}

Then type this way:
a
b

Code on how to take character input in Java

import java.util.Scanner;   
public class CharacterInputExample1  
{   
public static void main(String[] args)   
{   
Scanner sc = new Scanner(System.in);   
System.out.print(""Input a character: "");  
// reading a character   
char c = sc.next().charAt(0);   
//prints the character   
System.out.println(""You have entered ""+c);   
}   
} 

Code on how to take string input in java

import java.util.Scanner;  // Import the Scanner class

class MyClass {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println(""Enter username"");

    String userName = myObj.nextLine();  // Read user input
    System.out.println(""Username is: "" + userName);  // Output user input
  }
}

7. How to set a path in Java?

Windows 10 and Windows 8

  • In Search, search for and then select: System (Control Panel)
  • Click the Advanced system settings link.
  • Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  • In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
  • Reopen Command prompt window, and run your java code.
Mac OS X
To run a different version of Java, either specify the full path or use the java_home tool:
% /usr/libexec/java_home -v 1.8.0_73 --exec javac -version
Solaris and Linux
To find out if the path is properly set:
In a terminal window, enter:
% java -version
This will print the version of the java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set.
Determine which java executable is the first one found in your PATH
In a terminal window, enter:
% which java 

8. What is enumeration in Java?

Enumeration means a list of named constants. In Java, enumeration defines a class type. An Enumeration can have constructors, methods, and instance variables. It is created using the enum keyword. Each enumeration constant is public, static, and final by default. Even though enumeration defines a class type and has constructors, you do not instantiate an enum using new. Enumeration variables are used and declared in much the same way as you do a primitive variable.

9. What is inheritance in Java?

The process by which one class acquires the properties(data members) and functionalities(methods) of another class are called inheritance. The aim of inheritance in java is to provide the reusability of code so that a class has to write only the unique features and the rest of the common properties and functionalities can be extended from another class.

Child Class: The class that extends the features of another class is known as a child class, subclass, or derived class.

Parent Class: The class whose properties and functionalities are used(inherited) by another class is known as the parent class, superclass, or Base class.

inheritance in java

Know more about Inheritance in java.

10. Why multiple inheritances are not supported in Java?

Java supports multiple inheritances through interfaces only. A class can implement any number of interfaces but can extend only one class. Multiple inheritances is not supported because it leads to a deadly diamond problem.

11. Can the interface in Java be inherited?

Yes, interfaces can be inherited in java. Hybrid inheritance and hierarchical inheritance are supported by java through inheritable interfaces.

12. How to compare two strings in Java?

The below code explains about comparing two strings in java

// These two have the same value
new String(""test"").equals(""test"") // --> true 

// ... but they are not the same object
new String(""test"") == ""test"" // --> false 

// ... neither are these
new String(""test"") == new String(""test"") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
""test"" == ""test"" // --> true 

13. What is an abstraction in Java?

Objects are the building blocks of Object-Oriented Programming. An object contains some properties and methods. We can hide them from the outer world through access modifiers. We can only provide access to the other programs’ required functions and properties. This is the general procedure to implement abstraction in OOPS.

14. How is Abstraction achieved in Java?

Abstraction is achieved in Java by the use of abstract classes and abstract methods.

15. What is encapsulation in Java?

The idea behind encapsulation is to hide the implementation details from users. If a data member is private, it can only be accessed within the same class. No outside class can access private data member (variable) of other class.

However, if we set up public getter and setter methods to update (for example void setName(String Name ))and read (for example String getName()) the private data fields then the outside class can access those private data fields via public methods.

16. Why do we need encapsulation in Java?

Encapsulation in Java is a mechanism of wrapping the code and data (variables)acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class.

17. What is a collection in java?

Collections are like containers that group multiple items in a single unit. For example, a jar of chocolates, a list of names, etc.

Collections are used in every programming language and when Java arrived, it also came with a few Collection classes – Vector, Stack, Hashtable, Array.

Collection in java

18. What is API in Java?

Java application programming interface (API) is a list of all classes that are part of the Java development kit (JDK). It includes all Java packages, classes, and interfaces, along with their methods, fields, and constructors. These pre-written classes provide a tremendous amount of functionality to a programmer.

19. How to initialize an array in Java?

Initialization of array in java is explained in the below code

"int[] arr = new int[5];	 // integer array of size 5 you can also change data type
String[] cars = {""Volvo"", ""BMW"", ""Ford"", ""Mazda""};"

20. How to take input from users in Java?

import java.util.Scanner;
  Scanner console = new Scanner(System.in);
  int num = console.nextInt();
  console.nextLine() // to take in the enter after the nextInt() 
  String str = console.nextLine();

OR Use the below code

import java.util.Scanner;  // Import the Scanner class

class MyClass {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println(""Enter username"");

    String userName = myObj.nextLine();  // Read user input
    System.out.println(""Username is: "" + userName);  // Output user input
  }
}

21. What is static in Java?

In Java, a static member is a member of a class that isn’t associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.

22. Why the main method is static in java?

Java main() method is always static, so the compiler can call it without the creation of an object or before the creation of an object of the class. In any Java program, the main() method is the starting point from where the compiler starts program execution. So, the compiler needs to call the main() method.

23. What is a package in Java?

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts and to write better maintainable code. Packages are divided into two categories:

Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)

24. How to create a package in Java?

To make a bundle, you pick a name for the bundle (naming shows are talked about in the following area) and put a bundle articulation with that name at the head of each source record that contains the sorts (classes, interfaces, lists, and explanation types) that you need to remember for the bundle.

25. How to sort an array in Java?

"import java. util. Arrays;
Arrays. sort(array);"

26. What is an abstract class in Java?

A class that is declared using the “abstract” keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-abstract class) cannot have abstract methods.

27. What is a method in Java?

A method is a block of code that only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.

28. What is a class in Java?

A class in java is a template that describes the data and behaviour associated with instances of that class. When you instantiate a class you create an object that looks and feels like other instances of the same class. The data associated with a class or object is stored in variables; the behaviour associated with a class or object is implemented with methods.

29. How to enable Java in chrome?

  • In the Java Control Panel, click the Security tab
  • Select the option Enable Java content in the browser
  • Click Apply and then OK to confirm the changes
  • Restart the browser to enable the changes

30. What is a string in Java?

The string is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, the string is an immutable object which means it is constant and cannot be changed once it has been created.

31. What is an exception in Java?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.

32. What is a singleton class in Java?

The singleton design pattern is used to restrict the instantiation of a class and ensures that only one instance of the class exists in the JVM. In other words, a singleton class is a class that can have only one object (an instance of the class) at a time per JVM instance.

33. How to create a singleton class in Java?

Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor private so that you can restrict the creation of the object. Provide a static method to get an instance of the object, wherein you can handle the object creation inside the class only. In this example, we are creating an object by using a static block.

public class MySingleton {
 
    private static MySingleton myObj;
     
    static{
        myObj = new MySingleton();
    }
     
    private MySingleton(){
     
    }
     
    public static MySingleton getInstance(){
        return myObj;
    }
     
    public void testMe(){
        System.out.println(""Hey.... it is working!!!"");
    }
     
    public static void main(String a[]){
        MySingleton ms = getInstance();
        ms.testMe();
    }
}

34. What is an array in Java?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the “Hello World!” application. This section discusses arrays in greater detail.

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array.

An array of 10 elements. Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

35. What is garbage collection in Java?

Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to be deleted. The garbage collection implementation lives in the JVM. Each JVM can implement garbage collection however it pleases; the only requirement is that it meets the JVM specification. Although there are many JVMs, Oracle’s HotSpot is by far the most common. It offers a robust and mature set of garbage collection options.

36. How is garbage collection done in Java?

Java has an automatic built-in garbage collection mechanism in place. Apart from the built-in mechanism, manual initiation of garbage collection can also be done by using the gc() of the system class.

37. What is JVM in Java?

A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describes what is required in a JVM implementation.

38. How does hashmap work internally in Java?

HashMap in Java works on hashing principles. It is a data structure that allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link keys and values in HashMap.

39. What is bytecode in Java?

Bytecode is the compiled format for Java programs. Once a Java program has been converted to bytecode, it can be transferred across a network and executed by Java Virtual Machine (JVM). Bytecode files generally have a .class extension.

40. How to set classpath in Java?

  • Select Start, select Control Panel, double click System, and select the Advanced tab.
  • Click Environment Variables. In the section System Variables, find the PATH environment variable and select it.
  • In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK.

41. How to connect databases in Java?

  • Install or locate the database you want to access.
  • Include the JDBC library.
  • Ensure the JDBC driver you need is on your classpath.
  • Use the JDBC library to obtain a connection to the database.
  • Use the connection to issue SQL commands.
jdbc connection interface

42. What is DAO in Java?

Dao is a simple java class that contains JDBC logic. The Java Data Access Object (Java DAO) is an important component in business applications. Business applications almost always need access to data from relational or object databases and the Java platform offers many techniques for accessing this data.

43. What is AWT in Java?

The Abstract Window Toolkit (AWT) is Java’s original platform-dependent windowing, graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation Classes (JFC) — the standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support the Abstract Window Toolkit.

44. What is a framework in Java?

Frameworks are large bodies (usually many classes) of prewritten code to which you add your own code to solve a problem in a specific domain. Perhaps you could say that the framework uses your code because it is usually the framework that is in control. You make use of a framework by calling its methods, inheritance, and supplying “callbacks”, listeners, or other implementations of the Observer pattern.

45. How to update Java?

Manually updating Java on Windows is typically done through the Java Control Panel.

Windows 10: Type “java” into the Windows/Cortana search box, located in the lower left-hand corner of your screen. When the pop-out menu appears select Configure Java, located in the Apps section.

46. What is a variable in Java?

A Java variable is a piece of memory that can contain a data value. A variable thus has a data type. Data types are covered in more detail in the text on Java data types. Variables are typically used to store information which your Java program needs to do its job.

47. What is the difference between Java and Javascript?

The main differences between JavaScript and Java are:

1. JavaScript is used for Front End development while java is used for Back End Development. i.e.

JavaScript is responsible for the dynamic behaviour of a webpage. Mainly, JavaScript handles events, cookies, ajax (Asynchronous JavaScript and XML), etc. in a website. JavaScript is the heart of a Dynamic User Interface of a Web Page while Java is the best programming language for software engineers and can be used with JSP (Java Server pages) for handling the back end.

2. Java Script is a dynamically typed language and Java is a statically typed language: i.e

In JavaScript, the datatype of one variable can be changed:

var string = "hello world"; 
string = 4; 
document.write(string); 

OUTPUT IS 4
document.write( ) will now print ‘4′ on the browser.

But in Java, the datatype of one variable cannot be changed and Java shows the error.

int number = 45;
number = “hello world”; //ERROR!!!!!!!

3. JavaScript is a scripting language while Java is a programming language:

Like other languages, Java also needs a compiler for building and running the programs while JavaScript scripts are read and manipulated by the browser.

4. Java and JavaScript are very different in their SYNTAX.

For example:

Hello World Program in JAVA:

public class hello 
{ 
        public static void main(String[] args) 
        { 
                System.out.println("Hello World"); 
        } 
} 
Hello World Program in JavaScript:

<script> 
        document.write("Hello World"); 
</script> 

5. Both languages are Object Oriented but JavaScript is a Partial Object-Oriented Language while Java is a fully Object-Oriented Langauge. JavaScript can be used with or without using objects but Java cannot be used without using classes.

48. What is public static void main in Java?

This is the access modifier of the main method. It has to be public so that the java runtime can execute this method. Remember that if you make any method non-public then it’s not allowed to be executed by any program, there are some access restrictions applied. So it means that the main method has to be public. Let’s see what happens if we define the main method as non-public.

When java runtime starts, there is no object of the class present. That’s why the main method has to be static so that JVM can load the class into memory and call the main method. If the main method won’t be static, JVM would not be able to call it because there is no object of the class is present.

Java programming mandates that every method provide the return type. Java’s main method doesn’t return anything, that’s why its return type is void. This has been done to keep things simple because once the main method is finished executing, the java program terminates. So there is no point in returning anything, there is nothing that can be done for the returned object by JVM. If we try to return something from the main method, it will give a compilation error as an unexpected return value.

49. Why do we use interface in Java?

It is used to achieve total abstraction. Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. It is also used to achieve loose coupling. Interfaces are used to implement abstraction.

50. What is the purpose of serialization in Java?

Object Serialization is a process used to convert the state of an object into a byte stream, which can be persisted into a disk/file or sent over the network to any other running Java virtual machine. The reverse process of creating an object from the byte stream is called deserialization.

51. What is a functional interface in java?

A functional interface in Java is an interface that contains only a single abstract (unimplemented) method. A functional interface can contain default and static methods which do have an implementation, in addition to the single unimplemented method.

52. What is ‘this’ keyword in java?

The ‘this’ keyword refers to the current object in a method or constructor. The most common use of this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

53. What is classpath in java?

The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)

54. Why is Java Platform Independent?

At the time of compilation, the java compiler converts the source code into a JVM interpretable set of intermediate form, which is termed as byte code. This is unlike the compiled code generated by other compilers and is non-executable. The java virtual machine interpreter processes the non-executable code and executes it on any specific machine. Hence the platform dependency is removed.

55. What is Method overloading? Why is it used in Java?

Method overriding is a process in which methods inherited by child classes from parent classes are modified as per requirement by the child class. It’s helpful in hierarchical system design where objects share common properties.

Example: Animal class has properties like fur colour, and sound. Now dog and cat classes inherit these properties and assign values specific to them to the properties.

println() prints any data type passed to it as a string. 

public class Add_Overload { 
    void add(int x, int y){ 
        System.out.println(x+y); 
    } 
    void add(double x, double y){ 
        System.out.println(x+y); 
    } 
    void add(double x, int y){ 
        System.out.println(x+y); 
    } 
    public static void main(String args[]){ 
        Add_Overload a= new Add_Overload(); 
        a.add(10,20); 
        a.add(20.11,11.22); 
        a.add(20.11,2); 

    } 

56. Why is Java Robust?

  • Java is termed as robust because of the following features:
  • Lack of pointers: Java does not have pointers which makes it secure
  • Garbage Collection: Java automatically clears out unused objects from memory which are unused
  • Java has strong memory management.
  • Java supports dynamic linking.

57. Why is Java Secure?

Java does not allow pointers. Pointers give access to actual locations of variables in a system. Also, java programs are bytecode executables that can run only in a JVM. Hence java programs do not have access to the host systems on which they are executing, making it more secure. Java has its own memory management system, which adds to the security feature as well.

58. What is the difference between JDK and JVM?

JDK is a software environment used for the development of Java programs. It’s a collection of libraries that can be used to develop various applications. JRE (Java Runtime Environment) is a software environment that allows Java programs to run. All java applications run inside the JRE. JVM (java virtual machine) is an environment that is responsible for the conversion of java programs into bytecode executables. JDK and JRE are platform-dependent whereas JVM is platform-independent.

59. What are the features of Java?

  • Java is a pure Object Oriented Programming Language with the following features:
  • High Performance
  • Platform Independent
  • Robust
  • Multi-threaded
  • Simple
  • Secure

60. Does Java Support Pointers?

Pointers are not supported in Java to make it more secure.

61. Why are Static variables used in Java?

Static methods and variables are used in java to maintain a single copy of the entity across all objects. When a variable is declared as static it is shared by all instances of the class. Changes made by an instance to the variable reflect across all instances.

public class static_variable {

    static int a;
    static int b;
    static_variable(){
        a=10;
    }
    int calc_b(){
        b=a+10;
        return b;
    }
void print_val(){
    System.out.println(this.b);
}
public static void main(String args[]){
    static_variable v=new static_variable();
    v.calc_b();
    v.print_val();
    static_variable v1=new static_variable();
    v1.print_val();
}
}

62. What are static methods, static variables, and static blocks?

Static methods are methods that can be called directly inside a class without the use of an object.
Static variables are variables that are shared between all instances of a class.
Static blocks are code blocks that are loaded as the class is loaded in memory.

63. What’s the use of static methods?

Static methods are used when there is no requirement of instantiating a class. If a method is not going to change or be overridden then it can be made static.

64. How to get a string as user input from the console?

We have to instantiate an input reader class first. There are quite a few options available, some of which are BufferedReader, and InputStreamReader Scanner.
Then the relative functionality of the class can be used. One of the most prevalently used is nextLine() of Scanner class.

65. How can we sort a list of elements in Java?

The built-in sorting utility sort() can be used to sort the elements. We can also write our custom functions, but it’s advisable to use the built-in function as it’s highly optimized.

66. What is the difference between throws and throws in Java?

The throw is used to actually throw an instance of java.lang.Throwable class, which means you can throw both Error and Exception using the throw keyword e.g.

throw new IllegalArgumentException("size must be multiple of 2") 


On the other hand, throws are used as part of method declaration and signals which kind of exceptions are thrown by this method so that its caller can handle them. It’s mandatory to declare any unhandled checked exception in the throws clause in Java. Like the previous question, this is another frequently asked Java interview question from errors and exception topics but too easy to answer.

67. Can we make an array volatile in Java?

Yes, you can make an array volatile in Java, but only the reference is pointing to an array, not the whole array. What I mean if one thread changes the reference variable to point to another array, that will provide a volatile guarantee. Still, if multiple threads are changing individual array elements they won’t be having happens before guarantee provided by the volatile modifier.

68. Can I store a double value in a long variable without casting?

No, you cannot store a double value into a long variable without casting because the range of double is more than long, and we need to type cast. It’s not difficult to answer this question, but many developers get it wrong due to confusion on which one is bigger between double and long in Java.

69. Which one will take more memory, an int or Integer?

An Integer object will take more memory as Integer is an object and it stores metadata overhead about the object but int is a primitive type, so it takes less space.

70. What is the difference between a nested static class and top-level class?

A public top-level class must have the same name as the name of the source file, there is no such requirement for a nested static class. A nested class is always inside a top-level class and you need to use the name of the top-level class to refer nested static class e.g. HashMap.Entry is a nested static class, where HashMap is a top-level class and Entry is nested, static class.

71. What is the use of the final keyword?

The final keyword is used to declare the final state of an entity in java. The value of the entity cannot be modified at a later stage in the application. The entity can be a variable, class, object, etc.
It is used to prevent unnecessary modifications in a java application.

72. What’s the difference between deep copy and shallow copy?

Shallow copy in java copies all values and attributes of an object to another object and both objects reference the same memory locations.

Deep copy is the creation of an object with the same values and attributes of the object being copied but both objects reference different memory locations.

72. What’s the use of the default constructor?

The default constructor is a constructor that gets called as soon as the object of a class is declared. The default constructor is un-parametrized. The generic use of default constructors is in the initialization of class variables.

class ABC{ 
    int i,j; 
    ABC(){ 
        i=0; 
        j=0; 
    } 
} 

Here ABC() is a default constructor.

73. What is Object cloning?

Object cloning is the process of creating an exact copy of an object of a class. The state of the newly created object is the same as the object used for cloning.
The clone() method is used to clone objects. The cloning done using the clone method is an example of a deep copy.

74. Why are static blocks used?

They serve the primary function of initializing the static variables. If multiple static blocks are there they are executed in the sequence in which they are written in a top-down manner.

75. What’s the difference between String and String Builder class in java?

Strings are immutable while string Builder class is mutable. The string builder class is also synchronized.

76. How to calculate the size of an object?

The size of an object can be calculated by summing the size of the variables of the class the object is instantiated from.
If a class has an integer, a double variable defined in it then the size of the object of the class is size(int)+size(double).
If there is an array, then the size of the object would be the length of array*size of data type of array.

77. What’s the difference between == and .equals()?

“==” is an operator, whereas .equals() is a function.
“==” checks if the references share the same location, whereas .equals() checks if both object values are the same on evaluation.

78. Tell us something about the JIT compiler.

One of the most important questions asked in the Java interview. JIT(Just-in-time) compiler is a part of Java Virtual Machine and describes a technique used to run a program. It aims to improve the performance of Java programs by compiling byte code into native machine code to run time. It converts code at runtime as demanded during execution. Code that benefits from the compilation is compiled; the rest of the code is interpreted. This improves the runtime performance of programs. For compilation, JVM directly calls the compiled code, instead of interpreting it. The biggest issue with JIT-compiled languages is that the virtual machine takes a couple of seconds to start up, so the initial load time is slower.  

There are three types of JIT compilers:

  • Pre-JIT: This compiler compiles complete source code into native code in a single compilation cycle and is performed at the time of deployment of the application.
  • Econo-JIT: Only those methods are called at runtime are compiled. When not required, this method is removed.
  • Normal-JIT: Only those methods called at runtime are compiled. These methods are compiled and then they are stored in the cache and used for execution when the same method is called again.

Core Java interview questions

Let’s take a look at the commonly asked core java interview questions for experienced professionals.

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

There are some differences between Java and C++  as follows:

C++ Java
C++ supports both Procedural Oriented Programming and Object-oriented Programming models. Java Supports only object-oriented programming models.
C++ can easily access the native libraries inside the system.There’s no direct call support in Java. 
C++ is a platform-dependent programming language. Therefore, it is not portable. Java is a portable programming language as it is platform-independent. 
C++ is a language that is only compiled. Java is a programming language that is both compiled and interpreted.
The management of memory in C++ is manual. The JRE controls memory management in java. 

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

A. There are mainly two things that come in the Java Download file:

i. JDK

ii. JRE

The difference between these two is as follows:

JDK JRE
JDK stands for Java Development Kit.JRE stands for Java Runtime Environment.
JDK is ideally used for software development or other developmental work.JRE is a software and an environment that provides space for executing Java Programs.
JDK comes under the installer file. So, we don’t have to install it separately.JRE doesn’t need an installer as it only has a runtime environment. 
JDK is platform dependent. JRE is also platform dependent.
JDK package is also useful in debugging the developed applications.JRE supports files only when we are running our program. 

3. What are the Memory Allocations available in Java?

A. The memory allocations in Java are divided into five different types:

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

4. What are the differences between Heap and Stack Memory in Java?

Heap Memory is used when we are storing objects while the stack is used to store the order of these variables for execution. There are some differences between heap and stack memory as follows:

Heap MemoryStack Memory
The memory allocated in heap memory is in random order.The memory allocated in Stack Memory is in a Contiguous block.
The main issue in heap memory is memory fragmentation. It has a shortage of memory issues. 
The allocation and deallocation of memory are done manually in heap memory. The allocation and deallocation are done automatically by the compiler. 
The access time of heap memory is slow. In the case of Stack memory, it can be accessed faster. 

5. What is an Association?

Association is a connection between two different classes through their objects but has now ownership over another. Let us take an instance of a doctor and a patient where a doctor can be associated with a number of patients or many patients. So, here the association is one-to-many. 

6. Define Copy Constructor in Java

A copy constructor is used for creating objects by the use of another object of the same class in java. The copy constructor returns a duplicate copy of the existing object of the class. It is used only for the initialization and is not applicable when the assignment operator is used instead. 

7. What is an object-oriented paradigm?

Object-oriented paradigm is a programming paradigm where all the items are considered as ‘objects’, that are used to store code and values. The values are stored in the form of fields while the code is the procedure to create the objects. In an object-oriented paradigm, the procedures are attached to objects and these procedures can be accessed or modified easily using the objects.

8. Explain Java String Pool.

In Java heap memory, the string pool is the storage area where the value of each string is stored. These values are defined in the program and an object of type string is created in the stack. Also, the instance of this string is created in the heap that contains the value of the string. 

9. Pointers are used in C/C++. Why does Java not make use of pointers?

The most important question asked in the Java interview.

  1. Java does not use pointers because pointers are quite complicated and unsafe. Java codes are simple and making use of pointers makes the code complex.
  2. Java uses reference types to hide pointers and programmers feel convenient to deal with reference types without using pointers. This is what makes java different from C/C++.
  3. Use of pointers also causes potential errors.
  4. Memory allocation is managed by Java virtual machine so pointers are not used because the user can directly access memory by using pointers.
  5. Java works on the Internet. Applets are used on the internet. By using pointers, one can easily identify the address of variables, methods and also can find confidential information of another user on the internet. This could be harmful to leaking important information. At the same time, the procedure of garbage collection become quite slow.

Thus, in Java pointers are not used.

10. What do you understand by an instance variable and a local variable?

One of the important questions for the Java interview.

A variable is a data container that contains data given to a memory location in the program and its value can be changed during the execution of the program. Users can perform operations on the variable of a memory location. The most important part is we need to declare all the variables before execution while writing a program.

Instance Variable: Instance variables are accessed by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of the object. When we create an object instance variable is created and when we destroy the variable is destroyed. Every object has its copy of instance variables. Only instance variables will be impacted if certain changes are to be done.

Example:

Class Student {

Public String studentName;

Public double student years;

Public int student;

}

Local Variable: Local variables are declared within programming blocks. These variables are created when block, method, or constructor is started and variable is destroyed once block, method, or constructor exists. Access is limited to the method in which it is declared. Local variable decreases the complexity of code. Before executing, these variables are needed to initialize. It does not include any access modifiers like private, public, protected, etc.

Example:

public void student() {

String student name;

double student years;

int studentAge;

}

11. What do you mean by data encapsulation?

Data Encapsulation is wrapping up data in a single unit. It prevents the data from being accessed by the user. We hide the data variables inside the class and specify the access modifiers so that they are not accessible to other classes. Encapsulation mainly deals with data. It is achieved by declaring all the variables in the class as private and public methods. Thus, data encapsulation is also a kind of “data hiding” and “abstraction”. 

In Java, there are two methods for implementing encapsulation.

  1. Use the access modifier” private” to declare the class member variables.
  2. To access these private member variables and change their values, we have to provide the public getter and setter methods respectively.

Data Hiding increases in flexibility, reusability, and easy testing code are the advantages of data encapsulation.

This question is frequently asked in Java interviews.

12. Can you tell the difference between the equals () method and the equality operator (==) in Java?

Equality (==) is the operator and equals () is a method. They both are used for comparison.

The equals () method:

  • Equals () is a method.
  • It is used to compare the actual content of the object.
  • We cannot use the equals method with primitives.
  • The equals () method can compare conflicting objects utilizing the equals () method and returns “false”.
  • Equals () method can be overridden.
  • Content Comparison

The equality (==) operator:

  • Equality (==) is an operator.
  • It is used to compare the reference values and objects.
  • We can use the equality operator with objects and primitives.
  • The equality (==) operator can’t compare conflicting objects, so the time compiler surrounds the compile-time error.
  • Equality (==) operator cannot be overridden.
  • Address Comparison.

This is one of the asked Java interview questions.

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

JDK stands for Java Development Kit, a package containing developer tools and JRE. JDK is used to develop applets, applications, and components of Java using the Java programming language. It also contains numerous tools that are used for developmental work. These tools include debuggers, compilers, etc. 

There are some variants of JDK as follows:

  • JDK Standard Edition: This edition of JDK is the minimum requirement to run a java application as it provides the base to run applications.
  • JDK Enterprise Edition: JDK Enterprise Edition (EE) is developed by extending JDK Standard Edition with specifications that help developers create applications. 
  • JDK Micro Edition: The micro edition of JDK or ME is used to develop applications and their deployment where the portable java code is embedded in mobile devices. 

14. What are Access Specifiers and Types of Access Specifiers?

The Access Specifiers in java are the predefined keywords that can be used to set the accessibility of methods and classes. You can also change the access levels of methods, classes, constructors, and fields using Access Specifiers. As the name suggests, Access Specifiers means access to any member is specified. There are four types of Access Specifiers:

  • Public
  • Private
  • Protected
  • Default

15. Define Late Binding

The name late binding defines itself that the compiler doesn’t decide when the method is to be called, and it should leave it all to the runtime. It means the binding should be done later at runtime because the compiler may not have access to the method implementation code. Late binding occurs at the time of method code segment due to the unknown runtime of the code. For example, the parent and child classes of the same method are overridden in dynamic or late binding. 

16. Define Dynamic Method Dispatch

It is a method where we resolve the call to overridden method at run time instead of resolving it at compile time. To call the overridden method where we first call the superclass’s method. All this process is called Run-time polymorphism. 

17. What is the Daemon Thread?

Daemon thread is used to perform tasks like garbage collection in the program’s background. It is a low-priority thread in java that provides services to the user thread. The life of Daemon Thread depends on the mercy of user threads, which means when all the user threads die, JVM will terminate Daemon Thread too. Collection of garbage in java and finalizer are some of the examples of Daemon Thread. 

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

“>>” is known as Binary Right Shift Operator where the left operand value is moved right by the number we specify by the right operand. This operator is responsible for shifting the sign bits towards the right.

“>>>” is known as the Shift Right to Zero operator where the left operand value is moved right by the specified number of bits and the shifted values are filled with ‘0’. This operator is responsible for shifting the bits by filling them with zero (0). 

19. What is JDBC?

JDBC stands for Java Database Connector, an API that executes the query to connect with the database. JDBC is a part of Java Standard Edition and uses its drivers to make connectivity with the database. JDBC acts as an abstraction layer that establishes the connection between the Java application and an existing database. The JDBC has four types of drivers:

  • Native driver
  • JDBC-ODBC bridge driver
  • Thin driver
  • Network Protocol Driver
JDBC Driver java

20. Explain the various directives in JSP.

These are the messages that give instructions to the web container for translating a JSP page into the corresponding servlet. When the JSP page is done with the compilation into a servlet, these directives set the page-level instructions, include external files, and create customized libraries. The syntax used to define a directive is as below:

<%@ directive attribute=”value” %>

In the above syntax, we can see the directive starts with ‘%@’ and ends with a percentage sign (‘%’). In between, we pass the value and the attribute we need in our directive. 

Three types of Directives are as follows:

  • Page directive: The page directive defines the attributes that can be applied to a complete JSP page. The syntax of the page directive is as:
<%@ page attribute=”value”%>

The attributes that you can pass inside this definition are- import, isErrorPage, session, pageEncoding, contentType, extends, info, buffer, language, autoFlush, isThreadSafe, errorPage, etc. 

  • Include directive: The include directive is useful when we want to include the contents in our JSP file. The content may be any resource such as an HTML file or text file. The include directive is useful as it includes the original content at the page translation time. The syntax used for defining include directive is as:
<%@ include file=”NameOfResource” %>

In the above syntax, we can give the name of the resource that we want to define in our directive for eg:

<%@ include file=”index.html” %> where index.html is the name of our resource. 
  • Taglib directive: The taglib directive is very useful when we want to define a tag library that contains several tags in it. Tag Library Descriptor (TLD) is a file used to define the tags. The syntax for defining the taglib directive is as:
<%@ taglib url=”theURLofTheTagLibrary” prefix = “prefixOfLibrary”%>

In the above syntax, we need to provide two arguments such as the URL of the tag library that we want to define in our directive and the prefix of the tag. For eg. 

<%@ taglib url= “https://www.mygreatlearning.com/tags” prefix = “taglib” %>

21. What are the observer and observable classes?

Observer: The object is notified when the state of another object is changed. 

Observable: The state of an object may be of interest or the object where another object registers an interest. 

The objects that inherit the observable class are responsible for the list of ‘observers’ and it calls the update() method of each observer whenever the observable objects get upgraded. After calling the update() method, it sends a message to all the observers that there is a change in the object’s state. Now, the observer interface is implemented by the objects of the observed observable. 

22. What is Session Management in Java?

The session management in java is carried out in various ways such as HTTP Sessions API, cookies, URL rewriting, etc. A session is a convertible state between the server and the client, and it can handle multiple requests and responses between client and server. As the Web Server and HTTP are both stateless, the only way to manage the sessions between them is by the unique information about the sessions, such as session_id, which is passed between the server and the client in every request and response. This is the popular way to manage sessions in java, i.e. by establishing a Session ID between the client and the server. 

23. Explain JPA in Java.

JPA stands for Java Persistence API is a specification of Java and is used to persist the data between a relational database and the objects of JavJPA is like a connection bridge between relational database systems and object-oriented domain models. As we just discussed, it is only a specification of java, and therefore it is not responsible for performing any operation by itself. To perform an operation, it should be implemented. And to do that, there are some ORM tools such as TopLink, Hibernate, and iBatis that implement JPA for data persistence. The API creates the persistence layer for the web applications and the desktop. Java Persistence API deals with the following services:

  • Query Language
  • Object Mapping Metadata
  • Java Persistence API
  • Java Persistence Criteria API

24. Explain the different authentications in Java Servlets.

Authentication is generally a process used to identify someone’s identity. Authentication is very useful to assure if the person who claims to be someone is true or not. Both servers and the client user authentication. There are four different authentications in java servlets:

  • Basic Authentication: In this type of authentication, the server uses a username and password to authenticate someone’s identity.
  • Form-based Authentication: In Form-based authentication, the login page collects the user’s credentials, such as username and password. 
  • SSL and client certificate authentication: This type of authentication requires an SSL certificate from each client who requests to access some information from the server. 
  • Digest Authentication: Digest authentication is similar to basic authentication, where the passwords are encrypted by a hash formula to make it more secure. And the data is transmitted by using MD5 or SH

25. What is JCA in Java?

JCA is an abbreviation used for Java Cryptography Architecture that contains a set of APIs. These APIs are used to implement some modern concepts related to cryptography like message digests, digital signatures, and certificates. JCA provides the platform enabling the encryption and decryption of some secure transactions. Developers use JCA to enhance the security level of applications. It also enables the implementation of third-party security rules and regulations in our applications. 

26. How is an infinite loop declared in Java?

The never-ending loop is Infinite Loop. If you are using loops like for, while or do-while and the code is incorrect then your code will turn to an infinite loop.

Common codes that result in an infinite loop are:

  • Use of for(;;){your code}in the code
  • Use of while(true){your code}in the code
  • Use of do-while(true){your code}in the code

Infinite while loop in Java- The value of i always remains 1 since we never incremented its value inside the while loop. As a result, i bearing value 1 will always result in true (since 1<10) inside while test.

public class printNumber {

public static void main (String [] args) {
int i =1;
while(i&lt;10) {
System.out.println("value of i="+ i);
}
 }
}

Output: The value of i is printed infinite times (infinite loop)

Infinite do while loop in Java- The value of I always remains 1 passing the do while condition 1<10

public class printNumber {
      public static void main (String[] args) {
            int i =1;
           do {
                  System.out.println("value of i="+ i);
            } while(i<10);
      }
}

Output: The value of i is printed infinite times (infinite loop)

27. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

Yes, a single try block and multiple catch block co-exist in a Java program.

• Every try should and must be associated with at least one catch block.

• The priority for the catch block would be given based on the order in which the catch block is defined when an exception object is identified in a try block.

 • Highest priority is always given to the first catch block.

 • Immediately, the next catch block is considered if the first catch block cannot be the identified exception object.

28. Explain the use of the final keyword in variable, method, and class.

Final Variable:

Value of final keyword in java which is used with variable, field or parameter once a reference is passed on or instantiation is done it cannot be changed throughout the execution of the program. A variable without any value declared as final is known as a blank or uninitialized final variable. This variable can be only initialized through the constructor.

Final Method

The program cannot be executed, if a method is declared as final in Java and cannot be overridden by the child class.

Final Class

A class cannot be inherited by any subclass and can no longer be described as abstract once it is declared as final. A class can be either of the two, final or abstract.

Thus, the use of the final keyword in variable, method, and class is mentioned above.

29. Do final, finally, and finalize keywords have the same function?

1. In Java, final is a keyword that can also be used as an access modifier. 

2. The final keyword is used to restrict a user’s access. 

3. It can be used in various contexts like:

          1. Final Variable

          2. Final Method

          3. Final Class

4. Final keyword has a different effect.

5. Final keyword is used as an access modifier in Java and also with variables, methods, and classes.

6. The final variable in Java is a constant whose value can’t be changed once assigned.

7. Final can’t be inherited by any child class.

8. Finally block in Java helps in cleaning up the resources that have been used in the try block. Executes right after the execution of the try-catch block. 

10. Finalize is a method in Java used for Garbage Collection. It is used with objects which are no longer in use and helps in cleaning up activities and executes them just before an object is destroyed.

Thus the function of final, finally and finalize is not the same in Java.

30. When can you use the super keyword?

The use of the super keyword in Java is:-

The super variables are used with variables, methods, and constructors and it is a reference variable that is used to refer to parent class objects and super variables are used with variables, methods, and constructors.

1.  The derived class and base class have the same data members if a super keyword is used with variables.

2.   A super keyword is used when we want to call the parent class method if a parent and child class have the same-named methods.

3.  The super keyword can also be used to access the parent class constructor.

31. Can the static methods be overloaded?

Yes, static methods can be overloaded by the method of overloading. To overload the static method you need to provide another static method with the same name but a different method signature.  Static overloaded methods are resolved using Static Binding.

32. Can the static methods be overridden?

We cannot override static methods. The overriding concept is used to change the implementation depending on requirements. So, at the time of overriding the static method, we are losing the property of static. Hence, static methods cannot be overridden in java.

But, practically we can override a static method that process is called method hiding.

33. How would you differentiate between a String, StringBuffer, and a StringBuilder?

String, StringBuffer, and StringBuilder would be differentiated in the following ways:

String- 

1. Storage type is String Pool

2. Immutable

3. String is not used in a threaded environment.

4. String has slow performance.

5. Syntax- String var =“NLP”; 

    String var=new String(“NLP”);  

StringBuffer- 

1. Storage type is Heap.

2. Mutable

3. StringBuffer is used in a multi-threaded environment.

4. StringBuffer is slower than StringBuilder but faster than String.

5. Syntax-

    StringBuffer var = new StringBuffer("NLP");

StringBuilder-

1. Storage type is Heap.

2. Mutable 

3. StringBuilder is used in a single-threaded environment.

4. StringBuilder faster than StringBuffer.

5. Syntax-

    StringBuilder var = new StringBuilder("NLP");

34. Using relevant properties highlight the differences between interfaces and abstract classes.

The difference between interface and abstract classes is given below:-

Interfaces Class:

1. Only abstract methods are available in interfaces.

2. Static and final variables can only be declared in the case of interfaces.

3. Multiple inheritances are facilitated by interfaces

4. the class data members of interfaces are of the public- type.

Abstract Class:

1. Non-abstract methods can be present along with abstract methods in abstract classes.

2. Abstract classes can also have non-static and non-final variables.

3. Abstract classes do not promote multiple inheritances.

4. The class members for an abstract class can be protected or private also.

5. With the help of an abstract class, the implementation of an interface is easily possible.

public abstract class Athlete {
public abstract void walk ();
}

35. In Java, static as well as private method overriding is possible. Comment on the statement.

No, in the java private method is cannot be overridden. This method is called private because no class has access to the private method. They are not visible to the child class. 

In some cases, the static method also cannot be overridden because static methods are part of any object other than the class itself. You can also declare a static method with the same signature in the child class but is not considered runtime polymorphism. So, in java static as well as private method overriding is not possible.

36. What makes a HashSet different from a TreeSet?

HashSet and TreeSet differ in the following ways:

HashSet-

1. HashSet is faster than TreeSet.

 2. It is implemented using a hash table.

3. O(log n) operations are not supported in HashSet.

4. It does not keep data sorted.

TreeSet-

1. TreeSet is slower than HashSet.

2. TreeSet is implemented using a self-balancing binary search tree(Red-Black Tree).

3. O(log n ) operations are supported for search, insert, delete.

4. It keeps sorted data.

37. Why is the character array preferred over string for storing confidential information?

We should use a character array instead of a string to collect more sensitive information. They can clear immediately after use as they are less vulnerable than string. It only reduces the attack window for a successful hack and doesn’t eliminate the risk.

System.out.println (chars);

Logger.info(Arrays.toString(chars));

Hence, the character array is more secure than the String object though it can be exploited. For security, we should always encrypt a password rather than store it in plain text, and don’t forget to clear it from the heap as soon as the user is authenticated.

38. What are the differences between HashMap and Hashtable in Java?

HashMap and HashTable both are important classes of the Java Collection framework.  They stores data in key-value pair. Hashing is used to hash the key.

HashMap in Java

  • The HashMap is an advanced version of the HashTable and was introduced as a type of new class in JDK 1.2.
  • The only difference HashMap allows multiple null values and one null key.
  • The HashMap stays non-synchronized because it is not very thread-safe. 
  • It allows multiple null values with one null key.
  • You can traverse a HashMap by Iterator for the process of iteration for traversing all the stored values.
  • A user can synchronize the HashMap by calling a specified code.
  • It inherits a class named AbstractMap
  • Because of the absence of any synchronization in it it works very fast than HashTable.
  • It is a new type of class that was introduced in JDK 1.2.
  • 1The Iterator present in HashMap fails fast.

Hashtable in Java

  • The HashTable is the legacy class and was introduced before the HashMap.
  • The implementation of a HashTable allows no null value or null key.
  • The HashTable stays synchronized because it is thread-safe. 
  • It is a type of legacy class.
  • It doesn’t allow any null value or key.
  • You can easily traverse the values stored in a HashTable by Iterator along with an Enumerator.
  • An unsynchronized HashTable does not exist because it stays synchronized internally.
  • It inherits a class named Dictionary.
  • The HashTable works very slowly as compared to the HashMap. It is because of the presence of synchronization. But in this case, one doesn’t have to write an extra code for obtaining synchronization.
  • The Enumerator present in a HashTable does not fail fast

In the following ways, HashMap and HashTable are different in Java.

39. What is the importance of reflection in Java?

Java Reflection is the process of examining run time behaviour.

The Reflection API is mainly used in:

• IDE (Integrated Development Environment) 

• Debugger

• Test Tools etc.

Advantages:

1. Help to write programs that do not know everything at compile time.

2. More dynamic.

3. Quite powerful and useful.

4. Possible to inspect classes, interface, fields, and methods at runtime.

1. Reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modifying it during runtime.

2. Suppose we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. 

3. The static typing system of Java doesn’t allow this method invocation unless the type of the object is known beforehand. 

4. Using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.

Method method foo = object.getClass().getMethod(“fooBar”, null);

methodOfFoo.invoke(object, null);

Due to its advantage, reflection is important in Java.

Disadvantages:

a. Due to reflection, Method invocations are about three times slower than the direct method calls.

b. Due to wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.

c. Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. 

 Hence, it is advisable to follow solutions that don’t involve reflection and use this method as a last resort.

40. What are the different ways of threads usage?

The different ways of threads usage are:

  1. Extending the Thread class
class InterviewThreadExample extends Thread{  

   public void run(){  

       System.out.println(“Thread runs…”);  

   }  

   public static void main(String args[]){  

       InterviewThreadExample ib = new InterviewThreadExample();  

       ib.start();  

   }  

}
  1. Implementing the Runnable interface

This method is more advantageous as Java does not support multiple inheritances. JVM calls the run() method to execute the thread.

class InterviewThreadExample implements Runnable{  

   public void run(){  

       System.out.println(“Thread runs…”);  

   }  

   public static void main(String args[]){  

       Thread ib = new Thread(new InterviewThreadExample()); 

       ib.start();  

   }  

}

Runnable for multiple inheritances of classes is used for implementing thread. start() method is used for creating a separate call stack as Java does not have support for the thread execution. JVM calls the run() method for executing the thread in that call stack as soon as the call stack is created.

41. What are the differences between the constructor and method of a class in Java?

The difference between the constructor and method of a class in Java is given below: –

Java is Object Oriented Programming Language. All the variables, data, and statements must be present in classes in Java and consist of constructors and methods. 

Constructor
  • Create and initialize objects that don’t exist yet.
  • Constructors can’t be called directly; they are called implicitly when the new keyword creates an object.
  • A Constructor can be used to initialize an object.
  • A Constructor is invoked implicitly by the system.
  • A Constructor is invoked when an object is created using the keyword new.
  • A Constructor doesn’t have a return type.
  • A Constructor’s name must be the same as the name of the class.
Method
  • Methods perform operations on objects that already exist.
  • Methods can be called directly on an object that has already been created with new.
  • A Method consists of Java code to be executed.
  • A Method is invoked by the programmer.
  • A Method is invoked through method calls.
  • A Method must have a return type.
  • A Method’s name can be anything.
  • Java works as a “pass by value” or “pass by reference” phenomenon?

Java works as a pass-by-value phenomenon.

Pass by value: It makes a copy in memory of the parameter’s value, or a copy of the contents of the parameter. 

Public static void main (String[] args) {

…

Int y = 8;

System.out.println (y);

myMethod (y);

System.out.println (y);

}

Public static void main myMethod (int x) {

…

x = 7 ;

}

• Pass by reference: It is a copy of the address (or reference) to the parameter stored rather than the value itself. Thus, modifying the value of the parameter will change the value. 

int main (){

…

int y=8;

cout << y;

myMethod(y);

cout ,, y;

}

Int myMethod (int &x){

…

x = 7;

}

42. How do not allow serialization of attributes of a class in Java?

public class NLP { 

   private transient String someInfo; 

   private String name;

   private int id;

   // :

   // Getters setters

   // :

}

To disallow the serialization of attributes of a class in java, use the “transient” keyword.

In the above example, except “someInfo” all other fields will be serialized.

Thus, serialization of attributes of a class is not allowed in Java.

43. What happens if the static modifier is not included in the main method signature in Java?

1. If the ‘static’ modifier is not included in the main 

    method but the compilation of the program will not give 

    any issues but when you’ll try to execute it will show

   “NoSuchMethodError” error.  

2. We cannot find any compilation error.

3. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

4. This scenario happens because when you execute a JAVA program, the JVM needs to know the sequence of execution, needs to have a driver code, and what to execute.

5.  On the compilation, any method that is non-static hasn’t been allocated memory by default.

6. If no memory has been allocated to the method according to JVM then it doesn’t exist without compilation.

 7. If JVM does not find the ‘main’ function to execute, it will give error.

44. What happens if there are multiple main methods inside one class in Java?

1. The program can’t compile as the compiler defines that the method has already inside the class.

2. Yes, you can have as many main methods as you like. 

3. You can have main methods with different signatures from main(String[]) which is called overloading, and the JVM will ignore those main methods.

4. You can have one public static void main(String[] args) method in each class. 

5. Some people use those methods for testing. They can individually test the operation of each class. 

6. The JVM will only invoke the public static void main(String[] args) method in the class you name when you write java MyClass.

public class TwoMain { 

    public static void main(String args1[]) 

    { 

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

    } 

    public static void main(String args2[]) 

    { 

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

    } 

}

8. Those two methods have the same signature. The only way to have two main methods is by having two different classes each with one main method.

9. The name of the class you use to invoke the JVM (e.g. java Class1, java Class2) determines which main method is called.

10. Yes, we can define multiple methods in a class with the same name but with different types of parameters. Which method is to get invoked will depend upon the parameters passed.

45. What do you understand about Object Cloning and how do you achieve it in Java?

Object Cloning :-

1. Object Cloning is a method to create an exact copy of any object. 

2. To support object cloning a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class.

 The syntax of object cloning is: –

protected Object clone () throws CloneNotSupportedException{

 return (Object)super.clone();

}

3. It results in CloneNotSupportedException in Java if the cloneable interface is not implemented. 

Advantages of Object Cloning: 
  • The ‘=’ (assignment) operator cannot be used for cloning as it only creates a copy of reference variables in Java. 
  • To overcome this, the clone () method of Object class can be used over the assignment operator.
  • The clone () method is a protected method of class Object because only the Employee class can clone Employee objects. 
  • It means no class other than Employee can clone Employee objects since it does not know Employee class’ attributes.
Application of Cloning in Java: 
  • It allows field-by-field copying of objects which comes in handy when dealing with objects of similar characteristics.
  • The default clone () method can be patched up by calling clone on mutable sub-objects.

46. How does an exception propagate in the code?

  • When an exception occurs it first searches to locate the matching catch block. 
  • If the matching catch block is located, then that block would be executed. 
  • If the matching block is not located then, the exception propagates through the method call stack and goes into the caller method. 
  • This propagation happens until the matching catch block is found. If it is not found, then the program gets terminated in the main method.
  • An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method.
  • After a method throws an exception, the runtime system attempts to find something to handle it. 
  • The set of possible “somethings” to handle the exception is the ordered list of methods where the error occurred. 
  • The list of methods is known as the call stack and the method of searching is Exception Propagation.
  • Input-
class TestExceptionPropagation1{  

  void m(){  

    int data=50/0;  

  }  

  void n(){  

    m();  

  }  

  void p(){  

   try{  

    n();  

   }catch(Exception e){System.out.println(“exception handled”);}  

  }  

  public static void main(String args[]){  

   TestExceptionPropagation1 obj=new TestExceptionPropagation1();  

   obj.p();  

   System.out.println(“normal flow…”);  

  }  

}  

Output-

exception handled

       normal flow…

Thus, exception pro[pogate in the code.

47. Is it mandatory for a catch block to be followed after a try block?

1. No, it is not mandatory for a catch block to be followed after a try block. 

2. A catch block should follow the try block.  

3. They should be declared using the throws clause of the method if the exception’s likelihood is more.

4. We can use either the “catch” block or the “finally” block after try block.

5.  a. Try block followed by a catch block

     b. Try block followed by a finally block

     c.  Try block followed by both catch and finally block

1) Try block is followed by a catch block:

public class TryCatchBlock {

    public static void main(String[] args) {

        try {

            int i1 = 11;

            int i2 = 0;

            int result = i1 / i2;

            System.out.println(“The divison of i1,i2 is” + result);

        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }

}

Output:

java.lang.ArithmeticException: / by zero

2) Try block is followed by a finally block:

public class TryFinallyBlock {

    public static void main(String[] args) {

        try {

            int i1 = 11;

            int i2 = 0;

            int result = i1 / i2;

            System.out.println(“The divison of i1,i2 is” + result);

        } finally {

            System.out.print(“Code which must be executed :” + ” “);

            System.out.println(“Whether Exception throw or not throw”);

        }

    }

}

Output:

Exception in thread “main” java.lang.ArithmeticException: / by zero

at TryFinallyBlock.main(TryFinallyBlock.java:11)

3) Try block is followed by both catch and finally block:

public class TryCatchFinallyBlock {

    public static void main(String[] args) {

        int i1 = 11;

        int i2 = 0;

        try {

            int result = i1 / i2;

            System.out.println(“The divison of i1,i2 is” + result);

        } catch (Exception ex) {

            int result = i1 + i2;

            System.out.println(“The addition of i1,i2 is” + ” ” + result);

        } finally {

            System.out.print(“Code which must be executed :” + ” “);

            System.out.println(“Whether Exception throw or not throw”);

        }

    }

}

Output:

The addition of i1,i2 is 11

48. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

1. finally block will be executed even in the exception or not. 

2. The ‘System. exit()’ method anywhere in the try/catch block fails to execute finally block.

3. finally block is not executed in the case of the ‘System. exit()’ method.

4.

public int someMethod(int i){

   try{

       return 1;

   }catch(Exception e){

       return 999;

   }finally{

   }

}

5. Java finally block is a block used to execute important code such as closing the connection, etc.

6. Java finally block is always executed whether an exception is handled or not. 

7. It contains all the necessary statements that need to be printed in any of the exceptions that occur or not.

8. The finally block follows the try-catch block.

finally, a block in Java can be used to put “cleanup” code such as closing a file, closing a connection, etc.

9.Important statements to be printed can be placed in the finally block.

49. Can you call a constructor of a class inside another constructor?

Using this() we can definitely call a constructor of a class inside another constructor.

public class Test

{    

    private int result, other;

    public Test() : this(1)        

    {        

             other = 2;    

    }    

    public Test(int num)    

    {               

        result = num;    

    }

}

50. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

1. In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible.

 2. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. 

3. Storing of actual objects or non-primitive data types takes place in various memory locations.

4. Primitive type values can be stored in arrays in contiguous memory locations.

5. In the case of ArrayList, data storing in the form of primitive data types like int, the float is not possible. 

6. The data members/objects present in the ArrayList have references to the objects.

7. Storing of actual objects or non-primitive data types takes place in various memory locations.

8. Primitive type values can be stored in arrays in contiguous memory locations.

Thus, Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList.

1. Inheritance is less advantageous than composition.

2. Multiple inheritances are not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required- to read and write information into the file, the pattern of composition is preferred. The writer and reader functionalities can be made use of by considering them as private members.

3. Composition provides high flexibility and prevents the breaking of encapsulation.

4. Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.

5. The loosely coupled nature of the composition is preferable over the tightly coupled nature of inheritance.

6. 

public class Top {

public int start() {

  return 0;

}

}

class Bottom extends Top {

 public int stop() {

  return 0;

 }

}

7. Some modifications are done to the Top class like this:

public class Top {

 public int start() {

  return 0;

 }

 public void stop() {

 }

}

8. A compile-time error is bound to occur in the Bottom class. if new implementation is followed Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

class Bottom {

 Top par = new Top();

 public int stop() {

  par.start();

  par.stop();

  return 0;

 }
} 

Thus, inheritance is less advantageous than composition.

52. How is the creation of a String using new() different from that of a literal?

1. new() will create a new string in heap memory.

2. Using literal syntax to create a string may result in an existing string being returned or a new string being created and made available in the string pool.

 public bool checking() {
String first = "Great Learning";
String second = "Great Learning";
if (first == second)
 return true;
else
 return false;
}

4. The checking() function will return true as the same content is referenced by both the variables.

5. When a String formation takes place with the help of a new() operator, interning does not take place. 

6. The object gets created in the heap memory even if the same content object is present.

public bool checking() {
String first = new String("Great Learning");
String second = new String("Great Learning");
if (first == second)
 return true;
else
 return false;
}


7. The checking() function will return false as the same content is not referenced by both variables.

8. String strObject = new String(“Java”);

and

String strLiteral = “Java”;

9. There is a difference between these expressions. When you create a String object using the new() operator, it always creates a new object in heap memory. 

10. If you create an object using String literal syntax e.g. “Java”, it may return an existing object from String pool (a cache of String object in Perm gen space, which is now moved to heap space in recent Java release), if it already exists. 

11. Otherwise it will create a new string object and put it in a string pool for future re-use. 

53. Is exceeding the memory limit possible in a program despite having a garbage collector?

1. It is possible to exceed the memory limit in a program despite having a garbage collector.

2. Certain objects may be out of reach of the garbage collector.

3. As the task is complete to prevent it from unnecessarily consuming memory, dereference of the object is important.

4. If an object is unreachable in the program, then the execution of garbage collection takes place concerning that object.

5. With the help of a garbage collector memory is released for those new objects if memory is not sufficient to create them. 

6. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.

7. Exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. 

8. The developer should make sure to dereference the object after its work is accomplished.

9. Let’s take a look at the following example:

List<String> example = new LinkedList<String>();

while(true){

example.add(new String(“Memory Limit Exceeded”));

}

54. Why is synchronization necessary? Explain with the help of a relevant example.

1. In synchronization multiple threads are able to consume a shared resource efficiently and without affecting results.

2. If you’re trying to read and write data in a file at the same time, the output may be affected.

3. Here, it would be best to let only one thread consume the resource at a time to avoid discrepancies.

4. No Synchronization:

package anonymous;

public class Counting {

       private int increase_counter;

       public int increase() {

               increase_counter = increase_counter + 1;

               return increase_counter;

       }

}

If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value we get will be 11.

Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.

5. With synchronization:

package anonymous;

public class Counting {

       private int increase_counter;

       public synchronized int increase () {

               increase_counter = increase_counter + 1;

               return increase_counter;

       }

If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place.

55. In the given code below, what is the significance of … ?

      public void fooBarMethod(String... variables){
      // method code
      }

1. (…) is a feature called varargs (variable arguments), introduced as part of Java 5.

2. The function(…)  in the above example indicates that it can receive multiple arguments of the datatype String.

3. The fooBarMethod can be called in multiple ways and we can still have one method to process the data as shown below:

fooBarMethod(“foo”, “bar”);

fooBarMethod(“foo”, “bar”, “boo”);

fooBarMethod(new String[]{“foo”, “var”, “boo”});

public void myMethod(String… variables){

   for(String variable : variables){

       // business logic

   }

}

56. Can you explain the Java thread lifecycle?

1. New thread is always in the new state, the code has not been run yet and thus has not begun its execution.

2. When a thread is in the start() method it has two states runnable and running in an active state.

3. A thread, that is ready to run is moved to the runnable state. The thread may be running in the runnable thread. 

4. A program implementing multithreading acquires a fixed slice of time to each thread. Every thread runs for a short period and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of time.  In the runnable state, there is a queue where the threads lie.

5. When the thread gets the CPU, it moves from the runnable to the running state and moves from runnable to running and again back to runnable.

6. Whenever a thread is inactive for permanent then the thread is in the blocked state or is waiting.

7. Thus, thread A has to wait for thread B to use the printer, and thread A is in the blocked state. 

8. A thread in the blocked state is unable to perform any execution and thus never consumes any cycle of the Central Processing Unit (CPU). 

9. Thus, thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked state.

10. The main thread then waits for the child threads to complete their tasks if the join() method is used. 

11. When the child threads complete their job, a notification is sent to the main thread, which again moves the thread from waiting to the active state.

12. If there are a lot of threads in the waiting or blocked state, then the thread scheduler must determine which thread to choose and which one to reject, and the chosen thread is then allowed to run.

13. Timed Waiting: Sometimes, waiting for leads to starvation. If thread A has entered the critical section of a code and is not willing to leave that critical section. In such a condition, another thread B has to wait forever, which leads to starvation. To avoid such conditions, a timed waiting state is given to thread B. Thus, the thread lies in the waiting state for a specific period, and not forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. If the thread is in the timed wait state then the thread wakes up and starts its execution from when it has left earlier.

14. Terminated: When a thread has finished its job, then it exists or terminates normally. Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault. A terminated thread means the thread is no more in the system. If the thread is dead, there is no way one can activate the dead thread.

57. What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

The tradeoff is:

Search complexity and Insertion complexity:

Search-complexity

1. The search time complexity is O(N) for an unordered array.

 2.  The search time complexity is O(log N) for an ordered array.

3. N is the number of elements in an array.

Insertion-complexity

1. The insertion complexity is O(N) to maintain the order of elements. 

2.  The insertion complexity is O(1) for an ordered array.

The structure of an unordered array is a collection of items where each item holds a relative position concerning the others. 

Possible unordered array operations are:  int list[100] creates a new list that is a size of 100 and stores elements of integer data.

Advantage of an ordered array-  The search times have a time complexity of O(log n)  compared to an unordered array, which is O (n). 

The disadvantage of an ordered array- The insertion operation has a time complexity of O(n).

58. Is it possible to import the same class or package twice in Java and what happens to it during runtime?

During runtime, JVM internally loads the package or class only once so it is possible to import the same class or package more than once in Java.

59. In case a package has sub-packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

No, in case a package has a sub package will not suffice to import only the main package. Importing the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.

60. Will the finally block be executed if the code System.exit(0) is written at the end of try block?

No, the final block will not be executed if the code System.exit(0) is written at end of try block and the program gets terminated which is why the finally block never gets executed.

61. Explain the term “Double Brace Initialisation” in Java?

The way of initializing any collections in Java:-

Thus we know that the stringSets were initialized by using double braces.

• The first brace does the task of creating an anonymous inner class. We can use the add() method of HashSet to create a subclass of HashSet.

• The second braces do the task of initializing the instances. Double Brace Initialisation involves the creation of anonymous inner classes which may lead to problems during the garbage collection or serialization processes and may also result in memory leaks.

62. Why is it said that the length() method of the String class doesn’t return accurate results?

1. The length method returns the number of Unicode units of the String. 

2. Java uses UTF-16 for String representation and we need to understand the below terms:

Code Point represents an integer denoting a character in the code space.

3. The code points were divided logically into 17 planes under UTF-16.

4. The first plane was called the Basic Multilingual Plane which is BMP. 

5. Code points from the first plane are encoded using one 16-bit code unit.

6. The code points from the remaining planes are encoded using two code units.

7. If a string contains supplementary characters then the length of the function would count as 2 units 

This will result in the length() function as expected.

8. If there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO –  As per the java documentation, it is expected, but as per the real logic, it is inaccurate.

1. array.length- Length is a final variable for arrays.

2. string.length() – Applicable for string objects.

3. length vs length() – The length () method is applicable for string objects but not arrays.

63. Write a Java program to check if the two strings are anagrams.

import java.util.Arrays;

public class AnagramSample  {

   public static void main(String args[]) {

      String str1 = “recitals”;

      String str2 = “articles”;

      if (str1.length()==str2.length()) {

         char[] arr1 = str1.toCharArray();

         Arrays.sort(arr1);

         System.out.println(Arrays.toString(arr1));

         char[] arr2 = str2.toCharArray();

         Arrays.sort(arr2);

         System.out.println(Arrays.toString(arr2));

         System.out.println(Arrays.equals(arr1, arr2));

         if(arr1.equals(arr2)) {

            System.out.println(“Given strings are anagrams”);

         } else {

            System.out.println(“Given strings are not anagrams”);

         }

      }

   }

}

64. Write a Java Program to find the factorial of a given number.

Java program to find the factorial of a given number is:-

public class Factorial {

public static void main(String[] args) {

int num = 10;

long factorialResult = 11;

for(int i = 1; I <= num; ++i)

{

    factorialResult * =  i;

}

System.out.printf (“Factorial :  ” +factorialResult);

}

}

Output – Enter the n value:

}

5

Enter (n-1) numbers:

1

2

4

5

The missing number is: 3

65. Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing the sum of digits in each step and in turn doing the sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

 Java Program to check if any number is a magic number or not:

public class Main{
public static void main(String[] args) {
int number = 1000; // Number to check
int sum = 0;
while (number &gt; 0 || sum &gt; 9)
{
if (number == 0)
{
number = sum;
sum = 0;
}
sum += number % 10;
number /= 10
} // If sum = 1, it is magic number
if(sum == 1) {
System.out.println("It is a magic number");
}else {
System.out.println("It is not a magic number");
}
}

 Output: It is a magic number.

Java Interview Questions for Experienced Professionals

This section will cover the advanced-level questions that you must have complete knowledge of before going into a Java interview. You must start with Java interview questions for freshers and then slowly make your way to the end of Java interview questions for experienced.

1. What is serialization in Java?

Object Serialization is a process used to convert the state of an object into a byte stream, which can be persisted into a disk/file or sent over the network to any other running Java virtual machine. The reverse process of creating an object from the byte stream is called deserialization.

2. What is synchronization in Java?

Synchronization is a process of handling resource accessibility by multiple thread requests. The main purpose of synchronization is to avoid thread interference. At times when more than one thread tries to access a shared resource, we need to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. The synchronization keyword in java creates a block of code referred to as a critical section.

synchronization in Java

3. What is the spring framework in Java?

The Spring Framework is an application framework and inversion of the control container for the Java platform. Any Java application can use the framework’s core features, but there are extensions for building web applications on top of the Java EE (Enterprise Edition) platform.

spring framework in java

4. How to create an immutable class in Java?

  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables.
  • Make all mutable fields final so that their value can be assigned only once.
  • Initialize all the fields via a constructor performing the deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

5. What is servlet in Java?

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed by a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

servlet in Java - Java interview questions

6. What is xname class in Java?

An Expanded Name, comprising of a (discretionary) namespace name and a nearby name. XName examples are changeless and might be shared.

7. Can static methods reference non-static variables?

Yes, static methods can reference non-static variables. It can be done by creating an object of the class the variable belongs to.

8. How do static blocks get executed if there are multiple static blocks?

Multiple static blocks are executed in the sequence in which they are written in a top-down manner. The top block gets executed first, then the subsequent blocks are executed.

9. Can we override static methods?

Static methods cannot be overridden because they are not dispatched to the object instance at run time. In their case, the compiler decides which method gets called.

10. What is classloader?

ClassLoader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

  • Bootstrap ClassLoader: This is the first classloader which is the superclass of the Extension classloader. It loads the rt.jar file, which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.
  • Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
  • System/Application ClassLoader: This is the child classloader of the Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using “-cp” or “-classpath” switch. It is thus also known as the Application classloader.

11. Difference between Serializable and Externalizable in Java?

A serializable interface is used to make Java classes serializable so that they can be transferred over a network or their state can be saved on disk. Still, it leverages default serialization built-in JVM, which is expensive, fragile, and not secure. Externalizable allows you to fully control the Serialization process, specify a custom binary format and add more security measures.

12. Can we use String in the switch case?

We can use String in the switch case, but it is just syntactic sugar. Internally string hash code is used for the switch. See the detailed answer for more explanation and discussion.

13. What are object serialization and deserialization?

The use of java.io.Serializable to convert an object into a sequence of bytes is known as object serialization. Deserialization is the process of recovering back the state of the object from the byte stream.

14. What is the difference between checked and unchecked exceptions in Java?

The compiler checks a checked exception at compile time. It’s mandatory for a method to either handle the checked exception or declare them in their throws clause. These are the ones that are a subclass of Exception but don’t descend from RuntimeException. The unchecked exception is the descendant of RuntimeException and is not checked by the compiler at compile time. This question is now becoming less popular and you would only find this with interviews with small companies, both investment banks and startups are moved on from this question.

15. Is ++ operator thread-safe in Java?

No, it’s not a thread-safe operator because it involves multiple instructions like reading a value, incriminating it, and storing it back into memory which can be overlapped between multiple threads.

16. Which class contains the clone method? Cloneable or Object?

java.lang.Cloneable is a marker interface and doesn’t contain any method clone method is defined in the object class. It also knows that clone() is a native method means it’s implemented in C or C++ or any other native language.

Java Coding Interview Questions

Practising coding is an important aspect when it comes to programming or developer jobs. This section will help you understand the java interview questions for coding.

1. What is an interface in Java?

An interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations.

As you can see that although we had the common action for all subclasses sound() but there were different ways to do the same action. This is a perfect example of polymorphism (a feature that allows us to perform a single action in different ways). It would not make any sense to just call the generic sound() method as each Animal has a different sound. Thus we can say that the action this method performs is based on the type of object.

2. How to convert string to int in Java?

"class Scratch{
    public static void main(String[] args){
        String str = ""50"";
        System.out.println( Integer.parseInt( str ));   // Integer.parseInt()
    }
}"

3. Why string is immutable in Java?

The string is Immutable in Java because String objects are cached in the String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client’s action would affect another client. For example, if one client changes the value of String “ABC” to “abc”, all other clients will also see that value as explained in the first example. Since caching of String objects was important for performance reasons, this risk was avoided by making the String class Immutable. At the same time, String was made final so that no one can compromise invariant of String class, e.g., Immutability, Caching, hashcode calculation, etc., by extending and overriding behaviors.

4. How to compile a Java program?

Open a command prompt window and go to the directory where you saved the java program (MyFirstJavaProgram. java). …
Type ‘javac MyFirstJavaProgram. java’ and press enter to compile your code

5. How to convert char to int in Java?

public class JavaExample{  
   public static void main(String args[]){  
        char ch = '10';
        int num = Integer.parseInt(String.valueOf(ch));
                
        System.out.println(num);
   }
}

6. How to split strings in Java?

String string = ""004-034556"";
String[] parts = string.split(""-"");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

7. How to read a file in Java?

import java.io.*; 
public class Read 
{ 
  public static void main(String[] args)throws Exception 
  { 
  File file = new File(""C:\Users\LBL\Desktop\test.txt""); 
  
  BufferedReader br = new BufferedReader(new FileReader(file)); 
  
  String st; 
  while ((st = br.readLine()) != null) 
    System.out.println(st); 
  } 
} 

8. How to use the scanner in Java?

import java.util.Scanner;

class classname{
  public methodname(){
    //Scanner declaration
    Scanner s_name = new Scanner(System.in);
    //Use Scanner to take input
    int val = s_name.nextInt();
  }
}

9. How to reverse a number in Java?

class Reverse
{
   public static void main(String args[])
   {
      int num=564;
      int reverse =0;
      while( num != 0 )
      {
          reverse = reverse * 10;
          reverse = reverse + num%10;
          num = num/10;
      }

      System.out.println(""Reverse  is: ""+reverse);
   }
}

10. What is a maven in Java?

Maven is a powerful project management tool that is based on POM (project object model). It is used for project build, dependency, and documentation.

It simplifies the build process like ANT. But it is too much advanced than ANT.

11. What is an applet in Java?

An applet is a special kind of Java program that runs in a Java-enabled browser. This is the first Java program that can run over the network using the browser. An applet is typically embedded inside a web page and runs in the browser.

In other words, we can say that Applets are small Java applications that can be accessed on an Internet server, transported over the Internet, and can be automatically installed and run as a part of a web document.

12. How to generate random numbers in Java?

public static double getRandomNumber(){
    double x = Math.random();
    return x;
}

13. What are generics in Java?

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

14. What is overriding in Java?

Method overriding is a process of overriding a base class method by a derived class method with a more specific definition.

Method overriding performs only if two classes have an is-a relationship. It means class must have an inheritance. In other words, It is performed between two classes using inheritance relation.

In overriding, the method of both classes must have the same name and an equal number of parameters.

Method overriding is also referred to as runtime polymorphism because JVM decides the calling method during runtime.

The key benefit of overriding is the ability to define a method that’s specific to a particular subclass type.

Example of method overriding

class Human{
   //Overridden method
   public void eat()
   {
      System.out.println(""Human is eating"");
   }
}
class Boy extends Human{
   //Overriding method
   public void eat(){
      System.out.println(""Boy is eating"");
   }
   public static void main( String args[]) {
      Boy obj = new Boy();
      //This will call the child class version of eat()
      obj.eat();
   }
}

15. How to iterate hashmap in java?

public class InsertSort {
  public static void main (String [] args) {
   int [] array = {10,20,30,60,70,80,2,3,1};
   int temp;
   for (int i = 1; i < array.length; i++) {
    for (int j = i; j > 0; j--) {
     if (array[j] < array [j - 1]) {
      temp = array[j];
      array[j] = array[j - 1];
      array[j - 1] = temp;
     }
    }
   }
   for (int i = 0; i < array.length; i++) {
     System.out.println(array[i]);
   }
  }
}

16. How to convert string to date in java?

String string = ""January 2, 2010"";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(""MMMM d, yyyy"", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02

17. How to convert string to integer in java?

String string1 = ""100"";
String string2 = ""50"";
String string3 = ""20"";

int number1 = Integer.decode(string1);
int number2 = Integer.decode(string2); 
int number3 = Integer.decode(string3); 

System.out.println(""Parsing String """" + string1 + """": "" + number2);
System.out.println(""Parsing String """" + string2 + """": "" + number2);
System.out.println(""Parsing String """" + string3 + """": "" + number3);

18. How to sort arraylist in java?

import java.util.*;
public class ArrayListOfInteger  {

	public static void main(String args[]){
	   ArrayList<Integer> arraylist = new ArrayList<Integer>();
	   arraylist.add(11);
	   arraylist.add(2);
	   arraylist.add(7);
	   arraylist.add(3);
	   /* ArrayList before the sorting*/
	   System.out.println(""Before Sorting:"");
	   for(int counter: arraylist){
			System.out.println(counter);
		}

	   /* Sorting of arraylist using Collections.sort*/
	   Collections.sort(arraylist);

	   /* ArrayList after sorting*/
	   System.out.println(""After Sorting:"");
	   for(int counter: arraylist){
			System.out.println(counter);
		}
	}
}

19. What is hashmap in java?

HashMap is a Map-based collection class that is used for storing Key & value pairs, it is denoted as HashMap<Key, Value> or HashMap<K, V>. This class makes no guarantees as to the order of the map. It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).

20. What is stream in java?

A Stream in Java can be defined as a sequence of elements from a source. Streams supports aggregate operations on the elements. The source of elements here refers to a Collection or Array that provides data to the Stream.

Stream keeps the ordering of the elements the same as the ordering in the source. The aggregate operations are operations that allow us to express common manipulations on stream elements quickly and clearly.

21. What is lambda expression in java?

A lambda expression (lambda) describes a block of code (an anonymous function) that can be passed to constructors or methods for subsequent execution. The constructor or method receives the lambda as an argument. Consider the following example:

System.out.println(“Hello”)
This example identifies a lambda for outputting a message to the standard output stream. From left to right, () identifies the lambda’s formal parameter list (there are no parameters in the example), -> indicates that the expression is a lambda, and System.out.println(“Hello”) is the code to be executed.

22. What is microservices java?

Microservices are a form of service-oriented architecture style (one of the most important skills to become a Java developer) wherein applications are built as a collection of different smaller services rather than one whole app.

23. What is JSP in Java?

A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML, SVG, WML, and XML), and JSP elements, which construct dynamic content.

The recommended file extension for the source file of a JSP page is .jsp. The page can be composed of a top file that includes other files that contain either a complete JSP page or a fragment of a JSP page. The recommended extension for the source file of a fragment of a JSP page is .jspf.

The JSP elements in a JSP page can be expressed in two syntaxes, standard and XML, though any given file can use only one syntax. A JSP page in XML syntax is an XML document and can be manipulated by tools and APIs for XML documents.

24. What is the use of a constructor in Java?

A constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and method are different(More on this at the end of this guide). People often refer to constructors as a special type of method in Java.

A constructor has the same name as the class and looks like this in java code.

25. How many ways to create an object in java?

There are five different ways to create an object in Java:

  • Java new Operator
  • Java Class. newInstance() method
  • Java newInstance() method of constructor
  • Java Object. clone() method
  • Java Object Serialization and Deserialization

26. Why is Java becoming functional (java 8)?

Java 8 adds functional programming through what are called lambda expressions, which is a simple way of describing a function as some operation on an arbitrary set of supplied variables.

27. How to get the ASCII value of char in Java?

char character = 'a';    
int ascii = (int) character;

In your case, you need to get the specific Character from the String first and then cast it.

char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.

28. What is marker interface in java?

An empty interface in Java is known as a marker interface i.e.; it does not contain any methods or fields by implementing these interfaces, a class will exhibit a special behavior with respect to the interface implemented. If you look carefully at the marker interfaces in Java, e.g., Serializable, Cloneable, and Remote, it looks like they are used to indicate something to the compiler or JVM. So if JVM sees a Class is Serializable, it does some special operation on it, similar way if JVM sees one Class is implemented Clonnable, it performs some operation to support cloning. The same is true for RMI and Remote interface. In simplest Marker interface indicate a signal or a command to Compiler or JVM.

–> Practically we can create an interface like a marker interface with no method declaration in it but it is not a marker interface at all since it is not instructing something to JVM that provides some special behaviour to the class when our program is going to execute.

For example, Serializable, Cloneable, etc. are marker interfaces.

When my program gets executed, JVM provides some special powers to my class which has implemented the Marker Interfaces.

29. How to import a scanner in java?

import java.utils.Scanner
Scanner sc=new Scanner();

30. What is exception handling in java?

Exception Handling in Java is a way to keep the program running even if some fault has occurred. An exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object-oriented way to handle exception scenarios, known as Java Exception Handling.

public class Exception_Handling { 
    String gender; 
    Exception_Handling(String s){ 
        gender=s; 
    } 
     void Check_Gender(String s) throws GenderException{ 
        if (gender!="Male" || gender!="Female") 
            throw new GenderException("Gender Invalid"); 
        else 
        System.out.println("Gender valid"); 
        } 
    public static void main(String args[]){ 
        Exception_Handling n=new Exception_Handling("None"); 
        try{ 
            n.Check_Gender("Female"); 
        }catch (Exception e){ 
            System.out.println("Exception : "+e); 
        } 
    } 
    } 
class GenderException extends Exception{ 
    GenderException(String s){ 
        super(s); 
    } 
} 

31. How to scan strings in Java?

import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print(""Enter your name: "");
String name = in.nextLine();
System.out.println(""Name is: "" + name);
in.close();

32. When to use comparable and comparator in java with example?

If one wants a different sorting order, he can implement a comparator and define its own way of comparing two instances. If sorting of objects needs to be based on natural order then use Comparable whereas if your sorting needs to be done on attributes of different objects, then use Comparator in Java.

33. How to create a jar file in java?

The basic format of the command for creating a JAR file is:

jar cf jar-file input-file(s)
The options and arguments used in this command are:

  • The c option indicates that you want to create a JAR file
  • The f option indicates that you want the output to go to a file rather than to stdout

jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.
The input-file(s) argument is a space-separated list of one or more files that you want to include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the “input-files” are directories, the contents of those directories are added to the JAR archive recursively.
The c and f options can appear in either order, but there must not be any space between them.

34. What is the difference between next () and nextline () in java?

next() can read the input only till space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextLine() reads input, including space between the words (that is, it reads till the end of line n).

35. How to iterate a map in java?

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();

}

36. What is the diamond problem in java?

The “diamond problem” is an uncertainty that can emerge as a result of permitting various legacy. It is a significant issue for dialects (like C++) that consider numerous state legacies. In Java, nonetheless, numerous legacy doesn’t take into account classes, just for interfaces, and these don’t contain state.

37. How to swap two strings in java?

String a = ""one"";
String b = ""two"";

a = a + b;
b = a.substring(0, (a.length() - b.length()));
a = a.substring(b.length());

System.out.println(""a = "" + a);
System.out.println(""b = "" + b);

38. How to convert string to date in java in yyyy-mm-dd format?

String start_dt = ""2011-01-01"";
DateFormat formatter = new SimpleDateFormat(""yyyy-MM-DD""); 
Date date = (Date)formatter.parse(start_dt);
SimpleDateFormat newFormat = new SimpleDateFormat(""MM-dd-yyyy"");
String finalString = newFormat.format(date);

39. What is getname in java with example?

import java.io.*; 
  
public class solution { 
    public static void main(String args[]) 
    { 
  
        // try-catch block to handle exceptions 
        try { 
  
            // Create a file object 
            File f = new File(""new.txt""); 
  
            // Get the Name of the given file f 
            String Name = f.getName(); 
  
            // Display the file Name of the file object 
            System.out.println(""File Name : "" + Name); 
        } 
        catch (Exception e) { 
            System.err.println(e.getMessage()); 
        } 
    } 
} 

getName returns the name of the file.

40. What is bufferreader in Java?

The Java.io.BufferedReader class peruses text from a character-input stream, buffering characters to accommodate the proficient perusing of characters, clusters, and lines. Following are the significant focuses on BufferedReader − The cradle size might be determined, or the default size might be utilized.

41. What is aggregation in Java?

The case of Aggregation is Student in School class when School shut, Student despite everything exists and afterward can join another School or something like that. In UML documentation, a structure is signified by a filled precious stone, while conglomeration is indicated by an unfilled jewel, which shows their undeniable distinction regarding the quality of the relationship.

42. How to use switch case in Java?

int amount = 9;

switch(amount) {
    case     0 : System.out.println(""amount is  0""); break;
    case     5 : System.out.println(""amount is  5""); break;
    case    10 : System.out.println(""amount is 10""); break;
    default    : System.out.println(""amount is something else"");
}

43. What is recursion in Java?

Recursion is simply the strategy of settling on a capacity decision itself. This method gives an approach to separating entangled issues into straightforward issues which are simpler to settle.

44. What is autoboxing and unboxing in Java?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

45. How to create an array of objects in Java?

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

46. What is a static method in Java?

The static keyword is used to create methods that will exist independently of any instances created for the class. Static methods do not use any instance variables of any object of the class they are defined in.

47. When do we use the Array list?

Whenever there is a need for random access to elements in java we use ArrayList. Get and set methods provide really fast access to the elements using the array list.

48. What is the use of generics in Java?

Generics allow classes and interfaces to be a type for the definition of new classes in java which enables stronger type checking. It also nullifies the probability of type mismatch of data while insertion.

49. What is an iterator?

An iterator is a collection framework functionality that enables sequential access to elements. The access can be done in one direction only. Java supports two types of iterators:
1. Enumeration Iterator
2. List Iterator

50. What is a stack?

A stack is a data structure that supports the LAST IN FIRST OUT methodology. The element pushed last is at the top of the stack. A stack supports the following functionality:

  • Push-operation to push an element into the stack
  • Pop-operation to push an element out of the stack
  • Peek-An option to check the top element

51. What is a treemap?

Treemap is a navigable map interpretation in java that is built around the concepts of red and black trees. The keys of a treemap are sorted in ascending order by their keys.

52. What is a vector?

A vector is an ArrayList-like data structure in java whose size increases as per the demands. Moreover, it also supports some legacy functions not supported by collections.
You should also know that a vector is more suitable to work with threads, unlike collection objects.

53. What is the difference between ArrayList and vector?

An ArrayList is not suitable for working in a thread-based environment. A vector is built for thread-based executions. ArrayList does not support legacy functions, whereas a vector has support for legacy functions.

54. Write a program to calculate the factorial of a number in java.

import java.util.Scanner; 

public class star { 
     public static void main(String[] args) { 
         Scanner sc=new Scanner(System.in); 
         int fact=1; 
         int n=sc.nextInt(); 

         for (int i=1;i<=n;i++) 
         fact=fact*i; 

         System.out.println(fact); 


        } 

} 

55. Write a program to check if a number is prime.

import java.util.Scanner; 
public class star { 
     public static void main(String[] args) { 
         Scanner sc=new Scanner(System.in); 
         int n=sc.nextInt(); 
         int count=0; 
         for (int i=1;i<=n;i++) 
         { 
             if (n%i==0) 
             count++; 
         } 
         if (count==2) 
         System.out.println("Prime"); 
         else 
         System.out.println("Not Prime"); 
        } 
} 

56. Write a program to convert decimal numbers to binary.

import java.util.Scanner; 

class star 
{ 
public static void main(String arg[])    
{    
    Scanner sc=new Scanner(System.in); 
    System.out.println("Enter a decimal number"); 
    int n=sc.nextInt(); 
    int  bin[]=new int[100]; 
    int i = 0; 
    while(n > 0) 
    { 
    bin[i++] = n%2; 
       n = n/2; 
    } 
   System.out.print("Binary number is : "); 
    for(int j = i-1;j >= 0;j--) 
   { 
       System.out.print(bin[j]); 
   } 
} 
} 

57. Write a program to convert decimal numbers to octal.

import java.util.Scanner; 
class star 
{ 
  public static void main(String args[]) 
  { 
    Scanner sc = new Scanner( System.in ); 
    System.out.print("Enter a decimal number : "); 
    int num =sc.nextInt(); 
    String octal = Integer.toOctalString(num); 
    System.out.println("Decimal to octal: " + octal); 
  } 
} 

58. Which utility function can be used to extract characters at a specific location in a string?

The charAt() utility function can be used to achieve the above-written functionality.

59. Which of the following syntax for defining an array is correct?

- Int []=new int[];
- int a[]=new int[];
- int a[] =new int [32]
int a[]=new int[32] is the correct method.


60. What will this return 3*0.1 == 0.3? true or false?

This is one of the really tricky questions and can be answered only if your concepts are very clear. The short answer is false because some floating-point numbers can not be represented exactly.

61. Write a program to generate the following output in java?
*
**
****
*****
******

public class star { 
     public static void main(String[] args) { 
         int i; 
         int count=1; 
        for (i=1;i<=5;i++){ 
            for (int j=1;j<=i;j++) 
                System.out.print("*"); 
            System.out.println(" "); 

        } 

} 
} 

62. Write a program to generate the following output.
****
***
**
*

public class star { 
     public static void main(String[] args) { 
         int i; 
         int count=1; 
        for (i=5;i>=1;i--){ 
            for (int j=1;j<=i;j++) 
                System.out.print("*"); 
            System.out.println(" "); 

        } 

} 
} 

63. Write a program in java to remove all vowels from a string.

import java.util.Scanner; 

public class star { 
     public static void main(String[] args) { 
         Scanner sc=new Scanner(System.in); 
         String n=sc.nextLine(); 
         String n1=n.replaceAll("[AEIOUaeiou]", ""); 
         System.out.println(n1); 

         } 
        } 

64. Write a program in java to check for palindromes.

String str, rev = ""; 
      Scanner sc = new Scanner(System.in); 

      System.out.println("Enter a string:"); 
      str = sc.nextLine(); 

      int length = str.length(); 

      for ( int i = length - 1; i >= 0; i-- ) 
         rev = rev + str.charAt(i); 

      if (str.equals(rev)) 
         System.out.println(str+" is a palindrome"); 
      else 
         System.out.println(str+" is not a palindrome"); 

65. What is the underlying mechanism in java’s built-in sort?

Java’s built-in sort function utilizes the two pivot quicksort mechanism. Quicksort works best in most real-life scenarios and has no extra space requirements.

66. How to remove an element from an array?

To remove an element from an array we have to delete the element first and then the array elements lying to the right of the element are shifted left by one place.

67. Difference between a = a + b and a += b ?

The += operator implicitly cast the result of addition into the type of the variable used to hold the result. When you add two integral variables e.g. variable of type byte, short, or int then they are first promoted to int and them addition happens. If the result of the addition is more than the maximum value of a then a + b will give a compile-time error but a += b will be ok as shown below
byte a = 127;
byte b = 127;
b = a + b; // error : cannot convert from int to byte
b += a; // ok

Java OOPS Interview Questions

1. What is Class in Java?

In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance (in the glossary) of the class of objects known as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and behaviour (change gears, brake) in common. However, each bicycle’s state is independent and can be different from other bicycles.
When building bicycles, manufacturers take advantage of the fact that bicycles share characteristics, building many bicycles from the same blueprint. It would be very inefficient to produce a new blueprint for every individual bicycle manufactured.

In object-oriented software, it’s also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects. A software blueprint for objects is called a class (in the glossary).

2. What is a constructor in java?

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:



Example
Create a constructor:

// Create a MyClass class
public class MyClass {
  int x;  // Create a class attribute

  // Create a class constructor for the MyClass class
  public MyClass() {
    x = 5;  // Set the initial value for the class attribute x
  }

  public static void main(String[] args) {
    MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the constructor)
    System.out.println(myObj.x); // Print the value of x
  }
}

// Outputs 5
 

3. What is object in java?

An object is a software bundle of variables and related methods.
You can represent real-world objects using software objects. You might want to represent real-world dogs as software objects in an animation program or a real-world bicycle as a software object within an electronic exercise bike. However, you can also use software objects to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard.

4. How to create object in java?

  • Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
  • Instantiation: The new keyword is a Java operator that creates the object.
  • Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

5. Who executes the byte code in java?

Bytecode is the compiled format for Java programs. Once a Java program has been converted to bytecode, it can be transferred across a network and executed by Java Virtual Machine (JVM).

6. Why we can’t create the object of abstract class in java?

Because an abstract class is an incomplete class (incomplete in the sense it contains abstract methods without body and output) we cannot create an instance or object; the same way we say for an interface.

7. What is Constructor Overloading?

A class with multiple constructors with different function definitions or parameters is called constructor overloading.

import java.io.*; 
import java.lang.*; 
public class constructor_overloading { 
    double sum; 
    constructor_overloading(){ 
        sum=0; 
    } 
    constructor_overloading(int x,int y){ 
        sum=x+y; 
    } 
    constructor_overloading(double x,double y){ 
        sum=x+y; 
    } 
    void print_sum(){ 
        System.out.println(sum); 
    } 
    public static void main(String args[]){ 
        constructor_overloading c=new constructor_overloading(); 
        c.print_sum(); 
        constructor_overloading c1=new constructor_overloading(10,20); 
        c1.print_sum(); 
        constructor_overloading c2=new constructor_overloading(10.11,20.11); 
        c2.print_sum(); 
    } 
} 

8. How many types of constructors does Java support?

Java supports the following types of constructors:

  • Non-Parameterized or Default Constructors
  • Parameterized Constructors
  • Copy constructor

9. What is the role of finalize()?

Finalize() is used for garbage collection. It’s called by the Java run environment by default to clear out unused objects. This is done for memory management and clearing out the heap.

10. If a child class inherits the base class, then are the constructor of the base class also inherited by the child class?

Constructors are not properties of a class. Hence they cannot be inherited. If one can inherit constructors then it would also mean that a child class can be created with the constructor of a parent class which can later cause referencing error when the child class is instantiated. Hence in order to avoid such complications, constructors cannot be inherited. The child class can invoke the parent class constructor by using the super keyword.

11. What is constructor chaining?

Constructor chaining is the process of invoking constructors of the same class or different classes inside a constructor. In this way, multiple objects are not required for constructor invocation with constructors having different parameters.

Java Multithreading Interview Questions

1. What is multithreading in java?

Multithreading in Java is a feature that allows concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process.

2. What is thread-safe in java?

Thread-safety or thread-safe code in Java refers to code that can safely be used or shared in concurrent or multi-threading environments and will behave as expected. any code, class, or object which can behave differently from its contract in the concurrent environment is not thread-safe.

3. What is volatile in java?

A volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread-safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem.

4. How to generate random numbers in java within range?

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

5. If we clone objects using the assignment operator do the references differ?

When objects are cloned using the assignment operator, both objects share the same reference. Changes made to the data by one object would also be reflected in the other object.

6. Can we start a thread twice in java?

Once a thread is started, it can never be started again. Doing so will throw an IllegalThreadStateException

7. How can Java threads be created?

Threads can be created by implementing the runnable interface.
Threads can also be created by extending the thread class

This brings us to the end of the Java Interview Questions. Glad to see you are now better equipped to face an interview. 

Also, Read: Top 25 Common Interview Questions

Java Programming Interview Questions

1. How to find duplicate characters in a string in Java?

public class Example {
   public static void main(String argu[]) {
      String str = ""beautiful beach"";
      char[] carray = str.toCharArray();
      System.out.println(""The string is:"" + str);
      System.out.print(""Duplicate Characters in above string are: "");
      for (int i = 0; i < str.length(); i++) {
         for (int j = i + 1; j < str.length(); j++) {
            if (carray[i] == carray[j]) {
               System.out.print(carray[j] + "" "");
               break;
            }
         }
      }
   }

2. How to convert int to string in Java?

class Convert 
{ 
  public static void main(String args[]) 
  { 
    int a = 786; 
    int b = -986; 
    String str1 = Integer.toString(a); 
    String str2 = Integer.toString(b); 
    System.out.println(""String str1 = "" + str1);  
    System.out.println(""String str2 = "" + str2); 
  }

3. How to convert char to String in Java?

public class CharToStringExample2{
public static void main(String args[]){
char c='M';
String s=Character.toString(c);
System.out.println(""String is: ""+s);
}}

4. How to convert a char array to a string in Java?

class CharArrayToString
{
   public static void main(String args[])
   {
      // Method 1: Using String object
      char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
      String str = new String(ch);
      System.out.println(str);
 
      // Method 2: Using valueOf method
      String str2 = String.valueOf(ch);
      System.out.println(str2);
   }
}

5. How to split a string in java?

public class JavaExample{
   public static void main(String args[]){
	String s = "" ,ab;gh,bc;pq#kk$bb"";
	String[] str = s.split(""[,;#$]"");
		
	//Total how many substrings? The array length
	System.out.println(""Number of substrings: ""+str.length);
		
	for (int i=0; i < str.length; i++) {
		System.out.println(""Str[""+i+""]:""+str[i]);
	}
   }
}

6. How to reverse a string in java word by word?

import java.util.*;
class ReverseString
{
  public static void main(String args[])
  {
    String original, reverse = """";
    Scanner in = new Scanner(System.in);

    System.out.println(""Enter a string to reverse"");
    original = in.nextLine();

    int length = original.length();

    for (int i = length - 1 ; i >= 0 ; i--)
      reverse = reverse + original.charAt(i);

    System.out.println(""Reverse of the string: "" + reverse);
  }
}

7. How to read a string in java?

Scanner sc= new Scanner(System.in); //System.in is a standard input stream.
System.out.print(""Enter a string: "");
String str= sc.nextLine(); //reads string.

8. How to find the length of a string in java?

To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class.
 
In Java, strings are objects created using the string class and the length() method is a public member method of this class. So, any variable of type string can access this method using the . (dot) operator.
 
The length() method counts the total number of characters in a String.

9. How to convert double to string in java?

public class D2S{
public static void main(String args[]){
double d=1.2222222;
String s=Double. toString(d);
System. out. println(s);
}}

10. How to replace a character in a string in java?

String replace(char oldChar, char newChar): It replaces all the occurrences of a oldChar character with newChar character. For e.g. “pog pance”.replace(‘p’, ‘d’) would return dog dance.

11. How to sort a string in java?

import java.util.Arrays;

public class Test
{
    public static void main(String[] args)
    {
        String original = ""edcba"";
        char[] chars = original.toCharArray();
        Arrays.sort(chars);
        String sorted = new String(chars);
        System.out.println(sorted);
    }
}

  

12. How to input string in java?

import java.util.*;  
class Inp
{  
public static void main(String[] args)  
{  
Scanner sc= new Scanner(System.in); //System.in is a standard input stream  
System.out.print(""Enter a string: "");  
String str= sc.nextLine();              //reads string   
System.out.print(""You have entered: ""+str);             
}  
} 

13. How to remove special characters from a string in java?

class New  
{  
public static void main(String args[])   
{  
String str= ""This#string%contains^special*characters&."";   
str = str.replaceAll(""[^a-zA-Z0-9]"", "" "");  
System.out.println(str);  
}  
} 

14. How to get the length of a string in Java?

The length of the string in java can be found using the .length() utility.

15. How to read strings in Java?

import java.util.Scanner;  // Import the Scanner class

class MyClass {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println(""Enter username"");

    String userName = myObj.nextLine();  // Read user input
    System.out.println(""Username is: "" + userName);  // Output user input
  }
}

Programming Interview Questions on Array in Java

1. How to remove duplicate elements from an array in Java?

public class Change
{
   public static int removeDuplicate(int[] arrNumbers, int num)
   {  
      if(num == 0 || num == 1)
      {  
         return num;  
      }  
      int[] arrTemporary = new int[num];  
      int b = 0;  
      for(int a = 0; a < num - 1; a++)
      {  
         if(arrNumbers[a] != arrNumbers[a + 1])
         {  
            arrTemporary[b++] = arrNumbers[a];  
         }  
      }  
      arrTemporary[b++] = arrNumbers[num - 1]; 
      for(int a = 0; a < b; a++)
      {  
         arrNumbers[a] = arrTemporary[a];  
      }  
      return b;  
   }
   public static void main(String[] args) 
   {
      int[] arrInput = {1, 2, 3, 3, 4, 5, 5, 6, 7, 8};  
      int len = arrInput.length;  
      len = removeDuplicate(arrInput, len);  
      // printing elements
      for(int a = 0; a < len; a++)
      {
         System.out.print(arrInput[a] + "" "");
      }
   }
}

2. How to declare an array in Java?

Polymorphism is one of the OOPs features that allow us to perform a single action in different ways. For example, let’s say we have a class Animal that has a method sound(). Since this is a generic class so we can’t give it an implementation like Roar, Meow, Oink, etc. We had to give a generic message.

public class Animal{
   ...
   public void sound(){
      System.out.println(""Animal is making a sound"");   
   }
}
Now lets say we two subclasses of Animal class: Horse and Cat that extends (see Inheritance) Animal class. We can provide the implementation to the same method like this:

public class Horse extends Animal{
...
    @Override
    public void sound(){
        System.out.println(""Neigh"");
    }
}
and

public class Cat extends Animal{
...
    @Override
    public void sound(){
        System.out.println(""Meow"");
    }
}

3. How to return an array in Java?

import java.util.*;
public class Main
{
public static String[] return_Array() {
       //define string array
       String[] ret_Array = {""Java"", ""C++"", ""Python"", ""Ruby"", ""C""};
      //return string array
      return ret_Array;
   }
 
public static void main(String args[]) {
      //call method return_array that returns array   
     String[] str_Array = return_Array();
     System.out.println(""Array returned from method:"" + Arrays.toString(str_Array));
 
    }
}

4. How to generate random numbers in Java?

public static double getRandomNumber(){
    double x = Math.random();
    return x;
}

5. How to find the length of an array in Java?

class ArrayLengthFinder {
   public static void main(String[] arr) {
      // declare an array
      int[] array = new int[10];
      array[0] = 12;
      array[1] = -4;
      array[2] = 1;
      // get the length of array 
      int length = array.length;
      System.out.println(""Length of array is: "" + length);
   }
}

6. How to sort array in java?

public class InsertSort {
  public static void main (String [] args) {
   int [] array = {10,20,30,60,70,80,2,3,1};
   int temp;
   for (int i = 1; i < array.length; i++) {
    for (int j = i; j > 0; j--) {
     if (array[j] < array [j - 1]) {
      temp = array[j];
      array[j] = array[j - 1];
      array[j - 1] = temp;
     }
    }
   }
   for (int i = 0; i < array.length; i++) {
     System.out.println(array[i]);
   }
  }
}

7. How to convert a list to an array in java?

The best and easiest way to convert a List into an Array in Java is to use the .toArray() method.

Likewise, we can convert back a List to an Array using the Arrays.asList() method.

The examples below show how to convert List of String and List of Integers to their Array equivalents.

Convert List to Array of String
import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArray {
    public static void main(String[] args) {
        List<String> itemList = new ArrayList<String>();
        itemList.add(""item1"");
        itemList.add(""item2"");
        itemList.add(""item3"");

        String[] itemsArray = new String[itemList.size()];
        itemsArray = itemList.toArray(itemsArray);

        for(String s : itemsArray)
            System.out.println(s);
    }
}

8. How to convert string to char array in java?

public class StringToCharArrayExample{  
public static void main(String args[]){  
String s1=""hello"";  
char[] ch=s1.toCharArray();  
for(int i=0;i<ch.length;i++){  
System.out.print(ch[i]);  
}  
}}

9. Write a program to do bubble sort on an array in java.

import java.util.Scanner; 
class star 
{ 
  public static void main(String args[]) 
  { 
    int arr[] =new int [10]; 
    Scanner sc = new Scanner( System.in ); 
    System.out.println("Enter size of array"); 
    int n=sc.nextInt(); 
    System.out.print("Enter an arry : "); 
    for (int i=0;i<n;i++) 
        arr[i]=sc.nextInt(); 
    for (int i=0;i<n;i++) 
    { 
        for (int j=0;j<n-i-1;j++) 
        { 
            if (arr[j]>arr[j+1]) 
            { 
                int t=arr[j]; 
                arr[j]=arr[j+1]; 
                arr[j+1]=t; 
            } 
        } 
    } 
 for (int i=0;i<n;i++) 
    { 
        System.out.println(arr[i]); 
    } 
  } 
}

 10. How to initialize an array in Java?

int[] arr = new int[5];	 
// integer array of size 5 you can also change data type
String[] cars = {""Volvo"", ""BMW"", ""Ford"", ""Mazda""};

11. How to sort an array in Java?

import java. util. Arrays;
Arrays. sort(array);

Java Interview Questions FAQs

1. What should I prepare for the Java interview?

There is no fixed method through which you can prepare for your upcoming Java Interview. However, understanding the basic concepts of Java is important for you to do well. The next step would be to take up a Java Beginners Course that will help you understand the concepts well, or read the top books for self-learning. Apart from learning the basic concepts through courses, books, and blogs, you can also work on projects that will help you gain hands-on experience.

2. What are the basics of Java?

Java is an object-oriented general-purpose programming language. It is a popular programming language because of its easy-to-use syntax. The basics of Java include understanding what Java is, how to install Java and Java IDE, variables and data types in Java, Operators in Java, Arrays, Functions, Flow Control Statements, and basic programs. To learn the basics of Java, you can take up a Java for Beginners Course and understand the concepts required for you to build a successful career in Java Programming.

3. Is Java 100% object-oriented language?

No. Java is not a 100% object-oriented language. It follows some principles of an object-oriented language, but not all.

4. What are the features of Java?

The main features of Java include: multithreaded, platform-independent, simple, secure, architecture-neutral, portable, robust, dynamic, high-performance, and interpreted.

5. How can I learn Java easily?

Any method of learning that suits you and your learning style should be considered the best way to learn. Different people learn well through different methods. Some individuals may prefer taking up online courses, reading books or blogs, or watching YouTube videos to self-learn. And some people may also learn through practice and hands-on experience. Choose what works best for you!

You can enrol in these JAVA courses on Great Learning Academy and get certificates for free:

Java Programming
Data Structures and Algorithms in Java

Wondering where to learn the highly coveted in-demand skills for free? Check out the courses on Great Learning Academy. Enrol in any course, learn the in-demand skills and get your free certificate. Hurry!

{ “@context”: “https://schema.org”, “@type”: “FAQPage”, “mainEntity”: [{ “@type”: “Question”, “name”: “What should I prepare for Java interview?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “There is no fixed method through which you can prepare for your upcoming Java Interview. However, understanding the basic concepts of Java is important for you to do well. The next step would be to take up a Java Beginners Course that will help you understand the concepts well, or read the top books for self-learning. Apart from learning the basic concepts through courses, books, and blogs, you can also work on projects that will help you gain a hands-on experience.” } },{ “@type”: “Question”, “name”: “What are the basics of Java?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Java is a object-oriented general-purpose programming language. It is a popular programming language because of it’s easy-to-use syntax. The basics of Java include understanding what Java is, how to install Java and Java IDE, variables and data types in Java, Operators in Java, Arrays, Functions, Flow Control Statements, and basic programs. To learn the basics of Java, you can take up a Java for Beginners Course and understand the concepts required for you to build a successful career in Java Programming.” } },{ “@type”: “Question”, “name”: “Why is string immutable in Java?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “String is immutable in Java to ensure that the value of the string does not change. Java uses string literals, if there are multiple variables that refer to one object and the value of the object is changed, it would affect all reference variables. Hence, strings are immutable in Java.” } },{ “@type”: “Question”, “name”: “Why pointers are not used in Java?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Java doesn’t allow using pointers. Pointers are not used in Java to ensure that it is more secure and robust.” } },{ “@type”: “Question”, “name”: “Is Java 100% object oriented language?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “No. Java is not a 100% object oriented language. It follows some principles of object oriented language, but not all.” } },{ “@type”: “Question”, “name”: “What are the features of Java?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “The main features of Java include: multithreaded, platform independent, simple, secure, architecture neutral, portable, robust, dynamic, high-performance, and interpreted.” } },{ “@type”: “Question”, “name”: “How can I learn Java easily?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Any method of learning that suits you and your learning style should be considered as the best way to learn. Different people learn well through different methods. Some individuals may prefer taking up online courses, reading books or blogs, watching YouTube videos to self-learn. And some people may also learn through practice and hands-on experience. Choose what works best for you!” } },{ “@type”: “Question”, “name”: “What is API in Java?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “In Java, API stands for Application Programming Interface. It is a software that allows two applications to talk to each other. It is a list of classes that is part of a JDK or Java Development Kit and includes interfaces, packages, classes, fields, methods and constructors.” } },{ “@type”: “Question”, “name”: “What is Java full form?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Java is a programming language that is originally developed by James Gosling at Sun Microsystems. While the developers were drinking coffee and brainstorming names for their programming language, they chose to name it Java back in 1995. It does not have any full form.” } }] }

Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path:

Software engineering courses certificates
Software engineering courses placements
Software engineering courses syllabus
Software engineering courses fees
Software engineering courses eligibility

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top