Most Frequently Asked Java Interview Questions
- What is Java, and how is it platform-independent?
- What is JDK, JRE and JVM in Java?
- What are Instance, Local, and Class Variables in Java?
- Is Java a pure object-oriented programming language?
- Explain the memory areas of JVM in Java?
- What is a JIT compiler?
- What is the difference between Java and C++?
- Why Java doesn’t support pointers like C++?
- Explain the data types of Java.
- What is the default value of byte, float, double, and char data type in Java?
Basic Java Interview Questions for Freshers
1. What is Java, and how is it platform-independent?
Java is a high-level, object-oriented, multi-threaded and scalable programming language developed by James Gosling.
It is platform independent because java has the ability to run the same code on any operating system without modification. It compiles the java code (.java files) into an intermediate form called bytecode(.class file). The bytecode is not specific to any hardware or OS, it can run on any machine.
The bytecode is then processed by a component called JVM, which translates the bytecode into machine specific instructions at run time. JVM has to be installed separately for different OS(Mac, Linux and Windows).
2. What is JDK, JRE and JVM in Java?
JDK |
JRE |
JVM |
- It includes the full suite of tools required for developing Java applications.
- Includes JRE, JVM, java compiler, java debugger and javadoc.
|
- It is a software layer that provides the necessary environment to run java programs.
- It consists of the JVM, java libraries like .util and .lang, and runtime tools like java collector.
|
- JVM converts Java Code into Bytecode.
- It is platform dependent i.e it has different version of Mac, Linux and Windows.
|
3. What are Instance, Local, and Class Variables in Java?
Instance variables are declared inside the class but outside the methods. So basically these are accessible by all the methods of that class. The default value for numeric types is 0, for boolean false and null for object references.
Example:
class Sample {
// Instance Variables
public String s1;
public int m1;
// main method
public static void main(String[] args) {
// Creating an instance of the Sample class
Sample obj = new Sample();
// Initializing instance variables
obj.s1 = "Intellipaat";
obj.m1 = 100;
// Displaying the values of instance variables
System.out.println("The value of s1 is: " + obj.s1);
System.out.println("The value of m1 is: " + obj.m1);
// Modifying instance variables
obj.s1 = "Updated Intellipaat";
obj.m1 = 200;
// Displaying updated values
System.out.println("The updated value of s1 is: " + obj.s1);
System.out.println("The updated value of m1 is: " + obj.m1);
}
}
Output:
The value of s1 is: Intellipaat
The value of m1 is: 100
The updated value of s1 is: Updated Intellipaat
The updated value of m1 is: 200
Local variables’s scope is limited to the function, constructor, or block of code, so no other function can access those variables. These variables don’t have any default value.
Example:
class Sample {
// main method
public static void main(String[] args) {
// local variable
int m1 = 50;
// Displaying the value of the local variable
System.out.println("The value of m1 is: " + m1);
// Perform some operations on m1
m1 = m1 + 25; // Add 25 to m1
System.out.println("The updated value of m1 is: " + m1);
// Further operation
m1 = m1 * 2; // Multiply m1 by 2
System.out.println("The value of m1 after multiplying by 2 is: " + m1);
}
}
Output:
The value of m1 is: 50
The updated value of m1 is: 75
The value of m1 after multiplying by 2 is: 150
Class variables are also known as static variables in Java, defined in a class using static keywords. These variables are stored in static memory and can be called in a program using the class name. The default values are the same as the instance variables.
Example:
class Sample {
// Static or class variable
public static String s1 = "Intellipaat";
public static void main(String[] args) {
// Accessing and printing the static variable
System.out.println("The value of s1 is: " + s1);
// You can also modify the static variable if needed
s1 = "Updated Intellipaat";
System.out.println("The updated value of s1 is: " + s1);
}
}
Output:
The value of s1 is: Intellipaat
The updated value of s1 is: Updated Intellipaat
The main difference between Instance variables and Class Variables is that the instance variables belong to only a specified class in which they are declared. While the class variables belong to classes and subclasses.
4. Is Java a pure object-oriented programming language?
No, Java is not a pure object-oriented programming language because it provides primitive data types like char, boolean, int, short, long, double etc. and also supports the concepts of static methods and variables, which can be directly accessed with class name. So there is no need of an objects toaccess some specific entity Java that’s why Java is not a pure object-oriented programming language.
5. Explain the memory areas of JVM in Java?
- Class Memory Area – This is also known as the method area that stores the class-level data such as method data, variable code, runtime constant pool, constructor, etc.
- Heap Memory Area – It is used to assign the memory to objects. So basically, it is responsible for object creation and storage. After java, static methods and variables are stored in the Heap area, not the Class Area.
- Stack Area – A JVM stack area is used to store the partial data or partial results. Programs generally use this data for dynamic linking and returning value for the method.
- Program Counter Register Area – This is used to store the address of the following JVM instructions that need to be executed further.
- Native Method Stack – It is used to store the native methods and get allocated to a created thread that might be dynamic. These native methods are not written in Java programming language and never compiled to bytecode.
6. What is a JIT compiler?
JIT stands for Just-In-Time compiler in Java. It is a part of JVM that converts the bytecode into machine code for better performance of Java applications during execution.
As you know, that bytecode takes more time to execute than the machine code. So when JVM executes the bytecode it maintains a record of a function execution. In simpler terms, you can consider a Java application with so many functions, and it might be possible that some functions are repetitively used in a large Java application. If JVM executes the bytecode every time, it will create a worse effect on performance. So here, our hero JIT compiler takes an entry. It converts that bytecode into machine code that can be directly executed by hardware rather than interpreting that bytecode line by line.
So basically, JVM gives a signal for the entry of the JIT compiler, and JIT converts that red flag bytecode (provided by JVM) into machine code for better performance.
7. What is the difference between Java and C++?
- Memory Management – C++ provides more control over memory allocation and deallocation using pointers concepts. But Java doesn’t give the idea of pointers.
- Platform – Java is platform-independent, supporting the Write Once and Run Anywhere concept. While C++ is platform-dependent.
- Compiled/Interpreted – Java is compiled and interpreted while C++ is only compiled language.
- Multiple Inheritance – C++ supports various inheritance while Java language does not support this due to ambiguity problems.
- Root Hierarchy – Java programming language has a single root hierarchy due to Java. Lang. object class but C++ is not a single root hierarchy language.
8. Why Java doesn’t support pointers like C++?
Java doesn’t support the pointers concept due to safety, performance and multiple complication issues. As you know, you can directly access the memory address using the pointers in C++.
Comparing Java to C++ in terms of object-oriented programming, then Java wins here and obviously, pointers generally breach the abstraction concept of the programming language at a developer level. So to boost the performance and overall abstraction, Java provides the garbage collection and reference features which are automated.
9. Explain the data types of Java.
In Java, we have 2 types of data types i.e.
- Primitive or Pre-Defined Data Types
- Non-Primitive or Object Data Types
Primitive Data Types – Numeric data like integers and floating points are considered as primitive data types.
Example – byte, short, int, long, float, double, boolean, and char.
Non-Primitive or Object Data Types – These are generally reference types as they store the address of the variable’s values, not the variable’s value.
Example – String, Array, Objects, etc.
10. What is the default value of byte, float, double, and char data type in Java?
Here are the default value of the data types:
- Byte: 0
- Float: 0.0f
- Double: 0.0d
- Char: ‘\u0000’
11. What is the difference between Java, Python, and C++?
Here’s a comparison table highlighting the key differences between Java, Python, and C++:
Java |
Python |
C++ |
Verbose, requires semicolons |
Concise, indentation-based |
Complex requires semicolons |
Statically typed |
Dynamically typed |
Statically typed |
Moderate, managed by JVM |
Generally slower than Java |
High performance, compiled code |
Automatic garbage collection |
Automatic garbage collection |
Manual memory management |
Rich standard libraries |
Extensive libraries (e.g., NumPy, pandas) |
Standard Template Library (STL) |
Built-in support with threads |
GIL limits thread performance |
Powerful threading capabilities |
Large, strong enterprise focus |
Rapidly growing, diverse |
Established, strong in systems |
12. Explain the difference between StringBuffer and StringBuilder in Java programming.
StringBuffer |
StringBuilder |
StringBuffer methods are synchronized. |
StringBuilder is non-synchronized. |
StringBuffer is thread-safe. |
StringBuilder is not thread-safe. |
The performance is very slow. |
The performance is very fast. |
13. Define inheritance.
Inheritance is an object-oriented programming concept that allows one class to inherit the properties and methods from another class. Inheritance promotes the reusability of the code and establishes the hierarchy between the classes. The class from where we are deriving or inheriting the properties or methods is called a superclass and the class from where we are deriving is known as a subclass.
For instance, we have a class named car that includes attributes like number of tiers, mileage, and so on. Let’s now consider another class, car, which will also possess all of the vehicle’s properties. In this case, the car is a subclass that inherits the parent class’s properties, while the vehicle is a superclass.
14. Explain method overloading.
When a Java program contains more than one method with the same name but with different properties, then it is called method overloading.
Example
class Display {
// Method to display an integer
void show(int a) {
System.out.println("Integer: " + a);
}
// Method to display a string
void show(String b) {
System.out.println("String: " + b);
}
public static void main(String[] args) {
Display display = new Display();
// Calling overloaded methods
display.show(10); // Calls show(int a)
display.show("Intellipaat"); // Calls show(String b)
}
}
Here when we call the function based on the argument passed, the method will be called, so if we pass 10, it will call the method that prints integer, and if we pass a string, it will call a method that prints a string.
Watch this Java Interview Questions video:
15. Compare overloading with overriding.
Overloading refers to the case of having two methods of the same name but different properties; whereas, overriding occurs when there are two methods of the same name and properties, but one is in the child class and the other is in the parent class.
16. Explain the creation of a thread-safe singleton in Java using double-checked locking.
Singleton is created with the double-checked locking as before Java 5 acts as a broker and it’s been possible to have multiple instances of singleton when multiple threads create an instance of the singleton at the same time. Java 5 made it easy to create thread-safe singleton using Enum. Using a volatile variable is necessary for the same.
17. Differentiate between an ArrayList and a Vector.
ArrayList |
Vector |
An ArrayList is not synchronized. |
A vector is synchronized. |
An ArrayList is fast. |
A vector is slow as it is thread-safe. |
If an element is inserted into an ArrayList, it increases its array size by 50 percent. |
A vector defaults to doubling the size of its array. |
An ArrayList does not define the increment size. |
A vector defines the increment size. |
An ArrayList uses an Iterator for traversing. |
Except for the hashtable, a vector is the only other class using Enumeration and Iterator. |
18. Mention the difference between Iterator and Enumeration.
Iterator |
Enumeration |
Iterator is an interface found in the java.util package. |
Enumeration is a special data type that allows you to define a fixed set of constants. |
Uses three methods to interface:
- hasNext()
- next()
- remove()
|
Uses two methods:
- hasMoreElements()
- nextElement()
|
Iterator method names have been improved. |
The traversing of elements can only be done once per creation. |
19. Explain the difference between the inner class and the subclass.
Inner Class |
Subclass |
An inner class is a class that is defined within another class. |
A subclass is a class that inherits properties from another class called the superclass. |
It provides access rights for the class, which is nesting it, which can access all variables and methods defined in the outer class. |
It provides access to all public and protected methods and fields of its superclass. |
20. Can we execute any code, even before the main method? Explain.
Yes, we can execute any code, even before the main method. We can use a static block of code in the class when creating the objects at the load time of the class. Any statements within this static block of code will get executed at once while loading the class, even before the creation of objects in the main method.
Example
class Intellipaat {
// Static block
static {
System.out.println("Static block executed!");
}
public static void main(String[] args) {
System.out.println("Main method executed!");
}
}
Output
Static block executed!
Main method executed!
A static block runs when the class is loaded before any objects are created or the main method is invoked.
21. How can we restrict inheritance for a class?
We can restrict the class from getting inherited by using the following way:
- By using the final keyword
- If we make all methods final, then we cannot override it.
- By using private constructors
22. Java doesn’t support multiple inheritance. Why?
Java doesn’t support multiple inheritance because we cannot use different methods in one class; it creates ambiguity.
Example:
interface Intellipaat1 {
default void test() {
System.out.println("test() method from Intellipaat1");
}
}
interface Intellipaat2 {
default void test() {
System.out.println("test() method from Intellipaat2");
}
}
// Implementing multiple interfaces
class C implements Intellipaat1, Intellipaat2 {
// Resolving ambiguity
@Override
public void test() {
Intellipaat1.super.test(); // Call test from Intellipaat1
Intellipaat2.super.test(); // Call test from Intellipaat2
System.out.println("test() method from class C");
}
}
class Main {
public static void main(String[] args) {
C obj = new C();
obj.test();
}
}
Output:
test() method from Intellipaat1
test() method from Intellipaat2
test() method from class C
Intellipaat1 and Intellipaat2 test() methods are inheriting to class C. So, which test() method class C will take?
As Intellipaat1 and Intellipaat2 class test () methods are different, here we would face ambiguity.
23. Are constructors inherited? Can a subclass call the parent’s class constructor?
We cannot inherit a constructor in Java, However, a subclass can call the parent constructor using the super keyword. We do this to initialise inherited fields in the parents class by creating an instance of a subclass. By calling the parent constructor, we ensure that the parent class is initialised correctly.
24. Define JSON.
JSON stands for ‘JavaScript Object Notation.’ It is a much lighter and more readable alternative to XML. It is independent and primarily used for client-server and server-server communication.
25. What are the advantages of JSON over XML?
The advantages of JSON over XML are:
- JSON is lighter and faster than XML.
- It is easy to understand.
- It is easy to parse and convert to objects.
- JSON supports multiple data types—string, number, array, or Boolean—but XML only accepts strings.
26. Outline the major Java features.
The significant features of Java programming language are:
- Platform Independent: Java provides a “write once run anywhere” feature. This means you can write Java code once and can use the same code in any operating system. This is possible because the Javacode is converted to bytecode, which can be run on any system which has JDK installed.
- Object Oriented: Java follows the concept of object-oriented programming, which allows us to reuse the code through principles like inheritance. Encapsulation and polymorphism.
- Automatic Memory Management: Java offers built-in garbage collection, which helps you manage the memory efficiently by preventing memory leaks.
- Multithreading: Java supports multithreading, allowing concurrent execution of multiple threads.
- Security: Java provides a secure environment with features like the Java security manager.
Get 100% Hike!
Master Most in Demand Skills Now!
27. What do you mean by an object?
An object consists of methods and classes that depict its state and perform operations. Objects are the instances of a class that are created to use the attributes and methods of a parent class.
28. What is a Classloader?
It is a part of the Java Runtime Environment which is used to dynamically load the class files into the Java Virtual Machine(JVM). The classloader triggers whenever a Java file is executed.
There are three types of classloaders in Java:
- Bootstrap Classloader: The bootstrap loader is the superclass of extension classloader, which loads the standard JDK files from rt.jar and other core classes. The rt.jar file contains all the package classes of java.net, java.lang, java.util, java.io, java.sql, etc.
- Extension Classloader: The extension classloader is known as the parent of the System classloaders and the child of the Bootstrap classloader. It only loads the files available in the extension classpath, which includes ‘dirs/JRE/lib/ext directory. If the file is unavailable in the mentioned directory, the extension classloader will delegate it to the System classloader.
- System/Application Classloader: It loads the classes of application type available in the environment variable such as -classpath, or -cp command-line option. The application classloader generates a ClassNotFoundException if the class is unavailable in the application classpath.
29. How does the == operator function in Java?
Java uses the == operator to compare the reference equality of two objects, which means that it determines if the two objects refer to the same memory location or not.
30. What is polymorphism in Java?
Polymorphism refers to the ability of objects of different classes to be regarded as objects of a common superclass when writing object-oriented programs. This makes it possible for methods from different classes to be applied through one general interface, resulting in flexibility and reuse.
31. What is the purpose of static in Java? Mention an example.
The static keyword in Java is intended to indicate that a certain variable or method belongs to the class and not its instances. For this reason, even without instantiating an object of the class, such a variable or method can be accessed.
class MathUtils {
public static int add(int a, int b) {
return a + b;
}
public static double square(double num) {
return num * num;
}
public static void main(String[] args){
System.out.println(""+square(2));
}
}
Output: 4.0
32. What is exception handling in Java?
Exception handling is a way of dealing with runtime errors or unusual situations that may occur during execution in the Java programming language. It involves trapping exceptions with try-catch blocks and managing them gracefully so that no program termination happens or unexpected behaviour occurs.
33. What is a try-catch in Java?
A try-catch block in Java is used to implement exceptional handling. The code that may throw exceptions has to be written inside the try block, and if any exception occurs, catch it and work on it in the corresponding catch block.
34. Differentiate between checked and unchecked.
The compiler checks checked exceptions at compile time, meaning that programmers have to handle such exceptions with try-catch blocks or declare them using the method signature. Unlike checked exceptions, unchecked exceptions are not checked at compile-time, hence they do not require explicit handling by a programmer.
35. What is the meaning of ‘final’ in Java? Give example
Java uses the final keyword to declare constants, prevent method overriding, and create immutable classes. For example, final int MAX_SIZE = 100; declares a constant MAX_SIZE whose value is 100.
36. Is multithreading part of Java?
Yes, multithreading is part of Java. It provides built-in support for creating and managing threads, thereby enabling multiple tasks to be executed concurrently within one program.
37. What is the purpose of the ‘super’ keyword in Java?
Super is used in the Java programming language to refer to the superclass of an object being manipulated. It can also be used as a bridge between superclass methods/constructors and subclass methods/constructors. For instance, super.methodName() invokes the method defined by the superclass.
38. What is an abstraction in Java? Give an example.
Java Abstraction refers to encapsulating only the function ability and behavior of methods while not exposing their implementation details to the user. The object design used here focuses on what an object does rather than on how it performs that function. For instance, the List interface in Java is an example of abstraction because it describes general operations for lists without defining how they are implemented by specific list classes such as LinkedList and ArrayList.
Java Developer Interview Questions for Experienced
39. Is an empty .java file name a valid source file name in java?
Yes, we can save a java file with an empty .java file name. You can compile it in the command prompt by ‘javac .java’ and run it by typing ‘java classname’. Here is an example of such a program:
import java.util.*;
class A
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Output: Hello World
Once the code has been saved, you need to launch the command prompt and navigate to the file’s directory. After that, you need to write “javac .java” to compile the program and “java A” to execute it.
40. What is the difference between Object-oriented and object-based programming language?
Following are the key differences between the object-oriented and object-based programming languages:
Object-oriented programming language |
Object-based programming language |
Object-oriented programming languages support all the features of OOPS, including polymorphism and inheritance |
Object-based programming language does not support inheritance or polymorphism |
Doesn’t support built-in objects |
Support built-in objects like JavaScript has the window object |
Example: C#, C++, Java, Python, etc. |
JavaScript and Visual Basic are examples of object-based programming language |
41. Why is the main method static in Java?
The main method is static in Java because to call the static methods, there is no need for the object. The Java Virtual Machine(JVM) has to create an object to call the non-static main() method, which will result in extra memory allocation to avoid that we craete a main method with static keyword.
42. Can we declare the static variables and methods in an abstract class?
Yes, we can declare the static variables and methods in an abstract class by inheriting the abstract class. In java, the static variables and methods can be accessed without creating an object. You can simply extend the abstract class and use the static context as mentioned below:
// Parent class A
class A {
static int x = 110; // Static variable
// Static method
static void method1() {
System.out.println("Class A static function called");
}
}
// Child class prog1 inheriting from A
class prog1 extends A {
public static void main(String[] args) {
// Accessing the static method and variable of class A
A.method1();
System.out.println("Value of x = " + A.x);
}
}
The output of the above program will be:
Class A static function called
Value of x=110
43. What is Aggregation?
Aggregation in Java represents a relationship where one class contains the reference of another class. In other words, it refers to a one-way relationship between two classes where the aggregate class has the instance of another class it owns.
For example, in the program below the aggregate class student have a one-way relationship with the class Address. Here each student having an address makes sense, but address having the student doesn’t make any sense. So, instead of inheritance, the aggregation is based on the usage of the classes.
import java.util.*;
class Address
{
String street, city, state, country;
public Address(String street, String city, String state, String country)
{
this.street=street;
this.city=city;
this.state=state;
this.country=country;
}
}
class student
{
int reg_no;
String name;
Address address;
public student(int id,String name,Address address)
{
this.reg_no=id;
this.name=name;
this.address=address;
}
public void display()
{
System.out.println("Student details: ");
System.out.println("Name: "+name);
System.out.println("Reg_no: "+reg_no);
System.out.println("Address: "+address.street+", "+address.city+", "+address.state+", "+address.country);
}
public static void main(String args[])
{
Address address1=new Address("Paper Mill Road","SRE","UP","India");
Address address2=new Address("Service Road","BNG","KA","India");
student ob1=new student(111,"Sam",address1);
student ob2=new student(112,"Alex",address2);
ob1.display();
ob2.display();
}
}
The output of the above program will be:
Student details:
Name: Sam
Reg_no: 111
Address: Paper Mill Road, SRE, UP, India
Student details:
Name: Alex
Reg_no: 112
Address: Service Road, BNG, KA, India
44. What is composition?
Composition refers to a relationship between two objects. If an object contains another object and the contained object can’t exist without the existence of that particular object, then it’s known as the composition.
In simple words, the composition is a kind of aggregation used to describe the reference between two classes using the reference variable.
For example, a class student contains another class named address. So, if the class address cannot exist without the class student, then there exists a composition between them.
45. Can we overload the main method in Java?
Yes, you can overload the main() method in Java using the concept of method overloading.
Below is an example of main() method overloading:
import java.util.*;
class main_overloading
{
public static void main(String args)
{
System.out.println("Main with String");
}
public static void main(String args[])
{
System.out.println("Main with the String args[]");
}
public static void main()
{
System.out.println("main without String");
}
}
The output of the above code will be:
Main with the String args[]
This happens because the JVM only reconize the main method with (String args[]). If you need to call other overloaded main methods you have to call them explicitly.
Here the code if you want to do so,
import java.util.*;
class MainOverloading {
public static void main(String[] args) {
System.out.println("Main with the String args[]");
// Explicitly calling other overloaded main methods
main("Single String");
main();
}
public static void main(String args) {
System.out.println("Main with String");
}
public static void main() {
System.out.println("Main without String");
}
}
Output :
Main with the String args[]
Main with String
Main without String
46. Explain public static void main(String argos[]) in Java?
The main() method is the entry point for any java program. In the expression public static void main(String argos[]), each keyword has significance as mentioned below:
- Public: It’s an access specifier which is used to specify the accessibility of a method in java. Here, Public means anyone can access the method or the class.
- static: the static keyword in java identifies the main method as class-based, which means it can be accessed without creating an object/instance. Static methods can b3e directly called by the Java Virtual Machine(JVM), which in turn saves extra memory allocation.
- void: void is a return type in java, which means the main method will not return any value back.
- String args[]: String argos[] or String[] args is an array of String objects which stores the command line arguments. Here the argument is of array type.. Therefore, it’s passed as the parameter in the main() method.
47. What is the NullPointerException?
The NullPointerException occurs when the user attempts to access or modify the fields of a null object. A null object is an instance defined with null values or without any reference.
48. What is the difference between a constructor and a destructor?
Below is the difference between a constructor and a destructor based on various parameters:
Base of Comparison |
Constructor |
Destructor |
Purpose |
A constructor is used to allocate the memory. |
A destructor is used to deallocate or free up the memory. |
Arguments |
Mayor may not accept the arguments. |
Destructors don’t accept any arguments. |
Declaration |
class_name(arguments){
} |
~class_name(){
}; |
Calling |
The constructor is called as soon as the object is created. |
Called at the time of program termination or when the block is exited. |
Order of execution |
Constructors are executed in successive order, meaning from parent to child class. |
Destructors are called in the reverse order, meaning from child to parent class. |
Overloading |
Can be overloaded. |
Cannot be overloaded. |
49. Can a Java interface have static methods?
Yes, a Java interface can have static methods, but we cannot override them as they’re static. So, we have to define the static methods in the interface and only perform the calling party in the class.
Below is an example of a static method in the
Java interface:
import java.util.*;
interface A
{
static void staticmethod()
{
System.out.println("Static method of interface A called");
}
default void display()
{
System.out.println("Default function of interface A called");
}
}
Output :
spoj: The program compiled successfully, but main class was not found.
Main class should contain
The above interface has a static method and a default method that can be executed without affecting the class that implements it. However, there is no use in creating the static methods in the Java interface as we cannot override the function by redefining it in the main() method.
import java.util.*;
// Interface A with a static and a default method
public interface A {
// Static method in the interface
static void staticMethod() {
System.out.println("Static method of interface A called");
}
// Default method in the interface
default void display() {
System.out.println("Default function of interface A called");
}
}
// Class B implementing the interface A
class B implements A {
// No need to override static methods; they belong to the interface
// Default methods can be optionally overridden
@Override
public void display() {
System.out.println("Default function overridden in class B");
}
}
// Main class
class Main {
public static void main(String[] args) {
// Calling the static method of interface A
A.staticMethod();
// Creating an object of class B
B obj = new B();
// Calling the overridden default method
obj.display();
}
}
So, the output of the above program would be:
Static method of interface A called
Default function of interface A called
50. Differentiate between ‘==’ and equals()?
The main difference between ‘==’ and equals() is that ‘==’ is an operator, while equal() is a method in java. The == operator is used for reference or addresses comparison, meaning it checks if both the objects or variables are pointing to the same memory location.
Whereas, equals() method compares the content of two objects or variables. It checks if the value of two objects aresame or not.
import java.util.*;
class B
{
public static void main(String args[])
{
String str1=new String("Alex");
String str2=new String("Alex");
System.out.println("Output given by == operator: "+(str1==str2));
System.out.println("Output by equals() method: "+(str1.equals(str2)));
}
}
Output:
Output given by == operator: false
Output by equals() method: true
51. What are JAR files?
Java Archive(JAR) is a file format that aggregates many files into a single file similar in a format similar to a ZIP file. In other words, the JAR is a zipped file comprised of java lass files, metadata, and resources like text, images, audio files, directories, .class files, and more.
Following is the syntax to create a JAR file:
Jar cf file_name input files
52. What is the difference between method overloading and method overriding in Java? Provide examples to illustrate.
Method overloading is using a single class that has two or more methods with the same name but different parameters. It is solved at compile-time based on the number and types of arguments given. One more instance exists when a subclass provides the specific implementation for some method already defined in its superclass, this is called method overriding, which is used to achieve runtime polymorphism.
For example
class Parent {
void display() {
System.out.println("Parent's display method");
}
}
class Child extends Parent {
void display() {
System.out.println("Child's display method");
}
}
class Main {
public static void main(String[ ] args) {
Parent p = new Parent( );
p.display( ); // Output: Parent's display method
Child child = new Child();
child.display(); // Output: Child's display method
}
}
53. Explain the concept of encapsulation in Java. How does it help in achieving data hiding and abstraction?
Encapsulation in Java is the act of keeping together data and methods that are part of a class to hide the internal state from direct access. The reason behind this approach is to ensure data integrity and promote abstraction by exposing only essential details of the class’s behavior through public methods.
To achieve data hiding, encapsulation restricts direct access to an object’s internal state, thus ensuring data integrity. By doing this, it makes abstraction possible as it only exposes some critical behaviors about the object via public methods, thereby enabling simpler interaction and decreased complexity.
54. What is the purpose of the final keyword in Java? How is it used in variables, methods, and classes?
The final keyword can be added before a variable declaration, any method header, or preceding the class keyword so as not to allow changing their value, to prevent them from being overridden, or before words like “extends” in order not to let inheritance happen.
public final class Circle {
private final double PI = 3.14;
public final void calculateArea(final double radius) {
final double area = PI * radius * radius;
System.out.println("Area of circle: " + area);
}
}
55. Describe the concept of multithreading in Java. How can you create and manage threads in a Java application?
Java multithreading refers to the concurrent execution of multiple threads in one Java program. Threads are lightweight processes capable of running independently and sharing common memory space. There are two ways we can create threads in Java: by extending the Thread class or implementing the Runnable interface.
class MyThread extends Thread {
public void run() {
System.out.println("MyThread is running...");
}
}
class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
56. What is the difference between ArrayList and LinkedList in Java? When would you choose one over the other for storing data?
ArrayList is a dynamic array that stores elements and supports fast random access. It is better suited for element traversal and frequent access. Conversely, LinkedList is a linked list that stores its elements in the form of nodes, making it very suitable for high-speed insertion and deletion operations. Therefore, it can be useful where there are many additions or removals.
If you want fast access and traversal through elements, then use an ArrayList; otherwise, for fast insertion or deletion of elements, use LinkedList.
57. How many types of constructors are there in the Java programming language?
There are two types of constructors in the Java programming language:
- Parameterized Constructor: A constructor that accepts arguments or parameters is known as the parameterized constructor. It initializes the instance variables will the values passed while creating an object.
Below is an example of the parameterized constructor:
import java.util.*;
class A
{
int roll_no;
String name;
A()
{
System.out.println("Constructor called");
}
public void fun()
{
System.out.println("Class A function called");
}
}
class parameterized_constructor
{
public static void main(String args[])
{
A obj=new A();
obj.fun();
System.out.println("The value of instance variables are: ");
System.out.println("Name: "+obj.name);
System.out.println("Roll No: " +obj.roll_no);
}
}
The output of the above program would be:
Constructor called
Class A function called
The value of instance variables are:
Name: null
Roll No: 0
- Non-parameterized/Default constructor: The constructors with no parameters or arguments are known and non-parameterized constructors. In case you don’t define a constructor of any type, the compiler itself creates a default constructor which will be called when the object is created.
Below is an example of a non-parameterized constructor:
import java.util.*;
class A
{
int roll_no;
String name;
A(int x,String y)
{
this.roll_no=x;
this.name=y;
System.out.println("Constructor called");
}
public void fun()
{
System.out.println("Class A function called");
}
}
class non_parameterized_constructor
{
public static void main(String args[])
{
A obj=new A(10,"Harry Williams");
System.out.println("The value of instance variables");
System.out.println("Name: "+obj.name);
System.out.println("Roll No: "+obj.roll_no);
}
}
The output of the above program will be:
Constructor called
The value of instance variables
Name: Harry Williams
Roll No: 10
58. What is the purpose of a Default constructor in Java?
If no constructor is available in the class, the Java compiler creates a default constructor and assigns the default value to the instance variables.
For example:
import java.util.*;
class A
{
String name;
int id;
void display()
{
System.out.println("Name: "+this.name);
System.out.println("Id: "+this.id);
}
}
class B
{
public static void main(String args[])
{
A object=new A();
System.out.println("The values of the instance variables are:");
System.out.println("Name: "+object.name);
System.out.println("Name: "+object.id);
}
}
The output of the above program:
The values of the instance variables are:
Name: null
Name: 0
59. What is the use of a copy constructor in Java?
Java does not support a copy constructor. However, you can copy the values of one instance to another by copying the instance variables of one object to another. Below is an example of such a method:
import java.util.*;
class demo
{
String name;
int roll_no;
//constructor to initialize the name and roll number
demo(int x, String y)
{
name=y;
roll_no=x;
}
//constructor to initialize another object variables
demo(demo ob)
{
roll_no=ob.roll_no;
name=ob.name;
}
void display()
{
System.out.println("Name: "+name);
System.out.println("Roll Number:"+roll_no);
}
}
class copy_constructor
{
public static void main(String args[])
{
demo obj=new demo(10,"Alice Williams");
demo obj2=new demo(obj);
obj.display();
obj2.display();
}
}
The output of the following code is:
Name: Alice Williams
Roll Number:10
Name: Alice Williams
Roll Number:10
60. What is the difference between aggregation and composition?
Below are the key differences between aggregation and composition in Java:
Aggregation |
Composition |
The parent class has a one-way relationship with the child class. |
In composition, the parent class owns the child class |
Aggregation is denoted by an empty diamond in UML (Unified Modeling Language) notation |
Denoted by a filled diamond in the UML notation |
Child class has its own life cycle |
Child class doesn’t have a lifetime |
Aggregation is a weak relationship. For example, a bike with an indicator is aggregation |
Composition is a stronger relationship. For example, a bike with an engine is a composition |
61. What is object cloning?
Object cloning means creating the exact copy of an existing object. In java programming, object cloning can be done using the clone() method. To create the object clone, you should implement the java.lang.Cloneable interface, otherwise the clone() method generates a CloneNotSupportException.
The syntax for the clone method is:
protected Object clone() throws CloneNotSupportedException
62. What are various exception-handling keywords in Java?
Java language has three exception handling keywords:
- try: whenever a code segment has a chance of an error or any abnormality, it can be placed inside the try block. In case of any error, the try block will send the exception to the catch block.
- catch: catch handles the exception generated in the try block. It comes after the try block.
- final: The final keyword ensures that the segments execute despite the errors and exceptions processed by the try & catch block. The final keyword comes either after the try block or both the try and the catch block.
63. How to manually throw an exception in Java programming?
The programmer has to use the throws keyword to create and throw a manual exception. Below is the program to manually throw a single IOException. If you want to throw:
import java.io.*;
class D
{
void function1() throws ArithmeticException
{
throw new ArithmeticException("Arithmetic or zero value error");
}
}
class demoException
{
public static void main(String args[]) throws ArithmeticException
{
D obj=new D();
obj.function1();
System.out.println("End of the program");
}
}
The output of the above program will be:
java.lang.ArithmeticException: Arithmetic or zero value error
64. What is a WAR file?
The Eb Archive file contains the files of a web application and reduces the time needed to transfer the files. War files can store java classes, XML, JSP, image, CSS, js, HTML, and JavaServer pages, which can be used to distribute the collection of Java classes, XML files, Java Servlets, Web pages, etc.
Following is the syntax to create a WAR file:
Jar -cvf file_name.war*
These are the Core Java basic interview questions for freshers, let us check out some of the top Java interview questions that come under the intermediate category.
65. Differentiate between this() and super() in Java.
this() |
super() |
Represents the present instance of a class |
Represents the current instance of the parent class |
Calls the default constructor |
Calls the base class constructor |
Used to point to the current class instance |
Used to point to the instance of the superclass |
66. Name the methods of an object class.
- clone(): This method helps create and return a copy of an object.
- equals(): This method helps compare.
- finalize(): It is called by the garbage collector on the object.
- getClass(): It allows us to return the runtime class of the object.
- hashCode(): This method helps return a hash code value for the object.
- toString(): It lets us return a string representation of the object.
- notify(), notifyAll(), and wait(): These help in synchronizing the activities of the independently running threads in a program.
67. Define content negotiation.
If we have visited a website to search for information, we will get the information in different languages and in different formats. When a client makes an HTTP request to a server, the client can also specify the media types here. The client can specify what it can accept back from the host, and on the basis of availability the host will return to the client. This is known as content negotiation because the client and the server negotiate on the language and format of the content to be shared.
68. Can we import the same package/class twice? Will the JVM load the package twice at runtime?
A package or class can be inherited multiple times in a program code. JVM and compiler will not create any issue. Moreover, JVM automatically loads the class internally once, regardless of times it is called in the program.
69. Define an abstract class.
A class that contains the abstract keyword in its declaration is known as an abstract class. It can have abstract and non-abstract methods (method with a body).
- This class can have public, private, protected, or constants and default variables.
- It needs to be extended and its method needs to be implemented. It cannot be instantiated.
- If a class has at least one abstract method, then the class must be declared abstract.
70. Describe annotations.
- Java annotation is a tag that symbolizes the metadata associated with class, interface, methods, fields, etc.
- Annotations do not directly influence operations.
- The additional information carried by annotations is utilized by Java compiler and JVM.
71. What is the difference between HashMap and HashTable in Java? When would you choose one over the other for storing key-value pairs?
These two are used to save key/value pairs, but with some differences:
- HashMap does not have a synchronization feature, making it not thread-safe, while HashTable does.
- HashMap allows null keys as well as values, but HashTable does not allow any null key or value.
Generally, HashMap is preferred in non-thread-safe scenarios where performance is important; on the other hand, HashTable is recommended for multi-threaded environments where thread safety is required.
72. How does inheritance promote code reusability and extensibility?
In Java, inheritance is a mechanism where one class (superclass) derives another class (subclass). Properties of the superclass, such as methods and fields, are inherited by the subclass. This enables subclasses to reuse superclass code leading to enhanced code reusability. Additionally, this promotes extensibility by letting subclasses add new functions or override the methods of the superclass.
73. What are the different access modifiers in Java? Describe their visibility scopes and when to use each one.
Public, protected, default (no modifier), and private are four access modifiers in Java.
- Public: access from anywhere
- Protected: access to the same package or other packages (subclasses)
- Default (no modifier): Only access in the created package.
- Private: No one else but the declaring class will be able to obtain it.
Use public if you want your member to be accessed from anywhere, protected when you wish to restrict access to subclasses and classes within the same package, default when you want access at the package level, and private when you only want access within the declaring class.
74. How does Java handle memory management and garbage collection? Explain the role of the JVM in managing memory resources.
Garbage collection is Java’s automatic memory management system. It runs as a process that recovers memory from objects that will never be used again. Memory resources management is done by JVM like allocating memory for objects, garbage collecting unused objects, and optimizing memory usage for performance enhancement. Various types of memory areas are used by JVM such as heap, stack method area, and native method stacks to help keep its memory efficient.
75. What are the advantages and disadvantages of using the synchronized keyword for thread synchronization in Java? Are there any alternative approaches for achieving thread safety?
Benefits of using synchronized:
- It ensures thread safety by allowing only one thread to run a synchronized block or method at certain times.
- It is easy to work with and understand.
Drawbacks of using synchronized:
- This may result in performance overheads due to locking and unlocking of objects.
- May result in the occurrence of deadlock when used carelessly.
Other ways for achieving thread safety include:
- Use java.util.concurrent package classes such as ConcurrentHashMap, CopyOnWriteArrayList, etc., and Lock interface implementations for finer-grained control over locking.
- Use volatile keywords when you use variables that are being read and modified by multiple threads so that they are visible across various threads at all times & also that atomicity is guaranteed.
- Avoid shared mutable states by using immutable objects and thread-local variables.
Advanced Java Interview Questions for Senior Developers
76. Distinguish between static loading and dynamic class loading.
- Static loading: In static loading, classes are loaded statically with the operator ‘new.’
- Dynamic class loading: It is a technique for programmatically invoking the functions of a class loader at runtime. The syntax for this is as follows:
Class.forName (Test className);
77. Struts 1 classes are not thread-safe, whereas Struts 2 classes are thread-safe. Why?
Struts 1 actions are singleton. So, all threads operate on the single action object and hence make it thread-unsafe.
Struts 2 actions are not singleton, and a new action object copy is created each time a new action request is made and hence it is thread-safe.
78. Define JAXP and JAXB.
JAXP: It stands for Java API for XML Processing. This provides a common interface for creating and using DOM, SAX, and XSLT APIs in Java regardless of which vendor’s implementation is actually being used.
JAXB: It stands for Java API for XML Binding. This standard defines a system for a script out of Java objects as XML and for creating Java objects from XML structures.
79. Define an enumeration?
The term “enum” is commonly used to refer to an enumeration. An enumeration represents an interface that encompasses methods facilitating access to the underlying data structure from which the enumeration is derived. It enables a systematic, sequential retrieval of all the elements stored within the collection.
80. How can we find the actual size of an object on the heap?
In the Java programming language, you cannot accurately determine the exact size of an object located in the heap.
81. Which API is provided by Java for operations on a set of objects?
Java offers a comprehensive Collection API that presents a multitude of beneficial methods applicable to a group of objects. Noteworthy classes within the Collection API encompass ArrayList, HashMap, TreeSet, and TreeMap. These classes serve as valuable tools for handling, manipulating, and organizing data structures in Java programs.
82. What’s the base class of all exception classes?
Java.Lang.throwable: It is the superclass of all exception classes, and all exception classes are derived from this base class.
83. Why do we use a vector class?
A vector class provides the ability to execute a growable array of objects. A vector proves to be very useful if you don’t know the size of the array in advance or if we need one that can change the size over the lifetime of a program.
84. What is the difference between transient and volatile variables in Java?
Transient: In Java, it is used to specify whether a variable is not being serialized. Serialization is a process of saving an object’s state in Java. When we want to persist the object’s state by default, all instance variables in the object are stored. In some cases, we want to avoid persisting a few variables because we don’t have the necessity to transfer across the network. So, we declare those variables as transient.
If the variable is confirmed as transient, then it will not be persisted. The transient keyword is used with the instance variable that will not participate in the serialization process. We cannot use static with a transient variable as they are part of the instance variable.
Volatile: The volatile keyword is used with only one variable in Java, and it guarantees that the value of the volatile variable will always be read from the main memory and not from the thread’s local cache; it can be static.
85. Why Map interface does not extend the Collection interface in the Java Collections Framework?
The Map interface is not compatible with the Collection interface, because Map requires a key as well as a value, for example, if we want to add a key–value pair, we will use put(Object key, Object value).
There are two parameters required to add an element to HashMap object. In Collection interface, add(Object o) has only one parameter.
The other reasons are: Map supports valueSet, keySet, and other suitable methods that have just different views from the Collection interface.
86. Mention the uses of the synchronized block.
We use the synchronized block because:
- It helps lock an object for every shared resource.
- The scope of the synchronised block is smaller than the method.
87. What are the functions of hashCode() method?
The hashCode() method returns a hash code value (an integer number) and also the same integer number if the two keys (by calling the equals() method) are the same.
But sometimes, the two hash code numbers can have different or the same keys.
88. What is the default size of the load factor in the hashing-based collection?
Default size = 0.75
Default capacity = initial capacity * load factor
89. What are the differences between the JSP custom tags and Java beans?
- Custom tags can manipulate JSP content, but beans cannot.
- Composite operations can be reduced to a considerably simpler form with custom tags than with beans.
- Custom tags require reasonably a bit more work to set up than beans do.
- Custom tags are available only in JSP 1.1 and so on, but beans can be used in all JSP 1.x versions.
90. What are wrapper classes in Java?
Wrapper Classes in Java offers a mechanism to convert the primitive data types into reference or object types and vice-versa. Each primitive data type in Java has a dedicated class known as the wrapper class, which wraps the primitive types into an object of that particular class. Converting primitive data types into objects is known as autoboxing and converting from an object to primitive data types called unboxing.
One of the major applications of wrapper classes is changing the value inside the methods. Java does not support the call by reference, which means changes done inside a method will not change the original value. So, after converting the types into objects, the original values will also change. Also, the wrapper classes help to perform serialization by converting objects into streams.
91. Difference between Stack and Heap Memory in Java?
The key differences between Heap and Stack memory in Java are:
Features |
Stack Memory |
Heap Memory |
Memory Size |
Smaller in size. |
Larger in size. |
LifeTime |
Exists until the end of the thread. |
Lives from the start till the end of application execution. |
Access |
Objects stored in Stack can’t be accessed by other threads. |
Globally accessible. |
Memory Management |
Follows LIFO(Last In First Out) order. |
Dynamic memory allocation. |
Scope or Visibility |
The variables in Stack memory are only visible to the owner thread. |
Heap memory is visible to all the threads. |
Order of Allocation |
Continuous memory allocation. |
Random order memory allocation. |
Flexibility |
Less flexible, one cannot alter the allocation memory. |
Users can alter the allocated memory. |
Efficiency |
Fast access, allocation, and deallocation. |
Slow access, allocation, and deallocation. |
92. What do you mean by the interface in Java?
Java interface is a completely abstract class referred to as a collection of abstract methods, static methods, and constants. It acts as a blueprint of a class that groups related methods or functions with empty bodies.
Below is an example of a java interface:
import java.io.*;
interface x
{
int p=10;
void pr();
default void show()
{
System.out.println("A default method in interface");
}
}
class impx implements x
{
public void pr()
{
System.out.println("Hello World");
}
public static void main(String args[])
{
x ob=new impx();
ob.pr();
ob.show();
}
}
Output:
Hello World
A default method in interface
93. What is the difference between abstract class and interfaces?
Below are the major differences between the abstract class and an interface:
Abstract Class |
Interface |
Can provide complete, default, or only the details in method overriding |
Doesn’t provide any code, the user can only have the signature of the interface. |
Have instance variables. |
No instance variables. |
An abstract class can be public, private, or protected. |
The interface must be public. |
An abstract class can have constructors. |
No constructors are available in the interface. |
A class can inherit only a single abstract class. |
A class can implement one or more interfaces. |
Abstract classes are fast. |
Interfaces are slower as they have to locate the corresponding methods in the class. |
94. What is a servlet in java?
It’s a server-side technology used to create web servers and application servers. We can understand Servlets as the java programs that handle the request from the web servers, process the request, and reverts to the web servers after the response is generated.
Several packages like javax.servlet and javax.servlet. HTTP provides the appropriate interfaces and classes that help the user to create their servlet. All the servlets should implement the javax.servlet.Servlet interface, plus other interfaces and classes like the HttpServlet, Java Servlet API, and more.
The execution of a servlet involves six distinct steps:
- The clients initiate the request by sending it to the web server or application server.
- The web server receives the request from the clients.
- The servlet processes the request, carrying out the necessary computations, and generates the corresponding output.
- Subsequently, the servlet sends the processed request back to the web server.
- Finally, the web server dispatches the request to the clients, and the resulting output is displayed on the client’s screen or any other designated device.
95. What is a Request Dispatcher?
The request dispatcher serves as an interface utilized to effectively redirect requests to various resources within the application itself. These resources may include Java Server Pages (JSP), images, HTML files, or other servlets. Moreover, it facilitates the integration of responses from one servlet into another, guaranteeing that the client receives output from both servlets. Additionally, it allows for the seamless forwarding of client requests to the next servlet in the specified sequence.
There are two methods defined in a Requestdispatcher interface:
- void include(): It includes the content of the resource before sending the response.
- void forward(): the method forwards the request from one servlet to another resource like the JSP, image, etc on the server.
96. How do cookies work in Servlets?
Cookies are the text files sent by the server and get stored in the client system to keep the information on the local machine and use it for tracking purposes. Java Servlet supports HTTP cookies through javax.servlet.http.Cookie class that implements cleanable and serializable interfaces.
The server sends a set of cookies to the client computer, for example, name, age, etc. Then, the browser stores the information in the local machine and sends these cookies to the server, if any request is sent to the webserver. This information can then be used to identify the user.
97. What is the difference between ServletContext vs. ServletConfig?
The difference between ServletContext and ServletConfig is as follows:
ServletContext |
ServletConfig |
Common for all the servlets and generally represents the whole web application. |
represents a single servlet. |
Similar to global parameters linked to the whole application. |
Similar to local parameters associated with a particular servlet. |
The ServletContext has an application-wide scope. |
ServletConfig has the servlet wide scope. |
To get the context object, getServletContext() method is used. |
To get the config object, getServletConfig() is used. |
Mainly used to get a MIME type of file or application. |
Mainly used for specific users or tasks like the shopping card. |
98. Explain the thread lifecycle in Java?
There are 5 states in a thread lifecycle and java can be at any one of them. The thread lies in any one of these states:
- New: The thread lies in the new state after it has been created. It remains in the new state until you start the execution process.
- Running: At runnable state, the thread is ready to run at any point in time or it might have started running already.
- Running: The scheduler picks up the thread and changes its state to running, the CPU starts executing the thread in the running state.
- Waiting: While being ready to execute, another thread might be running in the system. So, the thread goes to the waiting state.
- Dead: Once the execution of the thread is finished, its state is changed to the dead state, which means it’s not considered active anymore.
99. How to distinguish processes from threads?
Below are the key differences between the processes and threads:
Process |
Thread |
The process is the set of instructions or programs in execution. |
Thread is a segment or part of a process |
Takes more time to execute. |
Takes less time to execute. |
Context switching is slower. |
Context switching is faster. |
Processes are generally isolated. |
Threads share the memory. |
The process is a heavy-weight process. |
Lightweight process. |
One blocked process will not affect the performance of other processes. |
A blocked thread would block other threads of the same process. |
The process consumes fewer more resources. |
Threads consume fewer resources. |
100. Explain the types of Exceptions in Java.
There are two types of Exceptions in Java Programming:
- Built-in Exception: These exceptions are the exceptions available in the standard package of java lang. They are used for certain errors with specific Exceptions as mentioned below:
- AriththmeticException: thrown for the errors related to the arithmetic operations.
- IOException: thrown for failed input-output operations.
- FileNotFourndException: raised when the file is not accessible or does not exist.
- ClassNotFoundException: exception is raised when the compiler is unable to find the class definition.
- InterruptedEException: raised when a thread is interrupted.
- NoSuchFieldException: raised when a class or method doesn’t have a variable specified.
- NullPointerException: thrown while referring to the variable or values of a null object.
- RuntimeException: raised for the errors occurring during the runtime. For example, performing invalid type conversion.
- IndexOutOfBoundsException: raised when the index of the collection like an array, string, or vector is out of the range or invalid.
- User-defined Exceptions: User-defined exceptions are the exceptions thrown by the user with custom messages. These are used for cases where the in-built Exception might not be able to define the error.
101. How to write multiple catch statements under a single try block?
Below is the program for multiple catch statements:
import java.util.*;
class multiple_catch
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int x,y,z;
try{
System.out.println("Enter the elements for division: ");
x=s.nextInt();
y=s.nextInt();
z=x/y;
System.out.println("Value of z: "+z);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occured");
}
catch(IllegalArgumentException e)
{
System.out.println("Illegal argument");
}
catch(Exception e)
{
System.out.println("Any Exception in the third block");
}
System.out.println("End of the program");
}
}
The output of the following program in different cases will be:
Case 1: Dividing an integer by zero
Enter the elements for division:
30
0
Arithmetic Exception occurred
End of the program
Case 2: Execution successful
Enter the elements for division:
15
3
Value of z: 5
End of the program
Case 3: Value entered is invalid
Enter the elements for division:
23
t
Any Exception in the third block
End of the program
102. Difference between the throw and throws keyword?
Following are the key differences between the throw and throws keyword:
Key |
throw |
throws |
Definition |
The throw keyword is used to explicitly throw an exception inside a program or a block of code. |
Throws keyword is used to declare an exception in the method signature that might occur during the compilation or execution of a program. |
Type of exception |
Can throw only unchecked exceptions. |
Can be used for both checked and unchecked exceptions. |
Syntax |
throw keyword followed by an instance variable. |
throws keyword followed by the exception class names. |
The implementation |
throw keyword is used to throw only a single exception. |
throws can be used to throw multiple exceptions. |
103. Write the string reversal program without using the in-built function?
There are two ways we can reverse a string in java without using the in-built function:
- Using the loop and print string backward by one character each time.
- Use the recursive function and print the string backward.
In the following program, you can see both ways to print the spring in reverse order:
import java.util.*;
class string_reversal
{
public void method1(String str)
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.print(str.charAt(i));
}
System.out.println();
}
public void reverse(String str)
{
if(str.isEmpty())
{
return;
}
else
reverse(str.substring(1));
System.out.print(str.charAt(0));
}
public static void main(String args[])
{
String str="Intellipaat";
System.out.println("The oroginal string is "+str);
System.out.println("String reversal using the loop: ");
string_reversal obj=new string_reversal();
obj.method1(str);
System.out.println("String reversal using recursion: ");
obj.reverse(str);
}
}
The output of the above program will be:
The oroginal string is Intellipaat
String reversal using the loop:
taapilletnI
String reversal using recursion:
taapilletnI
104. Write a program to print Fibonacci Series using the recursion concept?
import java.util.*;
class fib
{
public int fibonacci(int x)
{
if(x==0)
{
return 0;
}
else if(x==1||x==2)
{
return 1;
}
else
{
return (fibonacci(x-2)+fibonacci(x-1));
}
}
public static void main(String args[])
{
int t=10;
fib ob=new fib();
for(int i=0 ; i < t ; i++)
{
System.out.print(ob.fibonacci(i)+" ");
}
}
}
The output of the above program is:
0 1 1 2 3 5 8 13 21 34
That is all in the section of intermediate core Java interview questions. Let’s move on to the next section of advanced Java interview questions for experienced professionals.
105. Explain the expression language in JSP.
The expression language is used in JSP to simplify the accessibility of objects. It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session, etc.
106. What are implicit objects?
Implicit objects, also called pre-defined variables, are created by the JSP engine inside the service method so that it can be accessed directly without being declared explicitly.
107. Define a cookie. What are the differences between a session and a cookie?
A cookie is a small piece of information, which is sent to the browser by a web server. The browser stores the cookies for every web server in a local file. In a future request, the browser sends all stored cookies for that detailed web server.
The difference between cookies and sessions are:
- A session works regardless of the settings on the client browser. The client may have selected to disable cookies.
- Sessions and cookies also differ in storing the amount of information. The HTTP session is able to store any Java object, while a cookie can only store String objects.
108. What is HTTP Tunneling?
HTTP tunneling refers to encapsulating the private network data/information and transmitting it through a public network. Instead of sending data as a packet, tunneling encrypts the data and encapsulates it in a connection. This process allows the outside clients to collect all the data sent by the client-side Object Request Broker (ORB) that needs to be sent to the server-side ORB. HTTP tunneling masks other protocol requests as HTTP requests.
109. What is the function of the IOC container in spring?
The IOC container is responsible for:
- Creating an instance
- Configuring the instance
- Assembling the dependencies
110. What is lazy loading in hibernate?
Lazy loading is a kind of setting that decides whether to load the child entities along with the parent entities or not. When enabling this feature, the associated entities will be loaded only when they are requested directly. The default value of this setting is ‘true’ which stops the child entities from loading.
111. How can we fetch records using Spring JdbcTemplate?
We can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:
- ResultSetExtractor
- RowMapper
112. Which is the front controller class of Spring MVC?
The Dispatcher Servlet class works as the front controller in Spring MVC.
113. What are the states of an object in hibernate?
The states of an object in hibernate are:
- Transient: The objects that are just created having no primary key are in a transient state. Here the objects are associated with any session.
- Persistent: When the session of an object is just opened and its instance is just saved or retrieved, it is said to be in a persistent state.
- Detached: When the session of an object is closed, it is said to be in a detached state.
114. How to make an immutable class in hibernate?
If we mark a class as mutable=”false”, the class will be treated as an immutable class. The default value of mutable is “true”.
115. What is hash-collision in a HashTable? How is it handled in Java?
In HashTable, if two different keys have the same hash value, then it leads to hash-collision. A bucket of type linked list is used to hold the different keys of the same hash value.
116. Write a syntax to convert a given collection to a SynchronizedCollection.
The following will convert a given collection to a synchronized collection:
import java.util.*;
class Main {
public static void main(String[] args) {
// Example: Converting a List to a Synchronized List
List<String> list = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
List<String> synchronizedList = Collections.synchronizedList(list);
System.out.println("Synchronized List: " + synchronizedList);
// Example: Converting a Set to a Synchronized Set
Set<String> set = new HashSet<>(Set.of("Red", "Green", "Blue"));
Set<String> synchronizedSet = Collections.synchronizedSet(set);
System.out.println("Synchronized Set: " + synchronizedSet);
// Example: Converting a Map to a Synchronized Map
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
Map<String, Integer> synchronizedMap = Collections.synchronizedMap(map);
System.out.println("Synchronized Map: " + synchronizedMap);
// Example: Synchronized block for iterating over synchronized collections
synchronized (synchronizedList) {
for (String item : synchronizedList) {
System.out.println("Iterating Synchronized List: " + item);
}
}
synchronized (synchronizedSet) {
for (String color : synchronizedSet) {
System.out.println("Iterating Synchronized Set: " + color);
}
}
}
}
Output:
Synchronized List: [Alice, Bob, Charlie]
Synchronized Set: [Red, Blue, Green]
Synchronized Map: {One=1, Two=2, Three=3}
Iterating Synchronized List: Alice
Iterating Synchronized List: Bob
Iterating Synchronized List: Charlie
Iterating Synchronized Set: Red
Iterating Synchronized Set: Blue
Iterating Synchronized Set: Green
117. Write a code to make the Collections read-only.
We can make the Collections read-only by using the following lines code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Main {
// Method to sort a list of names using Java's lambda expressions
private void intellipaat(List<String> names) {
names.sort((p1, p2) -> p1.compareTo(p2));
}
public static void main(String[] args) {
// Create a list of names
List<String> names = new ArrayList<>(List.of("John", "Alice", "Bob", "Eve"));
// Print the list before sorting
System.out.println("Before sorting: " + names);
// Sort the list using the intellipaat method
Main main = new Main();
main.intellipaat(names);
// Print the list after sorting
System.out.println("After sorting: " + names);
}
}
Output: Before sorting: [John, Alice, Bob, Eve]
After sorting: [Alice, Bob, Eve, John]
118. What is meant by binding in RMI?
Binding is the process of associating or registering a name for a remote object, which can be used as a further, in order to look up that remote object. A remote object can be associated with a name using the bind/rebind methods of the Naming class.
119. What is the concept of method chaining in Java?
Method chaining in programming is when multiple method calls are used together with each call on the object returned by the previous one. This allows you to write code that is brief and easy to read. Method chaining is achieved by designing methods to return the object itself (this) after operating.
120. What is the ‘this’ keyword in Java? Explain with usage.
The ‘this’ keyword in Java refers to the currently created instance of a class. It is employed to distinguish between instance variables and parameters that have identical names, and also to invoke instance methods or constructors.
Example:
class MyClass {
private int value;
// Constructor with "this" to refer to the instance variable
public MyClass(int value) {
this.value = value;
}
// Method to print the value of the instance variable
public void printValue() {
System.out.println("Value: " + this.value); // "this" is optional here
}
}
class Main {
public static void main(String[] args) {
// Creating an object of MyClass
MyClass obj = new MyClass(42);
// Calling the method to print the value
obj.printValue();
}
}
Output: Value: 42
121. What is a runnable and callable interface in Java?
Runnable: The Runnable interface in Java represents a task that can be executed concurrently by a thread. It contains a single abstract method run() which is called by the thread when it starts executing the task.
Callable: A Callable interface is similar to Runnable; however, it returns a value and can throw checked exceptions. It’s a functional interface containing only one abstract method call() which returns a value of type V.
122. How does java support parallel processing of collections?
Parallel streams, a concept that was introduced in java 8 , can execute operations on collections concurrently using multiple threads. The essence of parallel streams is to split the data into smaller portions and have them distributed over different threads for handling. This can greatly optimize stream operations on large datasets, especially those running on multicore processors.
123. Name a few java annotations.
@Functional Interface annotation: It was introduced in Java SE 8, which indicates that the type declaration is intended to be a functional interface as defined by the Java language specification.
@Repeatable annotation: Introduced in Java SE 8, @Repeatable annotation indicates that the marked annotation can be applied many times to the same declaration or type use.
124. Distinguish between a predicate and a function.
A predicate takes one argument and returns a Boolean value.
A function takes one argument and returns an object. Both are useful for evaluating lambda expressions.
125. Write a code to sort a list of strings using java lambda expression.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Main {
// Method to sort a list of names using Java's lambda expressions
private void intellipaat(List<String> names) {
// Using List's sort method for better readability (Java 8+)
names.sort((p1, p2) -> p1.compareTo(p2));
// Alternatively, use the method reference for brevity
// names.sort(String::compareTo);
}
public static void main(String[] args) {
// Create a list of names
List<String> names = new ArrayList<>(List.of("John", "Alice", "Bob", "Eve"));
// Print the list before sorting
System.out.println("Before sorting: " + names);
// Sort the list using the intellipaat method
Main main = new Main();
main.intellipaat(names);
// Print the list after sorting
System.out.println("After sorting: " + names);
}
}
Output: Before sorting: [John, Alice, Bob, Eve]
After sorting: [Alice, Bob, Eve, John]
126. What is Nashorn in java ?
With java , Nashorn, a much-improved JavaScript engine, is introduced and it replaced the existing Rhino. It provides 2–10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Although, Nashorn uses the invoke dynamic feature, introduced in Java 7, to improve performance.
127. Define a StringJoiner and write a sample code.
StringJoiner is a class in Java that is used to join multiple strings together, optionally adding a delimiter between them. Here’s an example code that demonstrates the usage of StringJoiner:
import java.util.StringJoiner;
class Main {
public static void main(String[] args) {
// Create a StringJoiner with a delimiter "."
StringJoiner strJoiner = new StringJoiner(".");
// Add strings to the StringJoiner
strJoiner.add("AAA").add("BBB");
// Print the joined string
System.out.println(strJoiner); // Output: AAA.BBB
}
}
OutPut:
AAA.BBB
128. Can you execute the JavaScript code from java code base?
Yes! We can execute the JavaScript code from java code base by using ScriptEngineManager. We call JavaScript code and interpret it in Java.
129. What is the use of batch processing in JDBC?
Batch processing is a technique that is used to group a set of related SQL queries and execute them in order. This is done to avoid the execution of a single query at a time.
Making use of batch processing ensures that the queries execute faster, thereby maintaining the high efficiency and overall speed of execution.
130. What are the types of statements supported by JDBC?
There are three types of statements supported by JDBC as shown below:
- Statement: Used to execute static queries and for general access to the database
- CallableStatement: Provides access to stored procedures and runtime parameters
- PreparedStatement: Provides input parameters to queries while they are executing
131. What is a collection in Java?
A collection is a framework that is used to store and manipulate a container of objects in Java.
Java Collections can be used for performing a variety of operations such as:
- Search
- Sort
- Manipulate
- Delete
Below is the chart that represents the hierarchy of collections in Java:
132. What is the meaning of constructor overloading in Java?
Constructor overloading is a technique that is popular among programmers who have a requirement of adding multiple constructors to a single class with a different parameter list. The following denotes an example of constructor overloading in Java:
class Hello {
int i, j;
// Constructor with one parameter
public Hello(int x) {
i = x;
System.out.println("Constructor with one parameter called. i = " + i);
}
// Constructor with two parameters
public Hello(int x, int y) {
i = x;
j = y;
System.out.println("Constructor with two parameters called. i = " + i + ", j = " + j);
}
}
class Main {
public static void main(String[] args) {
// Creating an object using the constructor with one parameter
Hello obj1 = new Hello(10);
// Creating an object using the constructor with two parameters
Hello obj2 = new Hello(20, 30);
}
}
Output:
Constructor with one parameter called. i = 10
Constructor with two parameters called. i = 20, j = 30
133. What is the JDBC Driver?
Java Database Connectivity(JDBC) is an API that allows the client to access different data sources from spreadsheets to flat files and relational databases. It’s a middle layer interface that establishes a connection between java applications and databases. In addition to the connection of data sources, JDBC is used for sending queries and updates to the database, and retrieving and processing data received from the database.
There are four types of JDBC drivers:
- JDBC-ODBC bridge Drivers: Uses Open Database Connectivity(ODBC) to connect with the database. It’s also known as the Universal Driver as it can be used to connect with any database.
- Native-API Drivers: It’s a partial java Driver that uses client-side libraries of the database to convert JDBC calls into native ones of the database programming interface. The Network-API needs to be installed on individual client machines separately.
- Network protocol Drivers: The driver uses the middleware or application server to convert the JDBC calls into the vendor-specific protocol. It doesn’t require individual client-side installation as all the connectivity drivers are present in one driver.
- Thin Drivers: These are portable drivers that won’t require any installation from any client or server-side installation. They directly interact with the database and don’t require any database library to do so.
134. What is the difference between execute, executeQuery, and executeUpdate?
Below are the key differences between execute, executeQuery, and executeUpdate:
execute |
executeQuery |
executeUpdate |
Used to execute any SQL query and get the result in boolean format (True or False). |
executeQuery is used to execute the SQL queries and retrieve some data from the database. |
executeUpdate is used to execute DML (Data Manipulation Language) statements like updating or modifying the database. |
Returns a boolean value, where TRUE indicates the query returned is an object of the ResultSet, and FALSE indicates that nothing or an integer value has returned. |
Returns the ResultSet object that contains the result generated and returned by the query. |
Returns an integer value representing the number of rows updated or altered by the query. |
Used to execute both select and non-select queries. |
Used to execute select queries. |
Used to execute non-select queries. |
Ex-any SQL statement. |
Ex- SELECT |
Ex- INSERT, CREATE, ALTER, DELETEDDL, UPDATE, etc |
135. Explain the concept of functional interfaces in java.
A functional interface in java is an interface that consists of only one abstract method. It can have multiple default or static methods. They are used to implement lambda expressions, which allow for the expression of instances of single-method interfaces (functional interfaces) in a short form of programming language. Some examples of these functional interfaces in java include Runnable, Comparator, and Callable.
136. What are the advantages of using streams in java?
Streams in java provide a declarative and functional approach to process collections of data. Here are some benefits of using streams:
- Consequently, stream operations can be chained together to create codes that are concise and readable.
- Streams use functional-style operations such as map, filter, and reduce that enhance the clarity and maintainability of code.
- A Support parallel processing of data streams enhancing performance on multi-core systems.
- The abstraction layer also removes low-level details involved with iteration while automatically managing resources.
137. How does the Optional class in java help in handling null values?
java Optional class provides a means to handle potential null values without needing to explicitly check for null. It makes developers convey their intentions making the code more expressive and safer. Optional can guard against NullPointerExceptions by offering methods like orElse, orElseGet, and orElseThrow that act as default values providers or handlers absent itself.
138. What is the difference between forEach and forEachOrdered methods in Java streams?
A terminal operation is a method that terminates the iteration of elements in a stream. Although both are used to iterate elements in a stream, there is a difference between forEach and forEachOrdered methods:
- forEach: It processes items in no particular order, meaning it does not guarantee any specific sequence of execution. It can offer improved performance for parallel streams but cannot preserve the original ordering of the stream.
- forEachOrdered: Elements are processed as per their encounter order provided by the stream. Even for parallel streams, this ensures that items are processed sequentially based on their order of occurrence, it can be more expensive than for.
139. Explain the concept of method references in Java
In Java, method references provide a shorthand way to create lambda expressions that simply call an existing method. Method references mean you can reuse existing methods as lambdas, making code more compact and readable.
There are four kinds of Method References:
- Reference to the static method: ContainingClass::staticMethodName
- Reference to an instance method of a particular object: object::instanceMethodName
- Reference to an instance method of an arbitrary object of a particular type: ContainingType::methodName
- Reference to constructor: ClassName::new
Core Java Coding Interview Questions
140. Write a program that prints the numbers from 1 to 100. But for multiples of three, print ‘Fizz’ instead of the number, and for the multiples of five, print ‘Buzz’. For numbers that are multiples of both three and five, print ‘FizzBuzz’.
class MissingNumber {
public int intellipaat(int[] nums) {
int n = nums.length;
// Calculate the expected sum of numbers from 0 to n
int sum = n * (n + 1) / 2;
// Subtract each number in the array from the sum
for (int num : nums) {
sum -= num;
}
// The remaining value is the missing number
return sum;
}
public static void main(String[] args) {
// Example input
int[] nums = {3, 0, 1};
// Create an instance of the MissingNumber class
MissingNumber solution = new MissingNumber();
// Call the intellipaat method to find the missing number
int missingNumber = solution.intellipaat(nums);
// Print the missing number
System.out.println("The missing number is: " + missingNumber);
}
}
Output: The missing number is: 2
141. Write a function to determine if two strings are anagrams of each other.
import java.util.Arrays;
class Main {
// Method to check if two strings are anagrams
public boolean intellipaat(String str1, String str2) {
// If lengths differ, they cannot be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Convert strings to character arrays
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
// Sort the character arrays
Arrays.sort(chars1);
Arrays.sort(chars2);
// Compare sorted arrays
return Arrays.equals(chars1, chars2);
}
public static void main(String[] args) {
Main obj = new Main();
// Test cases
String str1 = "listen";
String str2 = "silent";
String str3 = "triangle";
String str4 = "integral";
String str5 = "hello";
String str6 = "world";
// Check for anagrams
System.out.println(str1 + " and " + str2 + " are anagrams: " + obj.intellipaat(str1, str2));
System.out.println(str3 + " and " + str4 + " are anagrams: " + obj.intellipaat(str3, str4));
System.out.println(str5 + " and " + str6 + " are anagrams: " + obj.intellipaat(str5, str6));
}
}
Output:
listen and silent are anagrams: true
triangle and integral are anagrams: true
hello and world are anagrams: false
142. Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
public class Main {
// Method to find the missing number in an array
public int intellipaat(int[] nums) {
int n = nums.length; // Number of elements in the array
int sum = n * (n + 1) / 2; // Sum of numbers from 0 to n
// Subtract each number in the array from the expected sum
for (int num : nums) {
sum -= num;
}
// The remaining value in sum is the missing number
return sum;
}
public static void main(String[] args) {
Main obj = new Main();
// Test cases
int[] nums1 = {3, 0, 1}; // Missing number is 2
int[] nums2 = {9, 6, 4, 2, 3, 5, 7, 0, 1}; // Missing number is 8
int[] nums3 = {0}; // Missing number is 1
int[] nums4 = {1}; // Missing number is 0
// Output results
System.out.println("Missing number in nums1: " + obj.intellipaat(nums1));
System.out.println("Missing number in nums2: " + obj.intellipaat(nums2));
System.out.println("Missing number in nums3: " + obj.intellipaat(nums3));
System.out.println("Missing number in nums4: " + obj.intellipaat(nums4));
}
}
Output:
Missing number in nums1: 2
Missing number in nums2: 8
Missing number in nums3: 1
Missing number in nums4: 0
143. Implement a function to reverse a singly linked list.
class ListNode {
int v; // Value of the node
ListNode nxt; // Pointer to the next node
ListNode(int v) {
this.v = v;
}
}
class LinkedListReverser {
public ListNode S_List(ListNode head) {
ListNode prev = null; // Previous node
ListNode cur = head; // Current node
while (cur != null) {
ListNode nxt = cur.nxt; // Save the next node
cur.nxt = prev; // Reverse the current node's pointer
prev = cur; // Move prev to current node
cur = nxt; // Move to the next node
}
return prev; // New head of the reversed list
}
// Helper method to print the linked list
public void printList(ListNode head) {
ListNode cur = head;
while (cur != null) {
System.out.print(cur.v + " ");
cur = cur.nxt;
}
System.out.println();
}
public static void main(String[] args) {
LinkedListReverser reverser = new LinkedListReverser();
// Creating a sample linked list: 1 -> 2 -> 3 -> 4 -> 5
ListNode head = new ListNode(1);
head.nxt = new ListNode(2);
head.nxt.nxt = new ListNode(3);
head.nxt.nxt.nxt = new ListNode(4);
head.nxt.nxt.nxt.nxt = new ListNode(5);
System.out.print("Original list: ");
reverser.printList(head);
// Reversing the linked list
ListNode reversedHead = reverser.S_List(head);
System.out.print("Reversed list: ");
reverser.printList(reversedHead);
}
}
Output:
Original list: 1 2 3 4 5
Reversed list: 5 4 3 2 1
144. Write a function to determine whether the given number is prime or not.
class PrimeChecker {
public boolean prime(int n) {
// Check for numbers less than or equal to 1
if (n <= 1) {
return false;
}
// Check for factors from 2 to the square root of n
for (int x = 2; x * x <= n; x++) {
if (n % x == 0) {
return false; // n is divisible by x, hence not prime
}
}
return true; // n is prime
}
public static void main(String[] args) {
PrimeChecker checker = new PrimeChecker();
// Test cases
int[] testNumbers = {1, 2, 3, 4, 5, 16, 17, 18, 19, 20, 29, 30};
for (int number : testNumbers) {
boolean isPrime = checker.prime(number);
System.out.println(number + " is prime: " + isPrime);
}
}
}
Output:
1 is prime: false
2 is prime: true
3 is prime: true
4 is prime: false
5 is prime: true
16 is prime: false
17 is prime: true
18 is prime: false
19 is prime: true
20 is prime: false
29 is prime: true
30 is prime: false
145. Given two sorted arrays, merge them into a single sorted array.
import java.util.Arrays;
class ArrayMerger {
public int[] merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1; // Pointer for nums1
int j = n - 1; // Pointer for nums2
int k = m + n - 1; // Pointer for the merged array
// Merge the arrays from the end to the beginning
while (i >= 0 && j >= 0) {
if (nums1[i] > nums2[j]) {
nums1[k--] = nums1[i--];
} else {
nums1[k--] = nums2[j--];
}
}
// If there are remaining elements in nums2, add them
while (j >= 0) {
nums1[k--] = nums2[j--];
}
return nums1;
}
public static void main(String[] args) {
ArrayMerger merger = new ArrayMerger();
// Example arrays
int[] nums1 = new int[6]; // Size should be m + n
nums1[0] = 1;
nums1[1] = 2;
nums1[2] = 3;
int m = 3; // Number of initialized elements in nums1
int[] nums2 = {2, 5, 6};
int n = nums2.length; // Number of elements in nums2
// Merge the arrays
int[] mergedArray = merger.merge(nums1, m, nums2, n);
// Print the merged array
System.out.println("Merged array: " + Arrays.toString(mergedArray));
}
}
Output: Merged array: [1, 2, 2, 3, 5, 6]
146. Implement a binary search algorithm.
class BinarySearch {
public int binary(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Calculate the middle index
if (nums[mid] == target) {
return mid; // Target found
} else if (nums[mid] < target) {
left = mid + 1; // Search in the right half
} else {
right = mid - 1; // Search in the left half
}
}
return -1; // Target not found
}
public static void main(String[] args) {
BinarySearch searcher = new BinarySearch();
// Example sorted array
int[] nums = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int target = 7;
int result = searcher.binary(nums, target);
if (result != -1) {
System.out.println("Element " + target + " found at index: " + result); // Output: 3
} else {
System.out.println("Element " + target + " not found.");
}
// Test with a target not in the array
target = 8;
result = searcher.binary(nums, target);
if (result != -1) {
System.out.println("Element " + target + " found at index: " + result);
} else {
System.out.println("Element " + target + " not found."); // Output: not found
}
}
}
Output: Element 7 found at index: 3
Element 8 not found.
147. Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
class PalindromeChecker {
public boolean palind(int y) {
// Negative numbers are not palindromes
if (y < 0) {
return false;
}
int rev = 0, org = y; // Store the original number
while (y != 0) {
int rem = y % 10; // Get the last digit
rev = rev * 10 + rem; // Build the reversed number
y /= 10; // Remove the last digit
}
// Check if the original number is equal to the reversed number
return org == rev;
}
public static void main(String[] args) {
PalindromeChecker checker = new PalindromeChecker();
// Test cases
int[] testNumbers = {121, -121, 10, 12321, 0};
for (int number : testNumbers) {
boolean isPalindrome = checker.palind(number);
System.out.println(number + " is a palindrome: " + isPalindrome);
}
}
}
Output:
121 is a palindrome: true
-121 is a palindrome: false
10 is a palindrome: false
12321 is a palindrome: true
0 is a palindrome: true
148. Given an integer array nums, find the contiguous subarray (containing at least one number) that has the largest sum and return its sum.
class LargestSumSubarray {
public int large_sum(int[] n) {
int m_sum = n[0]; // Maximum sum found so far
int c_sum = n[0]; // Current subarray sum
for (int x = 1; x < n.length; x++) {
c_sum = Math.max(n[x], c_sum + n[x]); // Update current sum
m_sum = Math.max(m_sum, c_sum); // Update maximum sum
}
return m_sum;
}
public static void main(String[] args) {
LargestSumSubarray finder = new LargestSumSubarray();
// Example array
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int maxSum = finder.large_sum(nums);
System.out.println("The largest sum of a contiguous subarray is: " + maxSum); // Output: 6
}
}
Output:
The largest sum of a contiguous subarray is: 6
149. Implement a stack data structure using arrays or linked lists.
class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (top < maxSize - 1) {
stackArray[++top] = value;
} else {
System.out.println("Stack is full. Cannot push " + value);
}
}
public int pop() {
if (top >= 0) {
return stackArray[top--];
}
System.out.println("Stack is empty. Cannot pop.");
return -1; // Returning -1 to indicate an error
}
public int peek() {
if (top >= 0) {
return stackArray[top];
}
System.out.println("Stack is empty. Cannot peek.");
return -1; // Returning -1 to indicate an error
}
public boolean isEmpty() {
return (top == -1);
}
public static void main(String[] args) {
Stack stack = new Stack(5); // Create a stack of size 5
// Test the stack implementation
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Top element is: " + stack.peek()); // Output: 30
System.out.println("Popped element is: " + stack.pop()); // Output: 30
System.out.println("Top element after pop: " + stack.peek()); // Output: 20
stack.push(40);
stack.push(50);
stack.push(60); // This will print a message since the stack is full
while (!stack.isEmpty()) {
System.out.println("Popped element: " + stack.pop());
}
System.out.println("Trying to pop from empty stack: " + stack.pop()); // Output: Stack is empty
}
}
Output:
Top element is: 30
Popped element is: 30
Top element after pop: 20
Popped element: 60
Popped element: 50
Popped element: 40
Popped element: 20
Popped element: 10
Stack is empty. Cannot pop.
Trying to pop from empty stack: -1
150. Implement a queue data structure using stacks.
import java.util.Stack;
class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int peek() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
// Test the queue implementation
queue.push(1);
queue.push(2);
System.out.println("Peek: " + queue.peek()); // Output: 1
System.out.println("Pop: " + queue.pop()); // Output: 1
System.out.println("Is queue empty? " + queue.empty()); // Output: false
queue.push(3);
System.out.println("Pop: " + queue.pop()); // Output: 2
}}
Output:
Peek: 1
Pop: 1
Is queue empty? false
Pop: 2
151. Write a function to check if a given number is an Armstrong number or not.
class ArmstrongChecker {
public boolean armstrong(int num) {
int sum = 0;
int originalNum = num;
int numDigits = String.valueOf(num).length();
while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, numDigits);
num /= 10;
}
return sum == originalNum;
}
public static void main(String[] args) {
ArmstrongChecker checker = new ArmstrongChecker();
// Example numbers to check
int[] numbersToCheck = {153, 370, 371, 9474, 123};
for (int number : numbersToCheck) {
boolean isArmstrong = checker.armstrong(number);
System.out.println(number + " is an Armstrong number: " + isArmstrong);
}
}
}
Output:
153 is an Armstrong number: true
370 is an Armstrong number: true
371 is an Armstrong number: true
9474 is an Armstrong number: true
123 is an Armstrong number: false
152. Write a function to count the number of words in a string.
class WordCounter {
public int countWords(String s) {
// Trim the string and split it by whitespace
String[] words = s.trim().split("\\s+");
// Return the number of words
return words.length == 1 && words[0].isEmpty() ? 0 : words.length;
}
public static void main(String[] args) {
WordCounter counter = new WordCounter();
// Example string
String example = " Hello, this is a test string. ";
int wordCount = counter.countWords(example);
System.out.println("The number of words is: " + wordCount);
}
}
Output: The number of words is: 6
153. Given a sorted array nums, remove the duplicates in place such that each element appears only once and return the new length.
import java.util.Arrays;
class DuplicateRemover {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
int index = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[index]) {
nums[++index] = nums[i];
}
}
return index + 1;
}
public static void main(String[] args) {
DuplicateRemover remover = new DuplicateRemover();
// Example array with duplicates
int[] nums = {1, 1, 2, 2, 3, 4, 4, 5};
int newLength = remover.removeDuplicates(nums);
System.out.println("The number of unique elements is: " + newLength); // Output: 5
System.out.print("The modified array is: ");
for (int i = 0; i < newLength; i++) {
System.out.print(nums[i] + " ");
}
}
}
Output:
The number of unique elements is: 5
The modified array is: 1 2 3 4 5
154. Write a function to calculate the factorial of a given number.
class FactorialCalculator {
public int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
FactorialCalculator calculator = new FactorialCalculator();
// Example number
int number = 5;
int result = calculator.factorial(number);
System.out.println("The factorial of " + number + " is: " + result); // Output: 120
}
}
Output: The factorial of 5 is: 120
155. Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), find the duplicate one.
class DuplicateFinder {
public int findDuplicate(int[] nums) {
int slow = nums[0];
int fast = nums[0];
// Phase 1: Finding the intersection point
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
// Phase 2: Finding the entrance to the cycle
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
public static void main(String[] args) {
DuplicateFinder finder = new DuplicateFinder();
// Example array with a duplicate
int[] nums = {1, 3, 4, 2, 2};
int duplicate = finder.findDuplicate(nums);
System.out.println("The duplicate number is: " + duplicate); // Output: 2
}
}
Output: The duplicate number is: 2
156. Implement a simple hashmap data structure.
import java.util.Arrays;
class MyHashMap {
private final int SIZE = 1000;
private final ListNode[] nodes;
public MyHashMap() {
nodes = new ListNode[SIZE];
}
public void put(int key, int value) {
int index = getIndex(key);
if (nodes[index] == null) {
nodes[index] = new ListNode(-1, -1);
}
ListNode prev = find(nodes[index], key);
if (prev.next == null) {
prev.next = new ListNode(key, value);
} else {
prev.next.val = value;
}
}
public int get(int key) {
int index = getIndex(key);
if (nodes[index] == null) {
return -1;
}
ListNode prev = find(nodes[index], key);
return prev.next == null ? -1 : prev.next.val;
}
public void remove(int key) {
int index = getIndex(key);
if (nodes[index] == null) {
return;
}
ListNode prev = find(nodes[index], key);
if (prev.next != null) {
prev.next = prev.next.next;
}
}
private int getIndex(int key) {
return Integer.hashCode(key) % SIZE;
}
private ListNode find(ListNode bucket, int key) {
ListNode node = bucket, prev = null;
while (node != null && node.key != key) {
prev = node;
node = node.next;
}
return prev;
}
private static class ListNode {
int key, val;
ListNode next;
ListNode(int key, int val) {
this.key = key;
this.val = val;
}
}
public static void main(String[] args) {
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // Insert a key-value pair (1, 1)
myHashMap.put(2, 2); // Insert a key-value pair (2, 2)
System.out.println(myHashMap.get(1)); // Returns 1
System.out.println(myHashMap.get(3)); // Returns -1 (not found)
myHashMap.put(2, 1); // Update key 2 to value 1
System.out.println(myHashMap.get(2)); // Returns 1
myHashMap.remove(2); // Remove key 2
System.out.println(myHashMap.get(2)); // Returns -1 (not found)
}
}
Output:
1
-1
1
-1
Java Scenario Based Interview Questions
157. Suppose you are working to produce a multi-threaded application that imitates a banking system. Customers can deposit and withdraw money from their accounts. How could thread synchronization be used to make sure that the balance of an account is updated correctly even when multiple threads are trying to update the balance at once?
This would signify that only one thread will execute these methods during a given instance, preventing any race condition where the final balance might not reflect all transactions because they occurred simultaneously, thus, it updates all these things correctly using this synchronized keyword in them.
class BankAccount {
private int balance = 0;
// Synchronized deposit method to ensure thread safety
public synchronized void deposit(int amount) {
balance += amount;
System.out.println("Deposited " + amount + ", new balance is " + balance);
}
// Synchronized withdraw method to ensure thread safety
public synchronized void withdraw(int amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrew " + amount + ", new balance is " + balance);
} else {
System.out.println("Insufficient balance");
}
}
// Getter for balance
public int getBalance() {
return balance;
}
}
class BankingThread extends Thread {
private BankAccount account;
public BankingThread(BankAccount account) {
this.account = account;
}
public void run() {
for (int i = 0; i < 10; i++) {
account.deposit(100);
account.withdraw(50);
}
}
}
class BankingSystem {
public static void main(String[] args) {
BankAccount account = new BankAccount();
BankingThread t1 = new BankingThread(account);
BankingThread t2 = new BankingThread(account);
// Start both threads
t1.start();
t2.start();
try {
// Wait for both threads to finish
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Print the final balance after both threads have finished
System.out.println("Final balance: " + account.getBalance());
}
}
Output:
Deposited 100, new balance is 100
Withdrew 50, new balance is 50
Deposited 100, new balance is 150
Withdrew 50, new balance is 100
Deposited 100, new balance is 200
Withdrew 50, new balance is 150
Deposited 100, new balance is 250
Withdrew 50, new balance is 200
Deposited 100, new balance is 300
Withdrew 50, new balance is 250
Deposited 100, new balance is 350
Withdrew 50, new balance is 300
Deposited 100, new balance is 400
Withdrew 50, new balance is 350
Deposited 100, new balance is 450
Withdrew 50, new balance is 400
Deposited 100, new balance is 500
Withdrew 50, new balance is 450
Deposited 100, new balance is 550
Withdrew 50, new balance is 500
Deposited 100, new balance is 600
Withdrew 50, new balance is 550
Deposited 100, new balance is 650
Withdrew 50, new balance is 600
Deposited 100, new balance is 700
Withdrew 50, new balance is 650
Deposited 100, new balance is 750
Withdrew 50, new balance is 700
Deposited 100, new balance is 800
Withdrew 50, new balance is 750
Deposited 100, new balance is 850
Withdrew 50, new balance is 800
Deposited 100, new balance is 900
Withdrew 50, new balance is 850
Deposited 100, new balance is 950
Withdrew 50, new balance is 900
Deposited 100, new balance is 1000
Withdrew 50, new balance is 950
Deposited 100, new balance is 1050
Withdrew 50, new balance is 1000
Final balance: 1000
158. Imagine a scenario involving the development of a chat application that makes it possible for many users to send messages in one chat room. In what way is it possible to use thread synchronisation to make sure that messages are displayed in the right order, even when multiple users are sending them at the same time?
To maintain message display order, the keyword “synchronised” would be used to synchronise access to the method that adds messages to the chat room. Thus, only one thread can add a message at a time, and this maintains their order as they come in.
import java.util.ArrayList;
import java.util.List;
class ChatRoom {
private final List<String> messages = new ArrayList<>();
// Synchronized method to ensure thread safety while adding messages
public synchronized void addMessage(String message) {
messages.add(message);
System.out.println(message);
}
}
class UserThread extends Thread {
private ChatRoom chatRoom;
private String userName;
public UserThread(ChatRoom chatRoom, String userName) {
this.chatRoom = chatRoom;
this.userName = userName;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
chatRoom.addMessage(userName + ": Message " + i);
try {
Thread.sleep(1000); // Simulating delay between messages
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ChatApplication {
public static void main(String[] args) {
ChatRoom chatRoom = new ChatRoom();
// Create two users sending messages
UserThread user1 = new UserThread(chatRoom, "User1");
UserThread user2 = new UserThread(chatRoom, "User2");
// Start both threads
user1.start();
user2.start();
try {
// Wait for both threads to finish
user1.join();
user2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
User2: Message 0
User1: Message 0
User2: Message 1
User1: Message 1
User2: Message 2
User1: Message 2
User2: Message 3
User1: Message 3
User2: Message 4
User1: Message 4
159. Think of yourself working on a system that processes massive amounts of data all at once for you. The system has multiple threads that read from a shared data source, do some math with it, and then store the results in the shared output. How would you prevent deadlocks in this situation?
To avoid them, make sure all threads acquire locks in the same order. Alternatively, the wait() method can be used with timeouts to prevent infinite waiting, as well as periodical checks for deadlock conditions.
class Message {
private String message;
private boolean empty = true;
// Synchronized read method to read the message
public synchronized String read() {
while (empty) {
try {
wait(); // Wait until there's a message to read
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty = true; // Mark message as consumed
notifyAll(); // Notify the writer that it can write again
return message;
}
// Synchronized write method to write a message
public synchronized void write(String message) {
while (!empty) {
try {
wait(); // Wait until the message is consumed and empty
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty = false; // Mark message as available
this.message = message; // Set the message
notifyAll(); // Notify the reader that a new message is available
}
}
// Writer thread simulates the producer
class WriterThread extends Thread {
private Message message;
public WriterThread(Message message) {
this.message = message;
}
@Override
public void run() {
String[] messages = {"Hello", "How are you?", "Goodbye", "Have a nice day!"};
for (String msg : messages) {
message.write(msg);
System.out.println("Written: " + msg);
try {
Thread.sleep(1000); // Simulating delay
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Reader thread simulates the consumer
class ReaderThread extends Thread {
private Message message;
public ReaderThread(Message message) {
this.message = message;
}
@Override
public void run() {
for (int i = 0; i < 4; i++) {
String msg = message.read();
System.out.println("Read: " + msg);
try {
Thread.sleep(1500); // Simulating delay
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ProducerConsumerExample {
public static void main(String[] args) {
Message message = new Message();
WriterThread writer = new WriterThread(message); // Producer
ReaderThread reader = new ReaderThread(message); // Consumer
writer.start(); // Start the writer thread
reader.start(); // Start the reader thread
try {
writer.join(); // Wait for writer thread to finish
reader.join(); // Wait for reader thread to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Read: Hello
Written: Hello
Written: How are you?
Read: How are you?
Written: Goodbye
Read: Goodbye
Written: Have a nice day!
Read: Have a nice day!
160. You are tasked to create a web application that uses a shared resource, such as a database connection pool, to handle requests. How would you use the ‘volatile’ keyword to make sure that all threads see the most recent state of the connection pool?
By declaring the connection pool reference as volatile, you make sure that changes made to the reference by one thread are immediately visible to other threads. This is important for making sure that all threads work on the most current state of the connection pool, preventing issues like using a closed or invalid connection.
import java.util.ArrayList;
import java.util.List;
class ConnectionPool {
private volatile List<Connection> connections = new ArrayList<>();
// Synchronized method to get a connection
public synchronized Connection getConnection() {
if (connections.isEmpty()) {
System.out.println("Creating a new connection");
connections.add(new Connection()); // Simulate creating a new connection
}
return connections.remove(connections.size() - 1); // Return the last connection
}
// Synchronized method to release a connection
public synchronized void releaseConnection(Connection connection) {
connections.add(connection);
System.out.println("Connection released");
}
}
class Connection {
// Simulate a simple connection object
public Connection() {
// Simulate a connection initialisation
}
}
class DatabaseTask extends Thread {
private ConnectionPool pool;
public DatabaseTask(ConnectionPool pool) {
this.pool = pool;
}
@Override
public void run() {
Connection connection = pool.getConnection(); // Get a connection from the pool
// Simulate using the connection
try {
Thread.sleep(1000); // Simulate some database task
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.releaseConnection(connection); // Release the connection back to the pool
}
}
class ConnectionPoolDemo {
public static void main(String[] args) {
ConnectionPool pool = new ConnectionPool(); // Initialize connection pool
// Create multiple tasks (threads) to simulate database requests
DatabaseTask task1 = new DatabaseTask(pool);
DatabaseTask task2 = new DatabaseTask(pool);
// Start the tasks (threads)
task1.start();
task2.start();
// Wait for the tasks (threads) to complete
try {
task1.join();
task2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Creating a new connection
Creating a new connection
Connection released
Connection released
161. Imagine that you are designing a Java application for an ongoing background task, which will be responsible for verifying updates from a distant server regularly. The job should have the ability to be halted at any time. How do you implement this task using thread interruption?
The background routine could be implemented as a Runnable or Thread class that would check for updates in a loop. This would mean that within the loops, one might invoke Thread.sleep() to momentarily halt it and handle InterruptedException when it crops up. Furthermore, if it is necessary to stop the task you can simply call the interrupt() method on the thread, which signals its interrupted status and causes InterruptedException during Thread.sleep(). The program can then exit gracefully by checking its interrupted status and telling the loop to stop running.
class BackgroundTask implements Runnable {
private volatile boolean running = true;
public void run() {
while (running) {
try {
// Simulate work
System.out.println("Checking for updates...");
Thread.sleep(1000); // Simulating periodic task that can be interrupted
} catch (InterruptedException e) {
// Catching the InterruptedException and checking if the task should stop
System.out.println("Task interrupted, stopping...");
running = false; // Change running to false to exit the loop
Thread.currentThread().interrupt(); // Preserve interrupt status for other handling
}
}
}
// This method allows external code to request a graceful stop
public void stop() {
running = false;
}
}
class BackgroundTaskDemo {
public static void main(String[] args) {
BackgroundTask task = new BackgroundTask();
Thread thread = new Thread(task);
thread.start(); // Start the background task
try {
Thread.sleep(5000); // Let the task run for 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
// Interrupt the task after 5 seconds
thread.interrupt(); // This will cause the thread to be interrupted if it's sleeping or blocked
}
}
Output:
Checking for updates…
Checking for updates…
Checking for updates…
Checking for updates…
Checking for updates…
Task interrupted, stopping…
162. Imagine you are developing a Spring Boot application that manages a library. Users can borrow and return books. How would you use Spring’s @Transactional annotation to ensure that the operations of borrowing and returning a book are atomic, meaning either both operations succeed or both fail?
You would use the @Transactional annotation on the service methods that handle the borrowing and returning of books. This ensures that if an exception occurs during either operation, the transaction will be rolled back, maintaining the integrity of your data.
@Service
class LibraryService {
@Autowired
private BookRepository bookRepository;
@Transactional
public void borrowBook(Long bookId, Long userId) {
Book book = bookRepository.findById(bookId).orElseThrow(() -> new BookNotFoundException("Book not found"));
if (book.isBorrowed()) {
throw new BookAlreadyBorrowedException("Book is already borrowed");
}
book.setBorrowed(true);
book.setUserId(userId);
bookRepository.save(book);
}
@Transactional
public void returnBook(Long bookId) {
Book book = bookRepository.findById(bookId).orElseThrow(() -> new BookNotFoundException("Book not found"));
if (!book.isBorrowed()) {
throw new BookNotBorrowedException("Book is not borrowed");
}
book.setBorrowed(false);
book.setUserId(null);
bookRepository.save(book);
}
}
163. Imagine you are working on a logging system where you need to log messages with different severity levels (INFO, WARN, ERROR). How would you design a custom functional interface to handle this in Java?
A custom functional interface named Logger can be defined with only one abstract method log(String message, Severity severity). This way, you can create an implementation for this interface using lambda expressions for each level of severity. The following is how you may declare and use this interface.
@FunctionalInterface
interface Logger {
void log(String message, Severity severity);
}
enum Severity {
INFO, WARN, ERROR
}
class Main {
public static void main(String[] args) {
Logger logger = (message, severity) -> System.out.println(severity + ": " + message);
logger.log("Application started", Severity.INFO);
logger.log("An error occurred", Severity.ERROR);
}
}
164. Suppose you have a list of user IDs, and you need to transform them into user objects by fetching user details from a database. How would you use the Function interface in Java to achieve this?
The Function interface is used to define a lambda expression that takes a user ID and returns a user object. Below is an example:
import java.util.function.Function;
class Main {
public static void main(String[] args) {
Function<String, User> fetchUser = (userId) -> {
// Simulate fetching user details from a database
return new User(userId, "John Doe", "[email protected]");
};
String userId = "123";
User user = fetchUser.apply(userId);
System.out.println(user.getName()); // Output: John Doe
}
}
class User {
private String userId;
private String name;
private String email;
public User(String userId, String name, String email) {
this.userId = userId;
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
}
165. You are working on a task management application, and you need to filter a list of tasks based on their priority. How would you use the Predicate interface in Java to filter tasks marked as high priority?
The task-parameterized predicate interface can be used to define the lambda expression that indicates if the given task is a high priority or not. In our context, let me give you an example:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors; // Import Collectors
public class Main { // Removed 'class' keyword in the wrong place
public static void main(String[] args) {
List<Task> tasks = Arrays.asList(
new Task("Task 1", "High"),
new Task("Task 2", "Medium"),
new Task("Task 3", "High")
);
// Predicate to filter tasks with "High" priority
Predicate<Task> isHighPriority = task -> task.getPriority().equals("High");
// Using streams to filter tasks and collect them into a list
List<Task> highPriorityTasks = tasks.stream()
.filter(isHighPriority)
.collect(Collectors.toList());
// Printing the names of high-priority tasks
highPriorityTasks.forEach(task -> System.out.println(task.getName()));
// Output: Task 1, Task 3
}
}
class Task {
private String name;
private String priority;
public Task(String name, String priority) {
this.name = name;
this.priority = priority;
}
public String getName() {
return name;
}
public String getPriority() {
return priority;
}
}
Output:
Task 1
Task 3
166. Consider a scenario where you need to perform calculations on two numbers, such as addition, subtraction, multiplication, and division. How would you use the BiFunction interface in Java to implement these operations?
The BiFunction interface helps us to create an interconnection between two parameters that will be added, subtracted, multiplied, or divided according to a certain condition using appropriate arithmetic operators through lambdas in a few lines of code, as shown below.
import java.util.function.BiFunction;
class Main {
public static void main(String[] args) {
// Define BiFunction lambdas for arithmetic operations
BiFunction<Integer, Integer, Integer> add = Integer::sum;
BiFunction<Integer, Integer, Integer> subtract = (a, b) -> a - b;
BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b;
BiFunction<Integer, Integer, Integer> divide = (a, b) -> {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return a / b;
};
// Example calculations
System.out.println("Addition (10 + 20): " + add.apply(10, 20)); // Output: 30
System.out.println("Subtraction (200 - 100): " + subtract.apply(200, 100)); // Output: 100
System.out.println("Multiplication (200 * 100): " + multiply.apply(200, 100)); // Output: 20000
// Division with error handling
try {
System.out.println("Division (200 / 100): " + divide.apply(200, 100)); // Output: 2
System.out.println("Division (10 / 0): " + divide.apply(10, 0)); // Throws ArithmeticException
} catch (ArithmeticException e) {
System.err.println(e.getMessage());
}
}
}
Output: Division by zero is not allowed.
167. Suppose you are developing a web application that requires detailed logging of various events, such as user actions, system errors, and performance metrics. How would you implement a robust logging system using Java Lambdas to improve the readability and maintainability of your logging code?
To implement a robust logging system, Apache Log4j framework supporting Java Lambdas can provide an alternative solution that will enable writing more readable and clean logging code, as illustrated by the subsequent example of how to use Lambda expression with Log4j for debugging purposes.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
class WebApplication {
private static final Logger logger = LogManager.getLogger(WebApplication.class);
public void userAction(String action) {
logger.debug(() -> String.format("User performed action: %s", action));
}
public void systemError(String errorMessage) {
logger.error(() -> String.format("System error occurred: %s", errorMessage));
}
public void performanceMetric(String metric) {
logger.info(() -> String.format("Performance metric: %s", metric));
}
}
168. Your web application frequently accesses external resources, such as databases or APIs, which can throw exceptions. How would you handle exceptions gracefully to ensure your application can recover from errors and continue to function without disrupting the user experience?
In your method within a Web application development, try-catch blocks might have been used to handle expected exceptions gracefully. Moreover, we are also able to utilise lambda expressions to wrap up logic that might cause trouble, therefore making it easy for us during management and debugging processes when we need them most. For instance, handling SQLExceptions
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.function.Function;
class DatabaseAccess {
private Connection connection;
public DatabaseAccess() {
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("Failed to connect to database", e);
}
}
public void queryDatabase(String query, Function<ResultSet, Void> resultProcessor) {
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query)) {
resultProcessor.apply(resultSet);
} catch (SQLException e) {
logger.error(() -> String.format("Failed to execute query: %s", query), e);
// Handle the exception appropriately
}
}
}
169. Your high-traffic web application is experiencing performance issues, and you suspect that inefficient use of heap memory is the root cause. How would you optimise heap memory usage to improve application performance?
To reduce the use of heap memory, you have to be very careful about how object creation and disposal are managed, monitor memory usage, and adjust garbage collection parameters as per the requirements of your application. You can examine memory consumption using visual VM, YourKit, or jconsole, which helps identify memory bottlenecks. This will ensure that there are no more objects to be collected by the garbage collector if its tuning is done well.
170. Your large-scale data processing application frequently encounters OutOfMemoryError. How would you diagnose and resolve this issue to prevent application crashes?
When diagnosed with OutOfMemoryError, you must start by analysing the heap dump generated at that time. An OutOfMemoryError occurs and -XX:HeapDumpOnOutOfMemory parameter causes a heap dump file to be created. The Heap Dump will show you what objects are occupying the most space and never being reclaimed by the garbage collector, among other things. Furthermore, using the -verbose:gc option allows for the monitoring of garbage collection behaviour via its output. Based on this analysis, one can either increase JVM’s memory allocation towards an application’s optimisation, for instance, adjusting initial/maximum heap size, or better manage its internal patterns of memory use.
171. Your application requires low-latency processing, and you’re concerned about garbage collection pauses affecting performance. How would you implement a custom garbage collection strategy to minimise these pauses?
To minimise garbage collection pauses in an application with low latency, you might want to consider employing Z Garbage Collector (ZGC), which was introduced in Java 11. ZGC has been designed for applications that stress the need for responsiveness, minimising pause time during garbage collection. To use ZGC, a user needs to specify the -XX:+UseZGC option when starting a Java application. For instances where the system is required to handle huge memory sizes, it can continue collecting older objects without pausing for long durations.
172. Imagine you’re working on a large database application where performance is critical. You need to retrieve a large set of data from a database and then perform operations on this data. How would you choose the most efficient Java collection to store this data, considering the operations you need to perform?
If you have a large dataset retrieved from a database that may require operations like searching or sorting, then a TreeSet or LinkedHashSet would be a relevant option. TreeSet retains its elements in sorted order, which could be very useful if you need to perform any sorted operation on your data set. On the other hand, LinkedHashSet keeps the insertion order, which becomes useful if you care about the order of the elements in your operations. Nevertheless, if one needs frequent access by index ArrayList or LinkedList, it may make more sense as they have constant-time positional access even though their elements are not inherently sorted out.
173. You are tasked with implementing a multi-threaded caching system that can handle concurrent access to cached data. How would you use Java collections to ensure thread safety and efficient data access?
If you have a multithreaded caching system, it will likely use a ConcurrentHashMap to preserve the cached data. ConcurrentHashMap is designed for concurrent access without requiring external synchronisation, and thus, it is ideal for multi-threaded environments. This class also provides thread-safe operations like put(), get(), and remove(), which are important for any caching system that may have multiple threads reading or writing the cache at the same time. Additionally, if one wants to iterate through the map when it’s being modified, they can use keySet(), entrySet(), or values() methods provided by ConcurrentHashMap so that they obtain a collection view that can be modified concurrently.
174. Your web application needs to manage user sessions, ensuring that each user has a unique session ID and that session data is stored efficiently. How would you use Java collections to implement this feature?
In a web application, managing user sessions can be done with the help of a HashMap, where session data is stored, such as each session ID serving as a key and each session value given in return. By using session ID, you can retrieve your session data faster since this approach allows for the efficient retrieval of this kind of information from the server side. It may also be used conveniently where there are no requirements for maintaining any order over its elements, as HashMap does not maintain any order on its elements. If you want to keep session insertion ordered, LinkedHashMap is recommended because it maintains them according to their insertion order. This could enable developers to implement decisions like expiring sessions based on their creation times.
175. You are developing a task scheduling system where tasks have different priorities. How would you use Java collections to implement a priority queue that efficiently handles tasks based on their priority?
A PriorityQueue could be used to execute a priority queue for task scheduling. The elements of the PriorityQueue are sorted by their natural order or with a custom comparator passed when constructing the queue. This is ideal for managing tasks based on priority since those at a higher position are dequeued first. The class PriorityQueue has efficient enqueue and dequeue operations that make it useful for a task scheduling system that processes tasks according to their priority.
176. You are building an e-commerce application where users can add items to their shopping cart. How would you use Java collections to implement the shopping cart feature, ensuring that each user has a unique shopping cart and that items within the cart are uniquely identified?
In an e-commerce application, this feature can be done using a HashMap where each key represents a user ID, and the value is another collection, such as HashSet or LinkedList, showing items in users’ shopping carts. It helps avoid adding duplicate items, as each item is only represented once in the cart with the help of HashSet, which does not allow duplicates. If you want to add items while keeping track of insertion order, then consider using LinkedList because it maintains insertion order among its elements. This method enables additions and retrievals from shopping carts to be made more effectively and concurrently ensures the uniqueness of every item there.
Java MCQ Interview Questions
177. What is the size of float and double in Java?
- 32bits and 64bits
- 32bits and 31bits
- 64bits and 69bits
- 64bits and 32bits
Ans: A. 32 and 64
178. Automatic type conversion is possible in which of the possible cases?
- Byte to float
- Byte to long
- Int to long
- Long to byte
Ans: C. Int to long
179. What is the output of the snippet:
int Int = 20;
System.out.println(Int);
- Compiler error
- Runtime error
- 224
- 20
Ans D. 20
180. On passing an array to a method, what does the method receive?
- Reference to memory
- Copy of array
- Length of array
- Reference of array
Ans: D. Reference of array
181. Which is the valid statement to declare and initialise an array?
- int[] A = {}
- int[] A = {1,2,3}
- int[] A = {134)
- int[] A = (1,3,5)
Ans: B. int[] A = {1,2,3}
182. Arrays in Java are:
- Objects reference
- Objects
- Data type
- All of the above
Ans: B. Objects
183. When is the object created with a new keyword?
- At run time
- At compile time
- Depends on code
- None
Ans: A. At run time
184. Identify the correct statement.
- Package is a collection of editing tools package is a collection of goods
- Package is a collection of classes and interfaces
- All of the above
Ans: C. Package is a collection of classes and interfaces
185. compareTo() returns
- True
- False
- An int value
- None
Ans: C. An int value
186. Which is the string class:
- java.lang
- java.awt
- java.applet
- java.string
Ans: A. java.lang
187. Total constructor in string class:
- 3
- 7
- 13
- 20
Ans: C. 13
188. Return type of method that doesn’t return any value:
- int
- void
- double
- None
Ans: B. void
189. Who invented Java Programming?
- Guido van Rossum
- James Gosling
- Dennis Ritchie
- Bjarne Stroustrup
Ans: B. James Gosling
190. What are the number of primitive data types in Java?
- 6
- 7
- 8
- 9
Ans: C. 8
191. Which component is used to compile, debug and execute the Java programs?
- JRE
- JIT
- JDK
- JVM
Ans: C. JDK
192. Which environment variable sets the Java path?
- My_Path
- JPATH
- JHTTP
- JAVA_HOME
Ans: D. JAVA_HOME
193. What is the output:
class Intellipaat {
public static void main(String args[])
{
double e, f,g;
e = 3.0/0;
f = 0/4.0;
g=0/0.0;
System.out.println(e);
}
}
- 0
- 12
- Zero Division Error
- All of the above
Ans: C. Zero Division Error
194. Find out the error:
class variable_scope
{
public static void main(String args[])
{
int x;
x = 5;
{
int y = 6;
System.out.print(x " " + y);
}
System.out.println(x " " + y);
}
}
- System.out.print(x ” ” + y);and System.out.println(x ” ” + y);
- x = 5; and int y = 6;
- Y is not accessible in the code
- Both A and C
Ans: D. Both A and C
195. State error:
Byte a = 10;
a = a * 10;
- Variable a can’t have value 10.
- Variable a can’t have a value of 100
- error incompatible types: int cannot be converted to Byte
- Multiplication operator converts the data type to Int
Ans: C. error incompatible types: int cannot be converted to Byte
196. Fill in the missing code
class MissingCodeSnippet {
public static void main(String[] args) {
int x = 5;
int y = 3;
// Missing code snippet
System.out.println("Result: " + z);
}
}
- int z = x +y;
- int z = x – y;
- int z = x * y;
- All of above
Ans: D. All of the above
197. Select the correct option:
class Palindrome {
// Function to check if a string is palindrome
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() – 1;
while (left < right) { if (str.charAt(left) != str.charAt(right)) { return false; } left++; right--; } return true; } public static void main(String[] args) { String option1 = "racecar";
String option2 = "hello";
String option3 = "level";
String option4 = "world";
System.out.println("Option 1 is palindrome: " + isPalindrome(option1)); }
}
- isPalindrome(option1)
- isPalindrome(option2)
- isPalindrome(option3)
- isPalindrome(option4)
Ans: A. isPalindrome(option1)
198. What is ‘Truncation’?
- Giving a floating point to an integer type
- Assigning a floating-point value to an integer type.
- Assigning an integer value to a floating type
- Assigning an integer value to a floating type.
Ans:
- Assigning an integer value to a floating type.
199. Which is the out of memory exception:
- MemoryErrorOut
- OutOfMemoryError
- Memoryoutofindex
- None
Ans: B. OutOfMemoryError
200. Selection statements of Java are:
- break
- continue
- for()
- if()
Ans: D. if()
201. Which is the superclass of every Java class:
- ArrayList
- Abstract class
- Object class
- String
Ans: C. Object class
202. Give output
class ArraySum {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum of elements: " + sum);
}
}
- Sum of elements: 15
- Sum of elements: 10
- Sum of elements: 0
- Sum of elements: 25
Ans: A. Sum of elements: 15
203. Output of the code:
class StringConcatenation {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String result = str1 + str2;
System.out.println(result);
}
}
- Hello World
- HelloWorld
- Hello + World
- Compilation error
Ans: B. HelloWorld
204. Code gives
class ArrayLength {
public static void main(String[] args) {
int[] numbers = new int[5];
System.out.println("Length of array: " + numbers.length);
}
}
- Length of array: 0
- Length of array: 5
- Length of array: 1
- Compilation error
Ans: B. Length of array:5
I hope this set of Java Interview Questions will help you prepare for your interviews. Best of luck in your endeavours!