RnewYear2022 RnewYear2022

- Java Blogs -

Top 110+ Java Interview Questions for Freshers & Advanced Professionals

Introduction

There are more than 3 billion devices that use Java for their software development. A plethora of job opportunities are available for Java Developers. Our goal in providing these Java interview questions and answers is to help you gain a deeper understanding of the language and be better prepared for your Java job interviews. 

In this Java Interview Questions blog, you will go through the top Java interview questions that you will come across in Java interviews. 

Let us have a glance at a few of the important Java programming interview questions here:

Top 110+ Java Interview Questions and Answers in 2023

Here is the list of the top frequently asked Java interview  questions and answers to help out freshers and experienced professionals. So let's begin. 

Java Interview Questions and Answers for Freshers

Let's begin with the first set of basic core Java technical interview questions, which are primarily relevant for freshers.

Q1). Explain what is Java?

Java is an object programming language that was premeditated to be moveable across several platforms and operating structures. This language was developed by Sun Microsystems. 

Java is exhibited after the C++ programming language and comprises special structures that make it perfect for programs on the Internet.

public class JanBask{

    public static void main(String[] args) {

        System.out.println("Hello, World!");

    }

}

Q 2). Explain the history of Java.

Java is a programming language that was first developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle) in the early 1990s. The language was designed with the goal of being "write once, run anywhere," meaning that code written in Java should be able to run on any platform without modification.

In 1995, Sun Microsystems released the first version of Java, called Java 1.0, which included the basic features of the language. This included the ability to create standalone programs as well as applets (small programs that run within a web page).

Over the years, Java has undergone several updates and improvements, with new versions being released regularly. Some of the most notable versions include Java 1.1 (1997), which added support for inner classes and JavaBeans, and Java 5.0 (2004), which introduced generics and annotations.

Q3). Explain the Meaning of Static in Java.

  • Static stands for one per class, not one for every object no matter how various instances of a class might occur. This entails that you can use them deprived of generating an instance of a class.
  • Static methods are indirectly final since overriding is done grounded on the type of the object and static approaches are involved in a class, not an object.
  • A static technique in a superclass can be followed by an alternative static method in a subclass if the unique method was not acknowledged as final.
  • Though, you can’t overrule a static technique with a non-static technique. In other words, you can’t modify a static technique into an illustration method of a subclass.

Q4). Why is Java Perceived to be Platform-Independent?

This is because platform-independent is the term that means “write once run anywhere”. Java is referred to because of its bytecodes that have the capacity to run on any system or device whatsoever irrespective of the underlying operating system.

Q5). What’s the feature of the Java programming language?

Java is a general-purpose, object-oriented programming language that is known for its features such as:

  1. Platform independence: Java code can run on multiple platforms, such as Windows, macOS, and Linux, without the need for modification. This is achieved through the use of the Java Virtual Machine (JVM), which interprets the Java code and runs it on the underlying operating system.
  2. Object-oriented: Java is based on the object-oriented programming paradigm, which means that the code is organized around objects and their interactions. This makes it easy to model real-world problems and create reusable and modular code.
  3. Automatic memory management: Java uses a technique called garbage collection to automatically manage the memory used by the program. This means that the programmer does not need to explicitly free memory, which can help to prevent memory leaks and other issues.
  4. Built-in support for multithreading: Java has built-in support for multithreading, which allows for the concurrent execution of multiple threads (smaller units of a process) within a program. This can make it easier to create responsive and high-performance applications.
  5. Rich API: Java comes with a large and powerful API (Application Programming Interface) that provides a wide range of functionality, including input/output, networking, and graphical user interface development.
  6. Strongly typed: Java is a strongly typed language, which means that variables have a specific data type and that the language checks for type consistency at compile time, helping to prevent type-related errors.
  7. Security: Java includes a number of security features, such as the Java Security Manager, that can help to protect against malicious code and other security threats.

Q6). Why is JAVA not 100% Object-Oriented?

Java is not cent percent object-oriented because it utilizes eight types of primitive datatypes named boolean, byte, char, int, float, double, long, and short which are not objects.

Q7). Explain Constructors in JAVA.

In Java, a constructor is a special type of method that is used to initialize an object when it is created. It is called automatically when an object is created using the "new" keyword, and it is used to set up the initial state of the object.

A constructor has the same name as the class, and it does not have a return type (not even void). Constructors can be overloaded, which means that a class can have multiple constructors with different parameter lists.

Here is an example of a simple class called "Person" that has a constructor:

class Person {

  String name;

  int age;

  // constructor

  Person(String name, int age) {

    this.name = name;

    this.age = age;

  }

}

To create an instance of the Person class and initialize it using the constructor, we would use the following code:

Person person1 = new Person("John", 30);

Q8). How many Types of Constructors are there in JAVA? 

There are two types of constructors in JAVA:

  • Default constructor: A constructor that has no parameters is called a default constructor. If a class doesn't have any constructor, then the compiler automatically provides a default constructor.
  • Parameterized constructor: A constructor that has parameters is called a parameterized constructor. It is used to initialize the object with specific values at the time of object creation.

Q9). What is a Singleton Class and How can we make a Class Singleton?

Singleton class is a class whose only instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

Q10). Is it Possible to Override a private or a Static Method in Java?

No, there is no provision to override a private or static method in Java. However, you can use the method hiding approach in extraordinary cases.

Q11). What do you mean by Association?

Association refers to a relationship where all the objects of the class have got their lifecycle and there is no owner as such. These relationships or associations as we call them can be one to one or one to many or many one or many to many.

Apart from these basic java interview questions for seasoned professionals, if you would like to be trained by experts in this technology, you can opt for JanBask Java Training.

Q12). Explain the Concept of Aggregation in JAVA.

Aggregation is a concept in JAVA for a specialized form of Association where all the objects have got their own lifecycle but there is ownership and the child object cannot belong to another parent object in any manner.

These were the java freshers' interview questions, now let’s move toward the questions asked by the seniors.

Q13). What is a classloader?

It is a subsystem of JVM that is used to load class files. When we run any Java program, it is loaded first by the classloader. There are three built-in classloaders in Java- Bootstrap ClassLoader, Extension ClassLoader, and System/ Application ClassLoader.

Q14). What do you mean by Data Encapsulation?

In Java, encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. It is one of the four fundamental principles of object-oriented programming (OOP) along with inheritance, polymorphism, and abstraction.

Data encapsulation in Java refers to the practice of hiding the implementation details of an object and exposing only the necessary information to the outside world. By making the fields of a class private and providing access to them through public methods, it ensures that the internal state of an object is protected from unauthorized access or modification. This allows for a more robust and secure design and also allows for greater flexibility in the implementation of the class.

Q15). What is the main objective of the Garbage Collection?

Freeing the heap memory by destroying unreachable objects is the main purpose of garbage collection.

 

Q16). What do you mean by JVM in Java?

JVM stands for Java Virtual Machine. It is an abstract computing machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled into Java bytecode. The JVM is responsible for converting the bytecode, which is platform-independent, into machine code, which is platform-specific.

It also provides the runtime environment in which Java bytecode can be executed. It is responsible for memory management, secure execution of code, and implementing the various features of the Java language, such as object-oriented features and exception handling.

In summary, JVM is a crucial component of the Java ecosystem that enables Java programs to run on different platforms without modification, by providing a standard runtime environment for executing Java bytecode.

Q17). Explain JRE.

JRE stands for Java Runtime Environment. It is a software package that contains the necessary components to run Java programs on a particular platform. It includes the Java Virtual Machine (JVM), the Java class libraries, and the Java application launcher.

The JRE provides the runtime environment for executing Java bytecode, which is the intermediate form of a Java program after it has been compiled. The JVM, which is a part of the JRE, interprets the bytecode and executes the program.

Q18). What is JDK in Java programming language?

The JDK stands for Java Development Kit. It is a software development environment used for developing Java applications and applets. It contains the necessary tools and libraries to develop, compile, and run Java programs.

The JDK includes the Java Runtime Environment (JRE), which provides the runtime environment for executing Java bytecode, the Java compiler, which is used to convert the source code into bytecode, and various other tools and utilities.

Q19). What are the differences between JVM, JRE, and JDK in Java?

Following are the difference between JVM, JRE, and JDK:

JVM: Stands for Java Development Kit, and is used for code development and execution. 

JRE: It stands for Java Run Environment, JRE is used for environment creation to execute the code. 

JVM: It stands for Java Virtual Machine and is used to provide specifications to implement JRE. 

 Here is a complete guide on How to Become a Java Developer

Q20). What are the advantages of Packages in Java?

Packages in Java provide several advantages, including

  1. Namespace Management: Packages provide a way to group related classes and interfaces and prevent naming conflicts between different classes or interfaces with the same name. This allows for a more organized and maintainable codebase.
  2. Access Control: Packages provide a way to control the visibility of classes and interfaces to other parts of the program. This allows for encapsulation and abstraction, which helps to ensure that the implementation details of a class or interface are hidden from other parts of the program.
  3. Reusability: Packages make it easier to reuse existing classes and interfaces, as they can be easily imported and used in other parts of the program. This helps to reduce the amount of code that needs to be written and makes development faster.
  4. Built-in Java Libraries: Packages include a set of built-in Java libraries, such as java.lang, java. util, and java.io, which provide commonly used functionality, such as input/output, collections, and string manipulation.
  5. Third-party Libraries: Packages make it easy to use third-party libraries, such as Apache commons, Google Guava, and many more.

Q21). Explain the Externalizable interface.

The externalizable interface helps to control the serialization process. Just like the serializable interface, it is a class that implements the Externalizable interface and is marked to be persisted. 

Q22). Explain the JIT compiler in Java?

JIT (Just-In-Time) compiler is a component of the Java Virtual Machine (JVM) that is responsible for improving the performance of Java applications at runtime. The JIT compiler works by converting the Java bytecode, which is platform-independent, into native machine code, which is specific to the host platform.

The JIT compiler analyzes the code as it is being executed, and dynamically compiles the most frequently executed sections of code into native machine code. This can significantly improve the performance of the application, as the compiled code can be executed much faster than the interpreted bytecode.

 

Q23). What do you mean by Class in Java?

In Java, a class is a blueprint or template for creating objects. It defines the properties and methods that an object of that class will have. A class can be thought of as a container for data (fields/variables) and functionality (methods) that are related to each other.

A class definition typically includes:

  • Fields: Variables that represent the state of an object.
  • Methods: Functions that define the behavior of an object.
  • Constructors: Methods used to create and initialize objects of the class.
  • Blocks: Initialization blocks that are used to initialize fields of the class.
  • Inner classes: Classes defined inside other classes.

For example, a class called "Car" might have fields like "year", "make", "model", "color", "speed", and methods like "start()", "stop()", "accelerate()", "brake()". An object of the class "Car" would be an instance of that class, with its own set of data and functionality.

These are the very basic java developer interview questions. Let's see some intermediate-level interview questions for java developers.

Q24). What is an Object in Java programming language?

In Java, an object is an instance of a class. It is a real-world entity that has a state (data) and behavior (methods). An object is created from a class, and it has its own unique identity, state, and behavior.

Q25). Explain different types of variables in Java language.

In Java, there are several types of variables, including:

  1. Static variables: These are variables that are associated with a class, rather than an object, and they can be accessed without creating an instance of the class.
  2. Local variables: These are variables that are defined within a method or block of code, and they can only be accessed within that method or block of code.
  3. Instance variables: These are variables that are defined at the class level, outside of any method, and they can be accessed by any method in the class.

Example:

class JanBask{  

int a=30;//instance variable  

static char name=prakash;//static variable  

void method(){  

int num=90;//local variable  

}  

}

Q26). What is the exact reason for not using a pointer in Java language?

Pointers are not used in Java because they are a major source of security vulnerabilities and stability issues. Pointers allow direct memory manipulation, which can lead to memory leaks and buffer overflows. These types of bugs can allow attackers to gain unauthorized access to sensitive data or take control of a program.

Q27). Explain Typecasting.

Typecasting in Java refers to the process of converting one data type to another. This is also known as type conversion or type coercion.

There are two types of typecasting in Java:

  1. Implicit typecasting: This is also known as automatic typecasting, and it occurs when a smaller data type is converted to a larger data type. For example, an int can be implicitly typecasted to a long or a double.
  2. Explicit typecasting: This is also known as manual typecasting, and it occurs when a larger data type is converted to a smaller data type. For example, a double can be explicitly typecasted to an int.

An example of implicit typecasting:

int x = 10;

double y = x;  // int is implicitly typecasted to double

An example of explicit typecasting:

double x = 10.5;

int y = (int) x; // double is explicitly typecasted to int

Q28). What are access modifiers in Java language?

In Java, access modifiers are keywords that are used to set the level of access for classes, methods, and variables. The four main access modifiers in Java are:

  1. public: A class, method, or variable that is declared as public can be accessed from anywhere in the program.
  2. private: A class, method, or variable that is declared as private can only be accessed within the same class.
  3. protected: A class, method, or variable that is declared as protected can be accessed within the same package or by a subclass in a different package.

Q29). What do you mean by “Double Brace Initialization” in Java?

Double brace initialization is a technique used to initialize an anonymous inner class, typically used for creating anonymous instances of a class or an interface. It uses two sets of curly braces, one for the anonymous inner class and another for the instance initialization block.

An example of Double brace initialization for creating an anonymous HashSet:

Set set = new HashSet() {{

    add("item1");

    add("item2");

}};

Q30). What is the Unicode system in Java?

Unicode is a standardized character encoding system that assigns unique numerical codes to each character in a wide range of scripts and languages. In Java, Unicode is used to represent characters and strings and is the default character encoding used in the Java platform.

Java uses the Unicode character set, which includes most of the characters used in the world's written languages, as well as many symbols and special characters. Each character is represented by a unique code point, which is a number between 0 and 65535. For example, the code point for the letter "A" is 65, and the code point for the euro symbol (€) is 8364.

If you face difficulties with these technical java interview questions, you can comment your queries in our comment section. Our team will revert back to you. In addition to this blog, if you want expert training on this technology, you can opt for JanBask Online Java Training.

Q31). Explain Object Oriented Programming.

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and methods that operate on that data. Java is an object-oriented programming language, which means that it follows the principles of OOP.

Q32). What are the main concepts of OOP in Java?

The main concepts of OOP in Java are:

  1. Encapsulation: This is the concept of hiding the internal details of an object from the outside world, and only exposing a public interface for interacting with the object. This allows for the implementation details of an object to be changed without affecting the rest of the program.
  2. Inheritance: This is the concept of creating a new class (a child class) that inherits the properties and methods of an existing class (the parent class). This allows for code reuse and can reduce the complexity of a program.
  3. Polymorphism: This is the concept of using a single interface to represent multiple types of objects. This allows a program to use objects of different classes interchangeably, as long as they implement the same interface.
  4. Abstraction: This is the concept of reducing complexity by hiding unnecessary details, and exposing only the essential features of an object or system.

Q33). What do you mean by Polymorphism?

Polymorphism in Java is the ability of an object to take on many forms. It is one of the four fundamental principles of object-oriented programming (OOP) along with encapsulation, inheritance, and abstraction.

There are two types of polymorphism in Java:

  1. Compile-time polymorphism: also known as method overloading, it occurs when a class has multiple methods with the same name but different parameters. The Java compiler can determine which method to call based on the number and types of the arguments passed to the method at compile-time.
  2. Run-time polymorphism: also known as method overriding, it occurs when a subclass provides a different implementation of a method that is already defined in its superclass. The Java runtime determines which method to call based on the actual type of the object at runtime.

Q34). Explain Abstraction in Java.

In Java, abstraction is a process of hiding the implementation details and showing only the functionality to the user. It is one of the four fundamental principles of object-oriented programming (OOP) along with encapsulation, inheritance, and polymorphism.

Abstract classes and interfaces are used to achieve abstraction in Java. An abstract class is a class that cannot be instantiated and is typically used as a base class for other classes. An interface is a collection of abstract methods (methods without a body) that a class can implement.

For example, consider a class called "Car" which has methods such as startEngine(), stopEngine(), and changeGear(). Instead of showing how these methods are implemented, we can simply show that the class has these methods and what they do. This way, the user of the class can use these methods without worrying about how they are implemented.

Q35). What is Interface in Java language?

In Java, an interface is a blueprint for a class. It defines a set of methods that a class must implement, but does not provide an implementation for those methods. Interfaces are used to achieve abstraction and multiple inheritance in Java.

An interface is defined using the keyword "interface" and it can contain only abstract methods (methods without a body) and constants. A class that implements an interface must provide an implementation for all the methods defined in the interface. A class can implement multiple interfaces.

For example, consider an interface called "Movable" which has methods such as moveUp(), moveDown(), moveLeft() and moveRight(). Any class that implements this interface must have these methods and provide an implementation for them.

Let’s see some more technical interview questions java.

Q36). What is Inheritance in Java?

Inheritance is referred to one class that can extend to another. So that the codes can be used again from one to another class. The existing class is referred to as the Superclass whereas the derived class is known as a subclass. 

Q 37). What are the different types of Inheritance in Java?

In Java, there are four types of inheritance:

  1. Single Inheritance: A class inherits from a single superclass. In other words, a subclass inherits the properties and methods of a single superclass.
  2. Multiple Inheritance: A class inherits from multiple superclasses. Java does not support multiple inheritances directly, but it can be achieved through interfaces.
  3. Multi-level Inheritance: A subclass inherits from a superclass, which in turn inherits from its own superclass. This creates a hierarchical chain of inheritance.
  4. Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.

Q38). Is Java not supporting multiple inheritances? Why?

Java does not support multiple inheritances, which means that a class cannot inherit from more than one superclass. This is because of the diamond problem, which can occur when multiple classes inherit from a common superclass.

In traditional multiple inheritance, a subclass can inherit conflicting implementations of the same method from its multiple superclasses. This creates an ambiguity about which method should be invoked when the method is called on an instance of the subclass.

For e.g.

class JanBask1

{

void test()

{

system.out.println("test() method");

}

}class JanBask2

{

void test()

{

system.out.println("test() method");

}

}Multiple inheritance

class C extends JanBask1, JanBask2

{

     /* Code */

}

Q39). What do you mean by method overloading and method overriding?

In Java, method overloading and method overriding are two concepts related to polymorphism.

Method overloading is the ability of a class to have multiple methods with the same name but different parameters. This allows methods with the same name to be called with different arguments, and the appropriate method will be executed based on the number and type of arguments.

Method overriding is the ability of a subclass to provide a specific implementation of a method that is already provided by its superclass. The subclass can override a method by providing a new implementation for the method with the same name, return type, and parameters as the method in the superclass. The overriding method must use the same method signature as the method it is overriding.

For example, consider a class called "Shape" with a method called "draw()". If a subclass called "Circle" wants to provide a different implementation of the "draw()" method, it can override the "draw()" method in the superclass with its own implementation.

Q40). What is the purpose of encapsulation in Java?

The purpose of encapsulation in Java is to hide the implementation details of a class and provide controlled access to its properties and methods. It is one of the four fundamental principles of object-oriented programming (OOP) along with inheritance, polymorphism, and abstraction.

Encapsulation is achieved through the use of access modifiers such as "private", "protected", and "public". A class can use these modifiers to control access to its properties and methods. For example, a class can use the "private" modifier to make a property or method accessible only within the class, and the "public" modifier to make a property or method accessible to any other class.

Encapsulation provides several benefits, including:

  1. Data hiding: Encapsulation allows a class to hide its internal data and methods from other classes, which prevents them from being directly accessed and modified.
  2. Increased security: Encapsulation helps to prevent unauthorized access to a class's properties and methods, which increases the security of the data.
  3. Flexibility: Encapsulation allows a class to change its internal implementation without affecting other classes that use it, which increases the flexibility of the code.
  4. Better maintenance: Encapsulation makes the code more maintainable by providing a clear separation of responsibilities.

Q41). What do you mean by the final keyword in Java?

The "final" keyword in Java is used to indicate that a variable, method, or class cannot be modified.

  1. Final variables: A final variable is a variable that cannot be reassigned after it has been initialized. Once a final variable is assigned a value, it cannot be changed.
  2. Final methods: A final method is a method that cannot be overridden by subclasses. This means that the implementation of a final method in a superclass cannot be changed by any subclass.
  3. Final classes: A final class is a class that cannot be extended by any other class. This means that a final class cannot have any subclasses.

The final keyword also can be used to improve the performance of a program by telling the compiler that the value of a final variable will not change, and the JIT compiler can optimize the code accordingly.

Q42). Is an empty .java file name a valid source file name in java?

No, an empty .java file name is not a valid source file name in Java. In Java, a source file must have a valid name and it should follow the naming conventions. According to the Java Language Specification, the source file name should have a .java extension and it should contain a top-level class or interface declaration.

Apart from these basic java interview questions for seasoned professionals, if you would like to be trained by experts in this technology, you can opt for JanBask Java Training.

Q43). What do you mean by Object Cloning in Java?

Object cloning in Java refers to the process of creating a copy of an existing object. The clone method in the Object class can be used to create a copy of an object, but it is a protected method and should be overridden in order to be used.

In order to create a new object that is an exact copy of an existing object, the class of the object must implement the Cloneable interface. This interface is a marker interface, which means that it doesn't contain any methods, it only serves as a flag to indicate that a class allows objects of its type to be cloned.

When an object is cloned, a new object is created with the same state as the original object, but the new object has a different memory address. This means that changes made to the new object will not affect the original object and vice versa.

Q44). Why are Java Strings immutable in nature?

Java strings are immutable in nature because strings are commonly used as keys in hash tables, such as those used in HashMap and Hashtable classes. If strings are mutable, their values could change after they were used as keys in a hash table, which would make it difficult or impossible to retrieve the corresponding value.

In addition to this blog, if you want expert training on this technology, you can opt for JanBask Online Java Training.

Q45). What is a collection class in Java language?

A collection class in Java is a class that is used to store and manage a group of objects. The Java collections framework is a set of classes and interfaces that provides a unified architecture for storing and manipulating collections of objects.

The core interfaces of the Java collections framework are:

  • The Collection interface, which is the root interface of the collections framework and represents a collection of objects.
  • The List interface, which extends the Collection interface and represents an ordered collection of elements.
  • The Set interface, which extends the Collection interface and represents a collection of unique elements.
  • The Map interface, which represents a collection of key-value pairs, where each key is unique.

Q46). What is Multithreading?

It is a process to execute different threads simultaneously. Multithreading is generally used for multitasking. It consumes less memory and provides fast and effective performance.

Apart from this blog, if you want to become a certified Java Developer in 2023 then you should definitely check out this JanBask course.

Q47). Explain Java String Pool.

Java String Pool, also known as String Intern Pool, is a storage area in Java heap where string literals are stored. 

Q48). What is a Map in Java? 

It is an interface of Util packages that maps unique keys to values. Map interface is not just a subset of the primary collection interface and hence it works in a different way. 

Q49). What is a Servlet?

In JAVA atmosphere a Java Servlet is a server-side technology used to extend the capability of the web servers by providing support for dynamic response and data persistence.

Q50). What do you Understand about Request Dispatcher?

The request Dispatcher interface in JAVA is used to forward the request to another resource which can be HTML, JSP or any other servlet within the same application.

There are two methods defined in this interface:

  • void forward()
  • void include()

JAVA Interview Questions and Answers for Experienced

Q51). How do cookies work in Servlets?

Cookies are small text files that a server can store on a client's computer. In a Servlet, you can use the javax.servlet.http.Cookie class to create and retrieve cookies. 

To set a cookie, you can create a new Cookie object, set its name, value, and other properties, and then add it to the response using the HttpServletResponse.addCookie() method. 

To retrieve a cookie, you can use the HttpServletRequest.getCookies() method to get an array of all cookies associated with the current request, and then iterate through the array to find the cookie you're looking for. 

Once you have a cookie, you can read its properties, like its name and value, and use that information to personalize the user's experience.

Q 52). Explain Late Binding in Java.

Late binding, also known as dynamic method dispatch, is a feature in Java that allows a program to determine the method to be invoked at runtime rather than at compile time. This is achieved through the use of polymorphism, which allows objects of different classes to be treated as objects of a common superclass or interface.

In Java, late binding is implemented through the use of virtual method tables (VMTs) and virtual method pointers (VMPs). When a method is called on an object, the JVM looks up the method to be invoked in the object's VMT, which is a table that contains a list of all the methods that can be invoked on the object. The VMT also contains the memory address of the method implementation, which is called the VMP. The JVM uses the VMP to invoke the correct method at runtime.

Q53). Is it Possible to Generate Array Volatile in Java?

Yes, you can generate an array volatile in Java but then again only the situation is directed to an array, not the entire array. This means that, if one thread deviates the reference variable to direct to the extra array, that will offer a volatile assurance, but if multiple threads are altering separate array elements they won’t be having ensues before assurance offered by the volatile modifier.

Also read: Java Developer Role & Responsibilities

Q54). Explain the Concept of Interfaces in JAVA.

Interfaces are gentler in performance as compared to abstract classes as additional indirections are compulsory for interfaces. An additional key factor for designers to take into deliberation is that any class can spread only one abstract class through a class that can implement numerous interfaces. The use of lines also places an additional burden on the developers at any time an interface is executed in a class; the developer is required to contrivance each and every technique of interface.

Q55). What are Real-World Practices of Volatile Modifiers?

One of the real-world uses of the volatile variable is to generate interpretation double and long atomic. Equally double and long are 64-bit extensive and they are recited in two parts, primary 32-bit first time and following 32-bit another time, which is non-atomic but then again volatile double in addition long read is atomic in Java. Additional use of the volatile variable is to deliver a recall barrier, just like it is cast off in the Disruptor framework. Fundamentally, the Java Memory model pull-outs a write barrier. Subsequently, you write to a volatile variable besides a read barrier beforehand you read it. That means, if you inscribe to the volatile field then it’s definite that any thread retrieving that variable will see the worth you wrote and everything you did beforehand doing that correct into the thread is certain to have occurred and any rationalized data values will also be noticeable to all threads since the memory barrier flushed all additional writes to the cache.

Q56). How to differentiate Static Loading and Dynamic Loading?

Static loading and dynamic loading are two different ways to load class files into a Java program at runtime.

Static loading, also known as early binding, occurs when the class files are loaded into the program at compile time. This means that the JVM loads all the required class files into memory when the program is compiled, and the classes are available to the program when it starts.

On the other hand, dynamic loading, also known as late binding, occurs when the class files are loaded into the program at runtime. This means that the JVM does not load the class files into memory until they are actually needed by the program. This can be done using the Class.forName() method or the ClassLoader.loadClass() method.

Feature

Static Loading

Dynamic Loading

Loading Time

Compile Time

Run Time

Memory Usage

Higher

Lower

Flexibility

Less

More

Class Availability

Available at program start

Available when needed

Method Overriding

Can't handle overridden methods

Can handle overridden methods

Performance

Slower

Faster

Q57). Define JAXP and JAXB.

JAXP (Java API for XML Processing) is a Java API that provides a set of standard interfaces for processing XML documents. JAXP allows developers to parse, transform, and validate XML documents using a common set of interfaces regardless of the underlying XML parser implementation. JAXP provides a pluggable architecture, which means that developers can switch between different XML parsers, such as SAX and DOM, without changing the code that uses JAXP.

JAXB (Java Architecture for XML Binding) is a Java API that provides a way to map Java classes to XML documents and vice versa. JAXB allows developers to marshal Java objects to XML and unmarshal XML to Java objects, using annotations or XML schema to define the mapping between the Java classes and the XML documents. JAXB also provides a way to validate XML documents against a schema and perform other operations such as filtering and transforming the XML.

Q58). Explain the meaning of Thread-local Variable in Java.

Thread-local variables are variables limited to a thread, it’s like a thread's individual copy which is not public between numerous threads. Java offers a Thread Local class to care for thread-local variables. It’s one of the numerous ways to attain thread safety. Though be cautious while using thread locally adjustable in managed environments e.g. with network servers where operative thread outlives somewhat application variables. A somewhat thread-local variable that is not detached once its work is done can possibly reason a memory leak in a Java application.

Q59). Explain the Meaning of the platform.

A platform is the hardware or software setting in which a program executes. Maximum platforms in JAVA can be defined as a grouping of the operating system and hardware, Windows 2000/XP, Linux, Windows 2000/XP, macOS, and Solaris.

In addition to this blog, if you want expert training on this technology, you can opt for JanBask Online Java Training.

Q60). What’s the variance between an Abstract Class and Interface in Java?

The main difference between an abstract class and an interface is that a boundary can only own assertion of public static approaches with no existing application while an abstract class can have associated with any admittance specified (i.e. public, private, etc.) with or without real implementation. Additional key variance in the usage of abstract classes and lines is that a class that gears an interface must contrivance all the approaches of the interface while a class that receives from an abstract class doesn’t need the execution of all the methods of its superclass. A class can instrument numerous interfaces but it can spread only one abstract class.

Q61). Define an enumeration.

An enumeration, also known as an enum, is a special type of data type in Java that defines a fixed set of named values. Enumerations are used to represent a fixed set of predefined values, such as days of the week, months of the year, or error codes.

An enumeration is defined using the enum keyword, followed by the name of the enumeration and a list of enumeration constants enclosed in curly braces. Each enumeration constant is separated by a comma, and the list of enumeration constants is terminated with a semicolon.

Here is an example of an enumeration that defines a set of possible status codes for a customer:

public enum Status {

    ACTIVE, INACTIVE, PENDING, SUSPENDED;

}

Q62). What is the reason for using vector classes?

Vector classes, such as java.util.Vector, are used in Java to provide a dynamic array data structure. They are similar to arrays but can grow or shrink in size as needed, which makes them more flexible and efficient than arrays in certain situations.

Here are some reasons why you might use vector classes:

  • Dynamically resizing: A vector can grow or shrink in size as needed, which allows you to add or remove elements to the vector without having to worry about running out of space or having unused space.
  • Thread-safe: Vector classes are thread-safe, which means that multiple threads can access the vector without having to worry about synchronization or data inconsistencies.
  • Legacy support: Vector classes have been around since the early days of Java and are used in many legacy applications. They are also compatible with older versions of Java, whereas some newer data structures such as ArrayList are not.

Q63). What is Session Management in Java?

Session management in Java refers to the process of tracking and maintaining the state of a user's interactions with a web application over a period of time. It allows the web application to remember information about a user's interactions and preferences, even if the user closes the browser or navigates to a different page.

There are several ways to implement session management in Java, but the most common method is to use the HttpSession interface provided by the Servlet API. The HttpSession interface allows you to create, retrieve, and invalidate a session, as well as set and get attributes associated with a session.

Here is an example of how you might use the HttpSession interface to create and retrieve a session:

// Creating a session

HttpSession session = request.getSession();

// Setting an attribute

session.setAttribute("user", "John Doe");

// Retrieving an attribute

String user = (String) session.getAttribute("user");

 

Q64). What is the difference between transient and volatile variables in Java?

In Java, a transient variable is a variable that will not be serialized (saved as part of the object's state) when the object is persisted to storage. This means that when an object containing a transient variable is serialized and then deserialized, the value of the transient variable will not be retained.

A volatile variable, on the other hand, is a variable that is guaranteed to be visible to all threads. When a thread reads a volatile variable, it will see the most recent value written to that variable by any other thread, even if the other thread wrote to it from a different core or processor. This can be useful for ensuring that threads see the most up-to-date value of a variable, particularly in multi-threaded code.

Q65). What is the variance between an Inner Class and a Sub-Class?

An Inner class is a class that is copied up to the additional class. An Inner class has admit privileges for the class which is nesting it and it can contact all variables and systems well-defined in the outer class, whereas a sub-class is a class that receives from another class named Superclass. Sub-class can contact all public and protected approaches and fields of its superclass.

Q66). Can we affirm a class as Abstract Deprived of having an Abstract Method?

Yes, we can generate an abstract class via abstract keyword beforehand class name even if it doesn’t have any abstract method. Though, if a class has even one abstract technique, it must be acknowledged as abstract or else it will give an error.

Q67). Can Volatile Generate a Non-Atomic Process to Atomic?

This additional good question I prefer to ask on volatile, typically as a follow-up of the preceding question. This query is also not simple to respond since volatile is not about atomicity, but there are situations where you can practice volatile flexibility to make the operation atomic. One instance I have seen is having a long arena in your class. If you distinguish that a long field is retrieved by extra than one thread e.g. an application, a value field or everything, you will make it volatile. Why? Since reading to an extended variable is not atomic in Java and done in double steps, if one thread is lettering or apprising long value, it’s probably for the additional thread to see half value (fist 32-bit). While interpretation/writing a volatile long or dual (64 bit) is atomic.

Q68). Explain the difference between get and post methods.

In Java, the HTTP GET method is used to retrieve data from a server, while the HTTP POST method is used to send data to a server for processing. 

The main difference between the two methods is that GET requests include data as part of the URL, while POST requests include data in the body of the request. Additionally, GET requests are idempotent, meaning that multiple identical requests will return the same response, while POST requests may have side effects and may not be idempotent. 

Due to these differences, GET requests are typically used for simple queries or data retrieval, while POST requests are used for more complex operations such as updates or data creation.

Q69). Differentiate forward() method and sendRedirect() methods?

In Java, the forward() method and the sendRedirect() method are used to navigate between different pages or resources within a web application.

The forward() method, which is part of the ServletRequest interface, is used to forward a request from one servlet to another resource, such as a JSP page or another servlet.

The sendRedirect() method, which is part of the HttpServletResponse interface, is used to redirect the client's browser to a different URL.

Let’s see some more technical interview questions on java.

Q70). Explain the wait-notify code for the producer-consumer situation?

Please understand the response for a code example. Just recollect to call wait () and inform () technique from the coordinated block and test waiting for ailment on the loop as an alternative of if block.

Q71). Explain Thread-Safe Code Singleton in Java?

Please understand the answer for a code instance and stage-by-stage guide to generating thread-safe singleton code in Java. As soon as we say thread-safe, which means Singleton should continue singleton even if low-level formatting occurs in the case of numerous threads. Using Java enum as Singleton class is one of the simplest ways to generate a thread-safe singleton in Java.

Q72). What are the Performance Inferences of Interfaces Over Abstract Classes?

Interfaces are gentler in performance as compared to abstract classes as additional indirections are compulsory for interfaces. Additional key factor for designers to take into deliberation is that any class can spread only one abstract class through a class that can implement numerous interfaces. Use of lines also places an additional burden on the developers at any time an interface is executed in a class; the developer is required to contrivance each and every technique of interface.

Q73). Explain JDBC Driver in Java language?

JDBC (Java Database Connectivity) is a Java API that allows Java programs to interact with a database. In order to use JDBC, a JDBC driver is required. A JDBC driver is a software component that enables a Java application to interact with a database by providing a standardized API for database access.

There are four types of JDBC drivers:

  1. Type 1 JDBC driver, also known as the JDBC-ODBC bridge driver, uses the ODBC driver to connect to a database.
  2. Type 2 JDBC driver, also known as the Native-API/partly Java driver, uses the client-side libraries of the database management system (DBMS) to connect to the database.
  3. Type 3 JDBC driver, also known as the Network-Protocol/All-Java driver, uses a pure Java client to communicate with a middleware server that translates the client's requests into DBMS-specific calls.
  4. Type 4 JDBC driver, also known as the Native-protocol/all-Java driver, communicates directly with the database using a pure Java client.

Q74). What are the JDBC API components?

The JDBC API (Java Database Connectivity API) is a collection of classes and interfaces that provide a standard way for Java programs to interact with databases.

Q75). List out the steps to connect to a database in java?

Here are the general steps to connect to a database in Java using JDBC:

  1. Load and register the JDBC driver.
  2. Establish a connection to the database.
  3. Create a statement.
  4. Execute the statement.
  5. Process the results.
  6. Close the connection.

Q76). Explain Reason that why is compile-time persistent in Java? What is the risk of using it?

Public static ultimate variables are also recognized as a compile-time endless, the public is non-compulsory there. They are swapped with definite values at compile time since the compiler distinguishes their value up-front and also distinguishes that it cannot be changed throughout run-time. One of the problems with this is that if you used a public stationary final variable from some in-house or third-party library and their worth changed, then your client will still be using the old value even after you organize a new version of JARs. To evade that, make certain you compile your program when your elevation dependence JAR files.

Q77). Why does Java not accompany manifold inheritances?

Java development team hit to make Java as

  • Unpretentious, object-oriented, and acquainted
  • Vigorous and secure
  • Architecture unbiased and transferrable
  • Extreme performance
  • Understood, threaded and lively
  • The details for overlooking Multiple Inheritance from the Java Language regularly stem from the unassuming, object-oriented and acquainted goal.

Q78). What are the observer and observable classes?

Observer is any object that wants to get notified when the stage of another object changes. While observable is any object whose stage might be interested, and in whom another object may get its interest listed. 

In addition to this blog, if you want expert training on this technology, you can opt for JanBask Online Java Training.

Q79). What are the different ways to handle exceptions?

There are mainly two ways to handle exception:

First is using try/catch: This risky code is surrounded by try blocks. Under it, when an exception occurs, then it is caught by the catch block. 

The second way is by declaring throws keyword: Here, at the end of the method, we can declare the exception by using throws keyword. 

Check Java Developer Resume Guide.

Q80). Explain the role of JDBC DriverManager class.

The JDBC DriverManager class is a central point of the JDBC API that is responsible for managing a list of JDBC drivers and for establishing a connection to a database. The main role of the DriverManager class is to:

  1. Load and register JDBC drivers.
  2. Establish a connection.
  3. Manage a list of drivers.
  4. Proxying driver.
  5. Handle exceptions.

Q81). What is meant by Serialization?

Converting any file into a byte stream is referred to as Serialization. The objects of the field are converted into bytes for security reasons. 

If you face difficulties with these java core interview questions, please comment down your queries. 

Q82). Can a constructor return a value?

No, there are return value statements in the constructor. 

Q83). What is a JIT compiler?

JIT stands for Just-in-Time compiler, it is basically a program to convert the Java bytecode into instructions, sent directly to the processor. JIT compiler is enabled by default in Java, it is activated when a Java method is invoked. 

Q84). What are the Memory Allocations available in JavaJava?

The memory allocations are available in three parts, namely Code, Stack, Heap, and Static.  

Q85). What are the different methods of session management in servlets?

A conversational stage between the client and server, sessions can consist of numerous requests from client and server. Since HTTP and Web Server are stateless, the only way to maintain a session is when some unique info is passed through the client and server in every response. 

Q86). What are the various directives in JSP?

In JSP (JavaServer Pages), directives are used to provide additional information to the JSP container about how a page should be handled and processed.

The following are the main types of directives in JSP:

  1. page Directive: The page directive is used to provide information about the current JSP page, such as the content type, the buffer size, and the error page to be used in case of an exception.

  2. include Directive: The include directive is used to include the content of another resource, such as a JSP page or a static file, in the current JSP page. This can be useful for including common elements, such as headers and footers, across multiple pages.

  3. Taglib Directive: The Taglib directive is used to import a custom tag library and make its tags available for use on the JSP page. Tag libraries provide a way to encapsulate complex logic and HTML markup in reusable tags.

  4. tag Directive: The tag directive is used to provide information about a custom tag, such as its name, the class that implements it, and the attributes that it accepts.

  5. attribute Directive: The attribute directive is used to define an attribute for a custom tag.

Q87). Explain hashCode() method.

In Java, the hashCode() method is a method that is defined in the Object class, which is the parent class of all objects in Java. The hashCode() method returns an integer value that represents the hash code of an object.

The hash code is a unique integer value that is associated with an object, it's typically used to identify the object in a hash-based data structure, such as a HashMap or HashSet. The hash code is calculated based on the object's internal state, such as its field values.

Q88). What’s the difference between Stack and Heap memory in Java language?

 In Java, Stack and Heap are two different types of memory that are used for different purposes.

Stack memory:

The Stack is a memory space that is used to store method call frames and local variables. Each thread in a Java program has its stack, and each time a method is called, a new frame is pushed onto the stack. The frame contains information about the method call, such as the method arguments and local variables. When the method returns, the frame is popped off the stack, and the memory is reclaimed. Because the stack is used to store method call frames and local variables, the size of the stack is typically much smaller than the size of the heap.

Heap memory:

On the other hand, Heap memory is the memory space where the objects and class instances are stored. The heap is a global memory space that is shared by all threads in a Java program. When an object is created, it is allocated memory on the heap, and when the object is no longer needed, the memory is reclaimed by the garbage collector. Because the heap is used to store objects and class instances, the size of the heap is typically much larger than the size of the stack.

Q89). What is Hibernate Framework?

Hibernate Framework is the programming technique that maps application domain model objects to the relational database tables. The Hibernate Framework provides the option to map plain old java objects to traditional database tablets with JPA annotations and XML configuration. 

Q90). Top Java Interview Question: What are the important benefits of using Hibernate Framework?

Here is the list of major benefits of using Hibernate Framework:

  • It eliminates all the boilerplate code that comes with JDBC and takes care of managing resources. 
  • It supports XML and JPA annotations, which makes code implementation independent. 
  • It is easy to integrate with other Java EE frameworks, it is quite famous that Spring Framework comes up with built-in support. 

Q91). What is the difference between an Error and an Exception?

An error is an irrecoverable condition that occurs at the runtime. Exceptions are conditions, occurring because of bad input or human error. 

Error

Exception

Represent serious problem

Represent a problem that can be handled by the program

Beyond the control of the program

Can be handled and recovered from

Example: OutOfMemoryError, StackOverflowError

Example: FileNotFoundException, IllegalArgumentException

Should not be caught but logged and recorded

Can be caught and handled using a try-catch block

Can crash the application

Can be handled and the application can continue to run

Extends the Error class

Extends the Exception class

Q92). What purpose do the keywords final, finally, and finalize fulfill?

  • Final: It is used to apply restrictions on class, variable, as well as method. 
  • Finally: It is used to place significant code, executed whether the exception is handled or not. 
  • Finalize: It is used to perform cleaning processing just before the object is garbage collected. 

Q93). What is the difference between a local variable and an instance variable?

A local variable in Java is mainly used in a method, constructor, or block and has a local scope. While an instance variable is a variable that is bound to its object itself.

Q94). What are the types of Exceptions in Java?

In Java, there are two main types of exceptions: checked exceptions and unchecked exceptions.

  1. Checked exceptions: Checked exceptions are exceptions that are checked by the Java compiler at compile time. These exceptions are typically related to input/output operations, such as reading from a file or writing to a network socket. Examples of checked exceptions include IOException, FileNotFoundException, and SQLException. The program must either catch these exceptions using a try-catch block or declare that the method throws the exception.
  2. Unchecked exceptions: Unchecked exceptions are exceptions that are not checked by the Java compiler at compile-time. These exceptions are typically related to programming errors, such as null pointer exceptions or illegal argument exceptions. Examples of unchecked exceptions include NullPointerException, IllegalArgumentException, and ArithmeticException. The program is not required to catch or specify these exceptions, but it's recommended to handle them to prevent the application from crashing.

Q95). Explain the difference between the throw and throws keyword.

In Java, the throw and throws keywords are used to handle exceptions, but they have different purposes and are used in different contexts.

The throw keyword is used to throw an exception explicitly from a method or a block of code. It is used to signal that an exceptional condition has occurred and that the normal flow of control cannot be resumed. The throw keyword is followed by an instance of the exception class that is to be thrown.

For example:

if (age < 18>

   throw new IllegalArgumentException("Age must be 18 or older");

}

The throws keyword is used to declare that a method or a constructor may throw one or more exceptions. When a method or a constructor declares that it throws an exception, it is indicating that the caller of the method or constructor should be prepared to catch and handle the exception. The throws keyword is followed by a list of exception classes that the method or constructor may throw.

For example:

public void readFile(String fileName) throws IOException {

   // code to read file

}

Q96). What is the expression language in JSP?

In JSP (JavaServer Pages), the expression language (EL) is a simple language that is used to access data and perform operations on it. The EL allows a JSP page to access data stored in JavaBeans, request attributes, session attributes, and application-scope attributes. It also allows a JSP page to perform basic operations such as arithmetic, logical, and comparison operations.

The EL expressions are enclosed in ${ } and can be used in various parts of a JSP page, such as in scriptlets, JSP tags, and attributes of JSP tags.

If you face difficulties with these java core interview questions, please comment on your problem in the next section. Apart from this blog, if you want to become a certified Java Developer in 2023 then you should definitely check out this JanBask course.

Q97). Explain the role of DispatcherServlet and ContextLoaderListener.

In Spring MVC, the DispatcherServlet and the ContextLoaderListener are two important components that are responsible for the overall request handling and initialization of the Spring context, respectively.

  1. DispatcherServlet: DispatcherServlet is the front controller of the Spring MVC framework. It acts as a single entry point for all incoming web requests to the application. It is responsible for mapping requests to appropriate controllers, handling the request flow, and returning the appropriate response. The DispatcherServlet is configured in the web.xml file and it maps to specific URL patterns. It is responsible for handling all incoming requests and dispatching them to appropriate controllers for further processing.

  1. ContextLoaderListener: The ContextLoaderListener is an implementation of the ServletContextListener interface that is responsible for initializing the Spring context for the application. It creates an instance of the ApplicationContext, which is the root container for the application's beans. The ContextLoaderListener is also configured in the web.xml file. It's responsible for loading the application context and making it available to all the components of the application. The listener is responsible for loading the root application context as well as any additional contexts that are configured through the contextConfigLocation parameter.

Q98). What are the life-cycle methods for a jsp?

In JSP (JavaServer Pages), the life-cycle of a JSP page consists of the following methods:

  1. jspInit(): The jspInit() method is called when the JSP page is first initialized. It is called before any other method, and it is typically used to initialize resources such as database connections or file handles that will be used throughout the life of the JSP page.
  2. _jspService(): The _jspService() method is called for each request to the JSP page. It is responsible for generating the output for the request. It's called after the jspInit() method, and it's called for each request. It's responsible for generating the response for the client.
  3. jspDestroy(): The jspDestroy() method is called when the JSP page is about to be destroyed. It is called after the last request has been processed, and it is typically used to release resources such as database connections or file handles that were acquired in the jspInit() method.

Q99). Can you explain the Java thread lifecycle?

In Java, a thread has a specific lifecycle that it goes through, from its creation to its termination. The following are the main stages of the thread lifecycle:

  1. New: A thread is in the new state when it has been created but has not yet started. The thread is not considered to be alive until the start() method is called.
  2. Runnable: A thread is in the runnable state when it is able to run, but it may or may not be currently running. The thread is considered to be alive when it is in this state.
  3. Running: A thread is in the running state when it is currently executing its run() method. This is the state in which the thread is actually performing its intended task.
  4. Blocked: A thread is in the blocked state when it is waiting for a resource, such as a lock, to be released. A thread may also be in this state if it is waiting for a certain event to occur.
  5. Dead: A thread is in the dead state when it has completed its execution or when it has been terminated by an uncaught exception. A thread is considered to be dead when it is no longer alive, and it cannot be restarted.

Q100). What is OutOfMemoryError in Java?

In Java, an OutOfMemoryError is a type of error that occurs when the Java Virtual Machine (JVM) is unable to allocate memory for a new object or array. This can happen when the heap space, which is the area of memory where objects are stored, runs out of free memory.

An OutOfMemoryError can occur for several reasons, such as:

  • The heap size is too small: If the heap size is not sufficient for the application's needs, the JVM may run out of memory and throw an OutOfMemoryError.
  • Memory leak: A memory leak is a situation where the application creates objects but never releases them. Over time, this can lead to a buildup of unused objects in the heap, eventually causing the JVM to run out of memory.
  • a Large number of long-lived objects: If the application creates a large number of objects that are long-lived, they may consume a large amount of memory and cause the JVM to run out of memory.
  • Unoptimized code: Unoptimized code, such as code that creates a large number of temporary objects, can also lead to an OutOfMemoryError.

Top 10+ Java Coding Questions and Answers frequently asked in Interviews.

101). Check if a given string is a palindrome using recursion.

public class PalindromeChecker {

    public static boolean isPalindrome(String s) {

        if (s.length() == 0 || s.length() == 1) {

            return true;

        }

        if (s.charAt(0) == s.charAt(s.length() - 1)) {

            return isPalindrome(s.substring(1, s.length() - 1));

        }

        return false;

    }

    public static void main(String[] args) {

        String input = "racecar";

        if(isPalindrome(input))

            System.out.println(input + " is a palindrome.");

        else

            System.out.println(input + " is not a palindrome.");

    }

}

102). Write a Java Program to print Fibonacci Series using Recursion.

public class Fibonacci {

    static int n1=0,n2=1,n3=0;

    static void printFibonacci(int count){

        if(count>0){

            n3 = n1 + n2;

            n1 = n2;

            n2 = n3;

            System.out.print(" "+n3);

            printFibonacci(count-1);

        }

    }

    public static void main(String args[]){

        int count=10;

        System.out.print(n1+" "+n2);

        printFibonacci(count-2);

    }

}

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

public class AnagramChecker {

    public static boolean isAnagram(String s1, String s2) {

        char[] c1 = s1.toCharArray();

        char[] c2 = s2.toCharArray();

        Arrays.sort(c1);

        Arrays.sort(c2);

        return Arrays.equals(c1, c2);

    }

 public static void main(String[] args) {

        String s1 = "listen";

        String s2 = "silent";

        if (isAnagram(s1, s2))

            System.out.println(s1 + " and " + s2 + " are anagrams.");

        else

            System.out.println(s1 + " and " + s2 + " are not anagrams.");

    }

}

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

public class Factorial {

    public static int findFactorial(int number) {

        int factorial = 1;

        for (int i = 1; i <= number; i++) {

            factorial *= i;

        }

        return factorial;

    }

    public static void main(String[] args) {

        int number = 5;

        System.out.println("Factorial of " + number + " is " + findFactorial(number));

    }

}

105). Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

public class MissingNumber {

    public static int findMissingNumber(int[] nums) {

        int expectedSum = nums.length * (nums.length + 1) / 2;

        int actualSum = 0;

        for (int i = 0; i < nums>

            actualSum += nums[i];

        }

        return expectedSum - actualSum;

    }

    public static void main(String[] args) {

        int[] nums = {1, 2, 4, 5, 6};

        System.out.println("The missing number is: " + findMissingNumber(nums));

    }

}

106). Write a Java program to create and throw custom exceptions.

class MyException extends Exception {

    public MyException(String message) {

        super(message);

    }

}

public class CustomExceptionExample {

    public static void validateAge(int age) throws MyException {

        if (age < 18>

            throw new MyException("Age must be greater than 18");

        }

    }

    public static void main(String[] args) {

        try {

            validateAge(16);

        } catch (MyException e) {

            System.out.println(e.getMessage());

        }

    }

}

107). What is the output of the following program?

class Java

{  

    public static void main (String args[])   

    {  

        System.out.println(10 * 50 + "JanBask");   

        System.out.println("JanBask" + 10 * 50);  

    }  

Output:

500JanBask

JanBask500

108). Write a Java program to rotate arrays 90 degrees clockwise by taking matrices from user input.

import java.util.Scanner;

public class MatrixRotation {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number of rows in the matrix: ");

        int rows = sc.nextInt();

        System.out.print("Enter the number of columns in the matrix: ");

        int cols = sc.nextInt();

        int[][] matrix = new int[rows][cols];

        System.out.println("Enter the elements of the matrix:");

        for (int i = 0; i < rows>

            for (int j = 0; j < cols>

                matrix[i][j] = sc.nextInt();

            }

        }

        sc.close();

        System.out.println("Original matrix:");

        for (int i = 0; i < rows>

            for (int j = 0; j < cols>

                System.out.print(matrix[i][j] + " ");

            }

            System.out.println();

        }

        System.out.println("Matrix after 90 degree clockwise rotation:");

        for (int j = 0; j < cols>

            for (int i = rows - 1; i >= 0; i--) {

                System.out.print(matrix[i][j] + " ");

            }

            System.out.println();

        }

    }

}

109). 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.

public class MagicNumber {

    public static boolean isMagicNumber(int number) {

        while (number > 9) {

            int sum = 0;

            while (number > 0) {

                sum += number ;

                number /= 10;

            }

            number = sum;

        }

        return number == 1;

    }

    public static void main(String[] args) {

        int number = 28;

        if (isMagicNumber(number)) {

            System.out.println(number + " is a magic number.");

        } else {

            System.out.println(number + " is not a magic number.");

        }

    }

}

Apart from this blog if you want to become a certified Java Developer in 2023 then you should definitely checkout this JanBask course.

110). Write a Java program to reverse a string.

public class StringReverser {

    public static String reverseString(String input) {

        char[] inputArray = input.toCharArray();

        for (int i = 0; i < inputArray>

            char temp = inputArray[i];

            inputArray[i] = inputArray[inputArray.length - i - 1];

            inputArray[inputArray.length - i - 1] = temp;

        }

        return new String(inputArray);

    }

    public static void main(String[] args) {

        String input = "Hello, World!";

        System.out.println("Original string: " + input);

        System.out.println("Reversed string: " + reverseString(input));

    }

}

111). Write a java program to check if any number given as input is the sum of 2 prime numbers.

public class SumOfPrimes {

    public static boolean isPrime(int number) {

        if (number < 2>

            return false;

        }

        for (int i = 2; i <= Math.sqrt(number); i++) {

            if (number % i == 0) {

                return false;

            }

        }

        return true;

    }

    public static boolean isSumOfTwoPrimes(int number) {

        for (int i = 2; i <= number / 2; i++) {

            if (isPrime(i) && isPrime(number - i)) {

                return true;

            }

        }

        return false;

    }

    public static void main(String[] args) {

        int number = 20;

        if (isSumOfTwoPrimes(number)) {

            System.out.println(number + " is the sum of two prime numbers.");

        } else {

            System.out.println(number + " is not the sum of two prime numbers.");

        }

    }

}

112). Write a Java program for solving the Tower of Hanoi Problem.

public class TowerOfHanoi {

    public static void solveTowerOfHanoi(int n, String from, String to, String aux) {

        if (n == 1) {

            System.out.println("Move disk 1 from " + from + " to " + to);

            return;

        }

        solveTowerOfHanoi(n - 1, from, aux, to);

        System.out.println("Move disk " + n + " from " + from + " to " + to);

        solveTowerOfHanoi(n - 1, aux, to, from);

    }

    public static void main(String[] args) {

        int n = 3;

        solveTowerOfHanoi(n, "A", "C", "B");

    }

}

113). Implement Binary Search in Java using recursion.

public class BinarySearch {

    public static int binarySearch(int[] arr, int start, int end, int target) {

        if (end >= start) {

            int mid = start + (end - start) / 2;

            if (arr[mid] == target) {

                return mid;

            }

            if (arr[mid] > target) {

                return binarySearch(arr, start, mid - 1, target);

            }

            return binarySearch(arr, mid + 1, end, target);

        }

        return -1;

    }

    public static void main(String[] args) {

        int[] arr = {2, 3, 4, 10, 40};

        int target = 10;

        int result = binarySearch(arr, 0, arr.length - 1, target);

        if (result == -1) {

            System.out.println("Element not present");

        } else {

            System.out.println("Element found at index " + result);

        }

    }

}

 

114). How to write multiple catch statements under a single try block?

In Java, it is possible to have multiple catch statements under a single try block to handle different types of exceptions. This is useful when you want to handle different types of exceptions in different ways. Here is an example of how to write multiple catch statements under a single try block:

try {

    // code that might throw an exception

    int a = 1 / 0;

    int[] arr = new int[5];

    arr[10] = 5;

} catch (ArithmeticException e) {

    System.out.println("Arithmetic exception occurred: " + e.getMessage());

} catch (ArrayIndexOutOfBoundsException e) {

    System.out.println("Array index out of bounds exception occurred: " + e.getMessage());

} catch (Exception e) {

    System.out.println("An exception occurred: " + e.getMessage());

}

Check Core Java Interview Questions if you are looking to do a job in core Java. 

Final Thoughts on Java Interview Question and Answer for Freshers & Advanced Professionals!

Java is a very popular programming language that can be found in the technology stack of every company. No matter if you are heading for the Java developer interview or full-stack developer interview, knowing interview questions for a a Java developer fresher & advanced professional is important for you to give your best and get hired in your dream company.

Every above Java interview question for fresher & advanced professionals is asked on repeat, so prepare them and give your best shot in an upcoming interview.

In case you are looking for complete preparation for Java Career, get along and explore our Java Training course online, led by real programmers with real-time industry projects, along with complete resume feedback and impactful preparation of Java interview questions for freshers and experienced.

Let us know in the comments below if you have any queries or questions related to these Java-experienced or Java freshers' interview questions and answers.

FAQ

1. What are the basic Java questions asked in the Interview?

Ans: Following are the basic Java questions:

  1. OOPs concepts: encapsulation, inheritance, polymorphism, and abstraction

  2. Java keywords: static, final, abstract, synchronized, volatile, etc.

  3. Java Collection Framework: List, Set, Map, etc.

  4. Exception handling: try-catch, throws, finally

  5. Multithreading and Concurrency

  6. Garbage Collection

  7. I/O operations and Serialization

  8. JDBC and database connectivity

  9. JUnit and test-driven development

  10. Familiarity with frameworks such as Spring, Hibernate, etc.

2. How to prepare for a Java Interview?

Following are the topics you should prepare:

  1. Review core Java concepts: Brush up on basic concepts such as OOPs, data structures, algorithms, and design patterns. Make sure you have a good understanding of the Java language, including keywords, operators, and control structures.
  2. Practice coding: Try to solve as many coding problems as you can, using websites such as LeetCode and HackerRank. This will help you to improve your problem-solving skills and get familiar with common coding patterns used in Java.
  3. Understand the framework: Familiarize yourself with popular Java frameworks like Spring, Hibernate, and Struts. Understand how they work and how to use them effectively.
  4. Get familiar with build tools and version control systems: Understand how to use Maven and Gradle for building and managing Java projects, and how to use Git for version control.
  5. Review Java 8 features: Understand how to use new features such as Lambda expressions and Stream API in Java 8.
  6. Understand Microservices, RESTful web services, and API development, if you are applying for a role that involves these.

The best way to prepare yourself and become a successful Java Developer then your JanBask course is through the best course.

3. What are the Java interview questions for 2 years of experience?

Following are the questions for 2 years of experience:

  1. Can you explain the difference between an interface and an abstract class?

  2. How do you implement thread safety in Java?

  3. Can you explain the difference between a HashMap and a Hashtable?

  4. How do you handle exceptions in your code?

  5. How do you ensure that a class is thread-safe?

  6. Can you explain the difference between a static and non-static inner class in Java?

  7. How do you implement a linked list in Java?

  8. Can you explain the difference between a shallow copy and a deep copy?

  9. How do you handle concurrency issues with the Singleton pattern?

  10. Can you explain the process of Garbage Collection in Java?


     user

    Jyotika Prasad

    Through market research and a deep understanding of products and services, Jyotika has been translating complex product information into simple, polished, and engaging content for Janbask Training.


Comments

  • P

    Paul Wilson

    Well explained answers, short but exact descriptions.

     Reply
  • E

    Emilio Davis

    Do you have a similar guide based on a simple self introduction question?

     Reply
  • Z

    Zane Brown

    Thanks for boosting our confidence by providing such a helpful post.

     Reply
  • K

    Kaden Brown

    A few important questions are missed. But still a good job !

     Reply
  • A

    Amelia MILLER

    Must read, really helpful for freshers.

     Reply
    • logo16

      JanbaskTraining

      Glad you found this useful! For more such insights on your favourite topics, do check out JanBask Training Blogs and keep learning with us!

  • A

    Aidan Johnson

    After going through this article, I felt I missed some good questions but thanks to your question booklet, now I have covered all the answers.

     Reply
    • logo16

      JanbaskTraining

      Hello, JanBask Training offers online training to nurture your skills and make you ready for an amazing career run. Please write to us in detail at [email protected]. Thanks

  • A

    Adonis Smith

    Thanks for this question booklet, do you have any guide for resume preparation for the same job.

     Reply
    • logo16

      JanbaskTraining

      Hello, JanBask Training offers online training to nurture your skills and make you ready for an amazing career run. Please write to us in detail at [email protected]. Thanks!

  • Z

    Zane Brown

    What is the cost of Java training at your institute?

     Reply
    • logo16

      JanbaskTraining

      Glad you found this useful! For more such insights on your favourite topics, do check out JanBask Training Blogs and keep learning with us!

  • A

    Aidan

    Can I get some relevant sample questions links to prepare well for my interview? Please revert!

     Reply
    • logo16

      JanbaskTraining

      Glad you found this useful! For more such insights on your favourite topics, do check out JanBask Training Blogs and keep learning with us!

  • A

    Adonis Smith

    Hi Team! Nice blog, the answers of the questions are really simple and easy to understand. Thank you!

     Reply
    • logo16

      JanbaskTraining

      Thank you so much for your comment, we appreciate your time. Keep coming back for more such informative insights. Cheers :)

  • M

    markyjones

    Wow, this is a great collection of questions and answers! I really like going through each question and answer and learning something new at every step. Thank you so much for sharing!

     Reply
    • logo16

      JanbaskTraining

      You are most welcome, often visit our site to read such amazing posts.

  • Z

    Zane

    This is an awesome list of questions and answers for fresher and advanced professionals to prepare for a Java interview! I found this post really interesting and helpful to prepare for my upcoming interview.

     Reply
    • logo16

      JanbaskTraining

      Thanks for your valuable comment. All the very best for your interview.

  • H

    Henry

    Hey, thanks for this amazing collection of questions and answers. I could explore a lot about Java. Keep writing and sharing this kind of post in the future as well.

     Reply
    • logo16

      JanbaskTraining

      Thanks for your comment. We will surely try to come up with more such posts.

  • R

    Rocky

    I was looking for comprehensive guidance on Java Interview Preparation. Finally, I got it. It seems very nice. Kudos and thanks!

     Reply
  • P

    Paxton Harris

    This is going to help a lot to those preparing for Java Interview. It hardly took me 10 minutes to go through the whole article. This is an informative and interesting post. Thanks a lot for sharing!!

     Reply
    • logo16

      JanbaskTraining

      Thank you too! We are really glad to know that you found this post helpful and interesting.

  • N

    Nash Martin

    Wow! Such an interesting and interactive post with a lot of helpful information, a very informative and valuable blog.

     Reply
    • logo16

      JanbaskTraining

      Glad to hear such a positive comment from you. Thank you!

  • C

    Caden Thomas

    This post is quite impressive, I must. say I generally follow your every post to expand my knowledge in different domains. Looking forward to your next post.

     Reply
    • logo16

      JanbaskTraining

      Thank you so much for your valuable comment, visit our site to read more interesting content.

  • M

    Mia

    Great post with so many important interview questions and answers. Going to help a lot. You stated all of the key facts when looking to prepare for a Java Interview.

     Reply
    • logo16

      JanbaskTraining

      Glad to know that you found this post interesting. Keep visiting our site to read more such posts.

  • B

    Beckham Allen

    You have successfully covered up all the Java interview questions and answers which I was searching for. Keep writing and sharing informative posts like this which can help us to expand our knowledge.

     Reply
    • logo16

      JanbaskTraining

      Thank you for your positive comment, we will surely bring such more posts.

  • M

    Maximiliano Jackson

    Hi, Thanks for this amazing post. I was looking for help to prepare for the upcoming Java interview, and I must say here I learned a lot more.

     Reply
    • logo16

      JanbaskTraining

      Glad to know that this post could help you. Often visit our site to read such more posts.

Related Courses

Trending Courses

salesforce

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53
salesforce

Upcoming Class

-1 day 29 Sep 2023

salesforce

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
salesforce

Upcoming Class

6 days 06 Oct 2023

salesforce

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
salesforce

Upcoming Class

-1 day 29 Sep 2023

salesforce

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
salesforce

Upcoming Class

-1 day 29 Sep 2023

salesforce

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
salesforce

Upcoming Class

0 day 30 Sep 2023

salesforce

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
salesforce

Upcoming Class

-1 day 29 Sep 2023

salesforce

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
salesforce

Upcoming Class

-1 day 29 Sep 2023

salesforce

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
salesforce

Upcoming Class

6 days 06 Oct 2023

salesforce

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
salesforce

Upcoming Class

-1 day 29 Sep 2023

salesforce

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
salesforce

Upcoming Class

-1 day 29 Sep 2023

salesforce

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
salesforce

Upcoming Class

34 days 03 Nov 2023

salesforce

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
salesforce

Upcoming Class

-1 day 29 Sep 2023

Interviews