16
Jun
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:
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.
Let's begin with the first set of basic core Java technical interview questions, which are primarily relevant for freshers.
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!");
}
}
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.
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.
Java is a general-purpose, object-oriented programming language that is known for its features such as:
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.
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);
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.
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.
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.
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.
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.
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.
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.
Packages in Java provide several advantages, including
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:
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:
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:
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
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:
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
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:
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:
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.
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:
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.
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:
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.
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:
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.
Java String Pool, also known as String Intern Pool, is a storage area in Java heap where string literals are stored.
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.
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.
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:
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.
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.
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
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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:
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.
Here are the general steps to connect to a database in Java using JDBC:
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.
Java development team hit to make Java as
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.
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.
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:
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.
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.
The memory allocations are available in three parts, namely Code, Stack, Heap, and Static.
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:
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.
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.
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.
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.
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.
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.
Here is the list of major benefits of using Hibernate Framework:
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?
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.
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.
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.
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:
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:
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:
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.
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.
1. What are the basic Java questions asked in the Interview?
Ans: Following are the basic Java questions:
OOPs concepts: encapsulation, inheritance, polymorphism, and abstraction
Java keywords: static, final, abstract, synchronized, volatile, etc.
Java Collection Framework: List, Set, Map, etc.
Exception handling: try-catch, throws, finally
Multithreading and Concurrency
Garbage Collection
I/O operations and Serialization
JDBC and database connectivity
JUnit and test-driven development
Familiarity with frameworks such as Spring, Hibernate, etc.
2. How to prepare for a Java Interview?
Following are the topics you should prepare:
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:
Can you explain the difference between an interface and an abstract class?
How do you implement thread safety in Java?
Can you explain the difference between a HashMap and a Hashtable?
How do you handle exceptions in your code?
How do you ensure that a class is thread-safe?
Can you explain the difference between a static and non-static inner class in Java?
How do you implement a linked list in Java?
Can you explain the difference between a shallow copy and a deep copy?
How do you handle concurrency issues with the Singleton pattern?
Can you explain the process of Garbage Collection in Java?
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.
AWS
DevOps
Data Science
Hadoop
Salesforce
QA
Business Analyst
MS SQL Server
Python
Artificial Intelligence
Machine Learning
Tableau
Interviews
Paul Wilson
Well explained answers, short but exact descriptions.
Emilio Davis
Do you have a similar guide based on a simple self introduction question?
Zane Brown
Thanks for boosting our confidence by providing such a helpful post.
Kaden Brown
A few important questions are missed. But still a good job !
Amelia MILLER
Must read, really helpful for freshers.
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!
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.
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
Adonis Smith
Thanks for this question booklet, do you have any guide for resume preparation for the same job.
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!
Zane Brown
What is the cost of Java training at your institute?
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!
Aidan
Can I get some relevant sample questions links to prepare well for my interview? Please revert!
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!
Adonis Smith
Hi Team! Nice blog, the answers of the questions are really simple and easy to understand. Thank you!
JanbaskTraining
Thank you so much for your comment, we appreciate your time. Keep coming back for more such informative insights. Cheers :)
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!
JanbaskTraining
You are most welcome, often visit our site to read such amazing posts.
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.
JanbaskTraining
Thanks for your valuable comment. All the very best for your interview.
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.
JanbaskTraining
Thanks for your comment. We will surely try to come up with more such posts.
Rocky
I was looking for comprehensive guidance on Java Interview Preparation. Finally, I got it. It seems very nice. Kudos and thanks!
JanbaskTraining
Thank you too for your valuable comment.
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!!
JanbaskTraining
Thank you too! We are really glad to know that you found this post helpful and interesting.
Nash Martin
Wow! Such an interesting and interactive post with a lot of helpful information, a very informative and valuable blog.
JanbaskTraining
Glad to hear such a positive comment from you. Thank you!
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.
JanbaskTraining
Thank you so much for your valuable comment, visit our site to read more interesting content.
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.
JanbaskTraining
Glad to know that you found this post interesting. Keep visiting our site to read more such posts.
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.
JanbaskTraining
Thank you for your positive comment, we will surely bring such more posts.
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.
JanbaskTraining
Glad to know that this post could help you. Often visit our site to read such more posts.