0% found this document useful (0 votes)
2 views

Java Interview question

The document contains a comprehensive list of Java interview questions and answers covering various topics such as object-oriented programming, Java's compilation process, immutability of strings, marker interfaces, and collection frameworks. It explains key concepts like ArrayList, LinkedList, Vector, Stack, and Queue interfaces, along with their differences and usage scenarios. Additionally, it addresses important characteristics of Java, such as the absence of pointers and the significance of the JIT compiler.

Uploaded by

Ashlesha Karande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Interview question

The document contains a comprehensive list of Java interview questions and answers covering various topics such as object-oriented programming, Java's compilation process, immutability of strings, marker interfaces, and collection frameworks. It explains key concepts like ArrayList, LinkedList, Vector, Stack, and Queue interfaces, along with their differences and usage scenarios. Additionally, it addresses important characteristics of Java, such as the absence of pointers and the significance of the JIT compiler.

Uploaded by

Ashlesha Karande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Java Interview Questions

1.why java is not a 100% object oriented programming language.

• Because we have a primitive data types like byte,int,float,char,Boolean,long, short.


• To make them object oriented we have wrapper classes which actually wrap the primitive data types into
an object of that class.

2.why pointers are not used in java.

• They are unsafe.


• Increases the complexity of the program and since java is known for the simplicity of the code.

3.what is JIT(just-In-Time) compiler,interpreter,compiler

• JDK stands for Java Development Kit. It is a software development kit used by Java developers to
create Java applications.

Aspect Compiler Interpreter JIT Compiler


Translates entire code at Executes code line-by- Optimizes and compiles
Type once line bytecode at runtime
Generates machine- No intermediate code Compiles bytecode to machine
Output independent bytecode generation code
Part of the JVM, compiles
Examples in javac is the Java compiler JVM interprets Java frequently used bytecode to
Java that produces .class files bytecode line-by-line machine code

4. java source code to machine code execution process in short?

• 1.first we creating the .java source code file.


• 2.Then Java source code (.java files) is compiled by the Java compiler (javac) into bytecode
(.class files)
• 3. The Java Virtual Machine (JVM) interprets and executes this bytecode into machine
code.

5.why string is immutable in java?

Immutable-you cannot modify once you create an object.

• String pool requires string to be immutable otherwise shared references can be changed from
anywhere.
• In real-world applications, the data type used for passwords is typically a string of
characters.
• Security because string is shared on different areas like security,networking
connection,database connection,having immutable string allows you to be secure and
safe because no one can change the references of string once it get created.

6.what is marker interface?

• Marker interface is the one type of interface having no data members or member functions.
• In simplest term,empty interface is called the marker interface.
• Eg-serializable,clonable

7.why marker interface in java is important?

• They serve as a marker or a flag to the compiler or runtime environment, indicating


something about the classes that implement them.
• Marker interfaces help categorize or identify classes at runtime.
• For instance, the Serializable interface in Java marks classes that can be serialized.

8.can you override the static and private methods in java?

• No,you cannot override the private or static method in java.


• You cannot override private methods in subclasses because it is not accessible there,what
you do create another private method with same name in child class.
• For static method,if we creating same method with same return type and same argument in
child class then it will hide the super class method,it is known as the method hiding.

9.does finally always execute in java?

• There are the two cases the finally keyword is not excuted
• 1.whenever our system is crashes then finally keyword is not executed.
• Execution of explicit function like”System.exit()”function finally keyword is not executed.

10.what methods does the object class have?

• There are the three methods of java.lang.object class.


• 1.clone() mehod-creates and returns the copy of this object.
• 2.equals() method-Indicates whether some objects are “equals to”this one;
• 3.finalize() method-this is called the garbage collector determines threre are no more references
to the objects.
• 4.getclass() method-returns the runtime class of an objects.
• 5.hash code()=return hash code value to object.
• 6.tostring()=returning the string representation of an object.

11.How can you make a class immutable?

• Declare a class final so it cannot be extended.


• Make all fields private so that direct access is not alloweded.
• Make all mutable fields are final so that its value can be assigned only once.
• Don’t’ provide setter method for variables.
12.singletone class?

• Singletone class is the class whose only one instance is created at the given time in one
jvm.

public class Singleton {


// Private static variable to hold the single instance of the class
private static Singleton instance;

// Private constructor to prevent instantiation from outside the class


private Singleton() {
// Constructor implementation
}

// Public static method to provide access to the single instance


public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
• }

13.Explain the collection Hierarchy?

• Java.util.collection is the root of the java collection framework and the most of the
collections are inheriated from the set,List.Queue interfaces except Map interface.
1. Java.util.List
• Contains the ordered elements
• May include the duplicates
• Supports the index based search.
2.java.util.Set
• Does not support the ordered elements
• Doesn’t includes the duplicates
• Does not supports the index based search
3.java.util.queue
• Queue follows the FIFO order
• In queue we adding the elements at rear end and removing the elements from front end
4.java.util.Map
• Map representing the key-value pair
• Map interface does not representing the collections
• It can only contains the unique key
• Can have duplicates value.

14.Explain the List Interfaces?

1.ArrayList-

• ArrayList is a dynamic array that can dynamically grow size while implementing the List interface.
• It allows dynamic resizing, adding, removing, and accessing elements based on their
indices.
2.How is ArrayList different from arrays in Java?

• Arrays have a fixed size that needs to be declared at the time of creation, whereas ArrayList can
dynamically resize itself.
• ArrayList provides methods to add, remove, and manipulate elements easily compared
to arrays.

3. How to create an ArrayList in Java?

• Syntax: ArrayList<String> arrayList = new ArrayList<>();

4. How to add elements to an ArrayList?

• You can add elements to an ArrayList using the add() method:


• arrayList.add("Element 1");
• arrayList.add("Element 2");

5. How to remove elements from an ArrayList?

• You can remove elements by index or by object:


• // Remove by index
• arrayList.remove(0);

• // Remove by object
• arrayList.remove("Element 2");

6. How to iterate through an ArrayList?

• You can iterate through an ArrayList using various methods, such as a traditional for loop, an
enhanced for loop or using iterators:
• // Using a traditional for loop
• for (int i = 0; i < arrayList.size(); i++) {
• System.out.println(arrayList.get(i));
• }

• // Using an enhanced for loop
• for (String element : arrayList) {
• System.out.println(element);
• }

• // Using iterators
• Iterator<String> iterator = arrayList.iterator();
• while (iterator.hasNext()) {
• System.out.println(iterator.next());
• }

7. Can ArrayList store primitive data types?


• No, ArrayList can only store objects
• However, Java provides wrapper classes like Integer, Double, etc., that can be used to
store primitive data types in ArrayList.

8. What is the initial capacity of an ArrayList?

• By default, when an ArrayList is created using the ArrayList() constructor without


specifying initial capacity, it starts with an initial capacity of 10.

9. How to check if an ArrayList is empty?

• You can use the isEmpty() method to check if an ArrayList is empty or not:
• if (arrayList.isEmpty()) {
• System.out.println("ArrayList is empty");
• } else {
• System.out.println("ArrayList is not empty");
• }

10. Is ArrayList thread-safe?

• No, ArrayList is not thread-safe. If multiple threads access an ArrayList concurrently and at least
one of the threads modifies the list structurally, it must be synchronized externally.

15.what is LinkedList?

1. What is a LinkedList in Java?

• LinkedList in Java is a linear data structure that consists of elements where each element
points to the next one using a pointer. It implements the List and Deque interfaces.

2. How is LinkedList different from ArrayList?

• Storage: ArrayList internally uses an array to store elements, while LinkedList


uses a doubly linked list.
• Performance: ArrayList is more efficient for random access (getting elements by
index), whereas LinkedList is better for frequent insertion and deletion
operations.

3. How to create a LinkedList in Java?

• You can create a LinkedList using the following syntax:


• LinkedList<String> linkedList = new LinkedList<>();

4. How to add elements to a LinkedList?

• Elements can be added to a LinkedList using the add() method:


• linkedList.add("Element 1");
• linkedList.add("Element 2");

5. How to remove elements from a LinkedList?


• Elements can be removed by index or by object using the remove() method:
• // Remove by index
• linkedList.remove(0);

• // Remove by object
• linkedList.remove("Element 2");

6. What is the difference between add() and offer() methods in LinkedList?

• Both add() and offer() methods are used to add elements. However, add() throws
an exception if the element cannot be added, whereas offer() returns false if the
element cannot be added (e.g., in the case of a capacity-restricted queue).

7. When to use ArrayList over LinkedList and vice versa?

• ArrayList: Use it when you require fast random access to elements or when the list size is known
and relatively constant.
• LinkedList: Use it when frequent insertion/deletion operations are required, especially at the
beginning or middle of the list, or when the size of the list might change frequently.

16.what is the vector?

• Vector is a legacy class in Java that implements a dynamic array that can grow or shrink in
size. It's similar to ArrayList but is synchronized.
1. How is Vector different from ArrayList?
• Thread Safety: Vector is synchronized, making it thread-safe. Operations on a Vector are
synchronized by default, whereas ArrayList is not synchronized.
• Performance: Due to synchronization, Vector might be slower than ArrayList in a single-
threaded environment.
• Growth: Vector doubles its array size by default when it needs to grow, while ArrayList
increases by 50% of the current size.
2. How to create a Vector in Java?
• You can create a Vector in Java using the following syntax:
• Vector<String> vector = new Vector<>();
3. How to add elements to a Vector?
• Elements can be added to a Vector using the add() method:
• vector.add("Element 1");
• vector.add("Element 2");
4. How to remove elements from a Vector?
• You can remove elements from a Vector by index or by object:

• // Remove by index
• vector.remove(0);

• // Remove by object
• vector.remove("Element 2");
5. How to iterate through a Vector?

Iteration through a Vector can be done similarly to an ArrayList using different types of loops or
iterators:

// Using a traditional for loop

for (int i = 0; i < vector.size(); i++) {

System.out.println(vector.get(i));

// Using an enhanced for loop

for (String element : vector) {

System.out.println(element);

// Using iterators

Iterator<String> iterator = vector.iterator();

while (iterator.hasNext()) {

System.out.println(iterator.next());

6. Is Vector thread-safe?

Yes, Vector is thread-safe because its methods are synchronized, making it safer to use in
multithreaded environments

7. Is Vector recommended for modern Java development?

No, Vector is considered a legacy class, and for most modern scenarios, using ArrayList along with
proper synchronization mechanisms (if needed) is preferred due to better performance.

8. What is the initial capacity of a Vector?

Similar to ArrayList, if you create a Vector without specifying an initial capacity, it starts with an
initial capacity of 10.

9. Can a Vector store primitive data types?

No, like ArrayList, Vector can only store objects. You can use wrapper classes like Integer, Double,
etc., to store primitive data types in a Vector.

17.what is the stack?


A Stack is a data structure that follows the Last In, First Out (LIFO) principle, where elements are
inserted and removed from the same end, known as the "top" of the stack.

2. How to create a Stack in Java?

You can create a Stack in Java using the java.util.Stack class:

Stack<Integer> stack = new Stack<>();

3. How to push elements onto a Stack?

You can add elements to the top of the Stack using the push() method:

stack.push(5);

stack.push(10);

4. How to pop elements from a Stack?

Elements can be removed from the top of the Stack using the pop() method:

int poppedElement = stack.pop();

This removes the top element from the Stack and returns it.

5. How to check the element at the top of the Stack without removing it?

You can inspect the element at the top of the Stack without removing it using the peek() method:

int topElement = stack.peek();

6. What happens if pop() or peek() is called on an empty Stack?

Calling pop() on an empty Stack results in an EmptyStackException. Similarly, calling peek() on an


empty Stack will also throw an EmptyStackException.

7. Is Stack in Java thread-safe?

The Stack class in Java is inherited from Vector, which is synchronized and therefore thread-safe.

8. How to check if a Stack is empty?

You can use the empty() method to check if a Stack is empty:

if (stack.empty()) {

// Stack is empty

} else {

// Stack is not empty


}

9. Can a Stack contain null elements?

Yes, a Stack in Java can contain null elements since it's designed to hold any object references.

10. What are some applications of a Stack data structure?

Function Call Stack: Used in programming languages to manage function calls.

Expression Evaluation: Used in evaluating expressions, infix to postfix conversion, etc.

Undo Functionality: In software applications to implement undo functionality.

18.what is the set interfaces in java?

• In java,the java.util.set interface represents the collection that doesn’t allow the duplicate
elements.
• Common implementations includes HashSet,LinkedHashSet,TreeSet.

1.Hashset-

• It implicitly implements a hashtable.


• Contain only unique elements.
• Only one null element can be added.
• It is in unordered fashion.

2.Linked Hashset

• Ordered version of the Hashset which maintains the doubly linked list across all elements.

3.sorted set-

• All the elements in sorted set must implements the comparable interface.
• It’s a set sorted in asending order.
4.Tree set
• A TreeSet in Java is an implementation of the Set interface that uses a tree for storage,
specifically a Red-Black tree
• It maintains elements in sorted order and does not allow duplicates.

19.Queue interfaces in java?

• Queue interface follows the first in first out order.


• In queue elements are added in rear end and the removed from the front end.
• Real world applications-
• 1.Messaging system-in system queue manages and processing the orderly delivery of
messages.
• 2.task scheduling-job scheduling systems like cron use queue to manage and execute
scheduled task.

1.where to use queue in the whatsapp?

• Message sending-when you send the message,it might go through a queue to manage
the order of sending a messge.
• Notifications-queue might handle the delivery of notifications.
• Offline messages-if the recipient is offline,messages could be queued for delivery once
they come online,maintaining the order of messages.

2.priority Queue-

• Priority queue is a queue with priority associated with each element.


• High priority elements is served before a low priority elements irrespective of their insertion order.
• Real world applications-

1.operating system-managing the processes with different priorities.

2.networking-Managing the networks.

3.DeQueue-

• In java a Deque(double-ended queue)is a linear collection that supports adding and removing
elements from both ends.
• The dequeue interface provides the various methods like
addFirst,addLast,removeFirst,removeLast.

4.Arraydeque-

• In java,the arrayDeque class implements the deque interface using a resizable array.
• In array deque there is no capacity restrictions.

20.Map interface-

• In java ,Map interface is the part of the java.util.package represents the collection of
key-value pair where each key is unique.
• Map interface implements the hashtable,Hash Map,sorted Map,Tree Map.

1.HashMap-

• It is non-synchronised in nature.
• Allows only one null key but multiple null values.
2.Hash Table-
➢ It is syncronised in nature.
➢ Doesn’t allow any null key or value.

3.sorted Map

➢ In sored map all entries are maintained in asending key order.


4.Tree Map
➢ Implicitly implements the red -black tree.
➢ Implementation cannot store any null key.

21.why map doesn’t extends the collection interface?

➢ Map interface supports the key-value pair whereas the collection interface is collection of objects
which are stored in structurd manner with a specified access mechanism.
➢ The main reason Map doesn’t extends the collection interface is that add (E,e) method of the
collection interface doesn’t’ support the key-value pair like map interface’s put(k,V)method.

22.difference between the fail-fast and fail-safe iterators.

➢ Fail-fast iterators throws the concurrentmodificationException when one thread iterating over the
collection object and other thread structurally modify collection object either adding,removing
and modyifying objct underlying the collection.they are called fail -fast iterators because they try
to immediately throw exception when they encounter the failure.
➢ Fail-safe iterators doesn’t’ throw the any exception because they work on collection of clone
insead of original collection.

23.what do you understand by blockingQueue?

➢ The java bloking queue interface ,java.util.concurrent.BlockingQueue,represents the queue which


is thread safe to put elements into and taking elements out of from.
➢ In other words ,multiple threads are inserting and taking elements concurrently from java
queue,without any concurrency issue arising.

24.difference between the syncronised collection and concurrent collection.

➢ Both of them are used in thread-safety.


➢ 1.Syncronised collection-

➢ Now, we will see what is synchronize? Here, synchronize means only one thread is allowed to
operate on an object at a time or in other words the object(which is synchronized) can't be
modified by multiple threads simultaneously.
➢ Synchronized Collection can be modified by one thread at a time

➢ Synchronized Collection has low performance than Concurrent Collection because


at a time only one thread is allowed to operate on an object so it increases the
waiting time of the threads.
➢ 2.concurrent collection-
➢ Now, we will see what is Concurrent? Here, concurrent means only multiple threads are
allowed to operate on an object at a time or in other words the object (which is concurrent)
can be modified by multiple threads simultaneously.
➢ Concurrent Collection can be modified by multiple threads at a
time(i.e. it is possible to modify or access Concurrent Collection by
multiple threads simultaneously).
➢ Concurrent Collection has high performance than Synchronized
Collection because at a time multiple threads are allowed to operate on
an object so it decreases the waiting time of the threads.

25.Internal working of Hashmap

➢ Hash map in java work on hashing principle where hash functions are used to link key and
value in Hashmap.
➢ Objects are stored by using put method(key,value)of hash Map and retrived by using the
get(key)method .

26.java is pass by value/pass by references.


• In Java, the answer is that it's "pass by value."
• Pass by value: When you pass a primitive data type (like int, float, char, etc.) or an
object reference to a method in Java, you're actually passing a copy of the value. For
primitive types, the value itself is passed, while for objects, the reference to the object
is passed by value.
• // Pass by value with primitive types
• public void modifyPrimitive(int x) {
• x = 5;
• }

• public static void main(String[] args) {
• int num = 10;
• modifyPrimitive(num);
• System.out.println(num); // Output will be 10, as num remains unchanged
• }

// Pass by value with objects

public class MyClass {

int value;

public MyClass(int value) {

this.value = value;

}public void modifyObjectReference(MyClass obj) {

obj.value = 5;

}
public static void main(String[] args) {

MyClass obj = new MyClass(10);

modifyObjectReference(obj);

System.out.println(obj.value); // Output will be 5, as the object's value is modified

27.why are comparable and comparator interfaces are required in java?

• The Comparable and Comparator interfaces in Java serve critical roles in enabling object
comparison and sorting within collections.
• 1. Comparable Interface:
➢ Comparable is an interface that allows a class to implement its natural ordering of
objects.
➢ When a class implements Comparable, it defines a way to compare its instances
with each other.
➢ this interface is particularly useful in situations where you want to define a default
way of sorting objects of your class.
➢ public class Student implements Comparable<Student> {
➢ private int rollNumber;
➢ // Other fields and methods

➢ @Override
➢ public int compareTo(Student otherStudent) {
➢ return Integer.compare(this.rollNumber, otherStudent.rollNumber);
➢ }
➢ }

2.comparator interface

➢ Purpose: Comparator provides a way to sort objects without modifying their


original class implementation
➢ It allows for multiple comparison strategies.
➢ Sorting objects based on different criteria at different times without modifying the
original class (e.g., sorting Student objects by name, age, or grade).
➢ public class StudentComparator implements Comparator<Student> {
➢ @Override
➢ public int compare(Student s1, Student s2) {
➢ return s1.getName().compareTo(s2.getName());
➢ }
➢ }

28.Equals and Hash code contracts.


➢ If the two objects are same according to the equals method then hash code of both objects must
be the same.
➢ It is not necessary that if you have same hash code for 2 objects means those two objects are
equal.This is collision.

29. what is the difference between equal method and == operator in java tabular formats

Aspect equals() method == operator


Usage Used to compare the content of objects. Used to compare the references of objects.
Checks if two objects have the same Checks if two object references are the
Purpose content. same.
Syntax object1.equals(object2) object1 == object2

30.can we restrict the visibility of derived method in java? Or What if method in child class is more
restricted than parent class

❖ If a method in a child class has more restricted access (e.g., declared as private) than its
counterpart in the parent class (e.g., declared as protected or public), it's considered a new
method in the child class, not an override

31. What is Java?

Java is a platform-independent high-level programming language. It is platform-independent


because its byte codes can run on any system regardless of its operating system.It is widely used
in various web applications, mobile applications. Java syntax is user friendly and it allows for easy
scalability and robustness in creating applications.

32. In Java, what are the differences between heap and stack memory?

Memory

Stack memory is used only by one thread of execution.

All the parts of the application use heap memory.

Access

Other threads can’t access stack memory.

Objects stored in the heap are globally accessible.Usage


Stack memory only contains local primitive and reference variables to objects in heap space.

Whenever you create an object, it is always stored away in the heap space.

32. What is an inner class?

An inner class is a class that is nested within another class.

33. What is a subclass?

A subclass is a class that inherits from another class called the superclass. Subclass can access all
public and protected methods and fields of its superclass.

34. How can developers use packages in Java?

Packages in Java allow developers to modularize the code and optimize its reuse easily

35. What are the advantages of packages in Java?

Packages help developers avoid name clashes.

Packages provide easier access control.

Packages can also contain hidden classes that are not visible to the outer classes and are only
used within the package.

❖ 36.shadowing variable in java?


➢ Shodowing occurs when two variables with different scope share the same name.
➢ This leads to hard to find bugs and makes code less reusable.
➢ Local variable shadows the instance variable inside a class method.
➢ Example-:
➢ public class emp {
➢ static int num1=12; //shadowing variable
➢ public static void main(String [] args)
➢ {
➢ int e=add(12);
➢ System.out.println(e);
➢ int f=sub(12);
➢ System.out.println(f);
➢ }
➢ public static int add(int num2)
➢ {
➢ int c=num1+num2;
➢ return c;
➢ }
➢ private static int sub(int num3)
➢ {
➢ int d=num3-num1;
➢ return d;
➢ }

➢ }

37. Association(HAS-A) Aggregation And Composition in Java

➢ Association represents the relationship between two classes. In this relationship, one class is
related to another class, often through their objects, but there's no ownership or lifecycle
dependency between them. The classes are simply connected.
➢ Eg-
➢ Consider a Student class and a School class. A student is associated with a school, but the student
and the school exist independently of each other.
➢ public class Student {
➢ private String name;
➢ private int age;

➢ // Other student attributes and methods

➢ // Association with School class
➢ private School school;

➢ // Constructor, getters, setters for Student
➢ }

➢ public class School {
➢ private String name;
➢ private String location;

➢ // Other school attributes and methods

➢ // Constructor, getters, setters for School
➢ }
❖ Aggregation:
➢ Aggregation is the one of the type of association where child can exists independently
whole part of parents.
➢ It represents a "has-a" relationship
➢ Eg-

Consider Department as a part of the University.

public class University {

private String name;

private List<Department> departments;


// Other university attributes and methods

// Constructor, getters, setters for University

public class Department {

private String name;

private String headOfDepartment;

// Other department attributes and methods

// Constructor, getters, setters for Department

❖ Composition-
➢ Composition is a stronger form of aggregation where the part (child) cannot
exist without the whole (parent). If the parent object is destroyed, all its child
objects are destroyed as well.
➢ Consider Car and Engine.
➢ public class Car {
➢ private String make;
➢ private String model;
➢ private Engine engine; // Composition relationship

➢ // Other car attributes and methods

➢ // Constructor, getters, setters for Car
➢ }

➢ public class Engine {
➢ private String type;
➢ private int horsepower;

➢ // Other engine attributes and methods

➢ // Constructor, getters, setters for Engine
➢ }

38.covarient return types in java?

➢ Before this concept generally we cannot changing the return type of overridden
method.but new concept are introduced in java is known as covariant return type where
we can changing the return types of overridden methods in subclasses.
➢ class cov
➢ {
➢ cov show()
➢ {
➢ System.out.println("this is the super class method");
➢ return this;//this refering the current object
➢ }
➢ }
➢ class B extends cov
➢ {
➢ @Override

➢ B show()
➢ {
➢ super.show();
➢ System.out.println("using the covariant return type we changing the return type of
override methods");
➢ return this;
➢ }
➢ }
➢ class Test
➢ {
➢ public static void main(String[] args)
➢ {
➢ B b=new B();
➢ b.show();
➢ }
➢ }

39.what is an exception?
➢ Exception is an abnormal condition which occurs during the execution of a program
and disrupts normal flow of the program.

39.Type promotion in java?

❖ The name Type Promotion specifies that a small size datatype can
be promoted to a large size datatype. i.e., an Integer data type can
be promoted to long, float, double, etc.
❖ This Automatic Type Promotion is done when any method which
accepts a higher size data type argument is called with the smaller
data type.

Example 1: In this example, we are testing the automatic type


promotion from small size datatype to high size datatype.
class GFG {

// A method that accept double as parameter


public static void method(double d)
{
System.out.println(
"Automatic Type Promoted to Double-" + d);
}

public static void main(String[] args)


{
// method call with int as parameter
method(2);
}
}
40.New features in java.
1.why java8?Main agenda behind the java 8?
❖ Java 8 provides the conciseness in code.
❖ Java brings in functional programming which is enabled by Lambda expressions.
❖ Main agenda behind the java 8 is to make coding easier and more efficient for
java developers.

2.what are the new features which are got introduced in java8?

❖ Lambda Expression
❖ Stream API
❖ Default methods in the interface
❖ Static methods
❖ Functional interface
❖ Optional
❖ Method references
❖ Date API
❖ Javascript Engine

3.what are the main advantage of using java 8?


❖ Create less line of code.
❖ Parallel operations are possible
❖ Creating the more readable and reusable code
❖ More testable code

4.what is lambda expression in java 8?


❖ Lambda expression is an anonymous function without name,return type and
access modifier and having one lambda(->) symbol.
❖ Example-
❖ Normal programming technique-
Public void add(int a,int b)
{
System.out.println(a+b);
}
❖ Equivalent lambda expression-

(a,b) ->system.out.println(a+b);

5.write the addition code using lambda expression?


interface Addition {

int add(int a, int b);

public class Main {

public static void main(String[] args) {

Addition addition = (a, b) -> a + b;

int result = addition.add(5, 3);

System.out.println("The sum is: " + result);

6.what are functional interfaces?

❖ Functional interfaces are those interfaces which can have only one abstract
method.
❖ It can have any number of static methods,default methods.No restriction on that.
❖ There are many functional interfaces are already present in java such as
eg:comparable,Runnable.

7.How lambda expression and functional interface are related?

❖ Functional interface are used to provide the references to lambda expression.

8.can you create your own functional interface?

❖ Yes ,you can create your own functional interface.


❖ To create your own functional interface.you can do following steps.
1.create an interface.
2.Annotate that with @FunctionalInterface.
3.define exactly one abstract method
4.there is no restriction on number of static and default methods defined in such
and interface.
9.what is method reference in java 8?
❖ Method references is the replacement of lambda expression.
❖ Mainly it is used in code reusability.
❖ Functional Interface’s Abstract method can be mapped to specific existing
method using double colon operator(::).This is Method reference.

10.write the code of method references in java?


// Static method in a class
class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
// Reference to the static method using ClassName::methodName
BiFunction<Integer, Integer, Integer> addFunction = MathUtils::add;

int result = addFunction.apply(5, 3);


System.out.println("The sum is: " + result);
}
}

41.what are defaults methods?

❖ Default method is a way of adding new methods to the interface without affecting the
implementing classes.
❖ This defaults methods are used in “Backward Compatibility”which means if JDK modifies
any interface(without default method)then the classes which implements this interface
will break.

42.Is it necessary to override default methods?

❖ Default methods are dummy implementations.


❖ If the implementing classes does not satisfy the defaults methods then they can override
and provide their own implementation.

43.is default keyword one of the access modifier?

❖ No, keyword is not access modifier like public or protected or private.


❖ For default access modifier we do not use any keyword.

44.how to override the defaults methods?


❖ You can override default method by keeping same method signature(name+arguments)
❖ You cannot use default keyword in class.
❖ By default all the methods are public so in child you cannot reduce visibility of
overridden default methods.

45.can you use hashcode() default implementation in interface.

❖ You cannot give your default implementation of hashcode() in interface for all
implementing classes to use.
❖ We are not allowed to override objects class method as default methods in interface
else will get compile time error.

46.How default methods in interface cope up with Diamond problem.

• If two implemented interfaces contains same default methods then that’s the
diamond problem
• In java ,in such situation,The code will not compile.
• Solution to diamond problems-
• 1.use Interface Name.super.methodName();

47.why static methods were introduced in java 8?

❖ Only reason for creating the static methods in interfaces is that you can call
those methods with just interface name.no need to create class and then its
object.
❖ Classes are more costly in terms of memory and performance.
❖ Interface can never contain:
• Constructors
• Static blocks
• Nothings costly in terms of memory and performance.

48.are static methods available to implementing classes by default?

❖ Static methods are not available to implementing classes.


❖ They are not default methods.They are static.

49.what are predicates?

❖ Predicate is a predefined Functional Interface(having only one abstract


method)
❖ The only abstract method of predicate is test(T t);
• Public Boolean test(T t);
❖ Whenever we want to check some Boolean condition then you can
go for predicates.
50.write the code of predicate function?

// Java program to illustrate Simple Predicate

import java.util.function.Predicate;

public class PredicateInterfaceExample1 {

public static void main(String[] args)

// Creating predicate

Predicate<Integer> lesserthan = i -> (i < 18);

// Calling Predicate method

System.out.println(lesserthan.test(10));

}
}
51.how to use the predicates?
I. If you need to test if the length of the string is greater than or equal to 5.Then in such situation
where you need to test condition,use test() method of predicate.
52.Type parameter and return types of predicates?
❖ Input to predicate can be anything like
• Predicate<String>
• Predicate<Integer>
• Predicate<Employee>
❖ Only one argument is required which is input type in predicate.
❖ Return type of the predicate is only Boolean.
53.Advantages of Predicates?
❖ Code Reusability
❖ If you have same condition being used 100 times in a program then you can write once and just
use 100 times with checkLength.test(different string to be tested)
❖ Conditional checks are holded by Functional interfaces.
54.what is predicate joining?
❖ In predicate joining you can combine the predicates in serial predicate.
❖ There are the three ways to join the predicates:
• And
• Or
• Negate
❖ Eg-if you want to test 2 conditions
• To check the length of string>5
• To check if length is even.
55.code of the predicate joining And,Or,Negate see the vs code java folder.
56.what are functions?
❖ Functions is also a predefined functional Interfaces(Having only 1 abstract method)
❖ The only abstract method of function is apply(T t)
• R apply(T t);
❖ This takes one input and return one output (not necessary to always Boolean value)
57.what is the difference between Predicate and Function?
1.It has return type as Boolean.It is used for conditional checks.
2.It has the return type as object.it is used to perform operations and return result.

2.It is written in the form of predicate<T>which accepts a single arguments.


2.It is written in form of function<T,R> which accept the single argument and return any type of object.

3.It contains the test() abstract method


3.It contains the apply() abstract method.

58.what is the functional chaining?


❖ We can combine multiple functions together with andThen method.
❖ There are two ways to combine functions:
• F1.andThen(f2).apply(Input):first f1 then f2
• F1.compose(f2).apply(input)-first f2 then f1
❖ Multiple functions can be chained together like:
❖ F1.andThen(f2).andThen(f3).andThen(f4).apply(Inputs);
59.what is consumer functional interface?
❖ Consumer functional interfaces consumes items.consumers never return anything,they just
consume.
❖ In contains the accept methodwe
❖ Example-
❖ Take any object and save its details in Database and don’t’ return anything.
❖ Interface Consumer<T>{
Public void accept(T t)
}
60.consumer functional interface example see the java folder.
61.what is Consumer chaining?
❖ In consumer chaining we combine multiple consumers together using andThen method.
❖ There is only one ways to combine consumers:
❖ C1.andThen(c2).apply(Input);-first c1 then c2.
❖ No compose() in consumer.
❖ Multiple consumers can be chained together like:
C1.andThen(c2).andThen(c3).andThen(c4).apply(Inputs);
62.what is supplier Functional interface?
❖ Supplier Functional interface always supply the required objects.
❖ In contains the get() method
❖ Example:
Always supply me current date.
Interface Supplier<R>
{
Public R get();
}
❖ It does not take any input,does not consumes the items,only gives you the output.
63.Advantages of Supplier?
❖ Code Reusability
❖ Write once,use anywhere.
64.use of biconsumer BiFunction,BiPredicate and why no bisupplier?
❖ We need Bi xyz in functional interfaces.
❖ There is no input in supplier so no 1 or 2 Input arguments needed.Hence no BiSupplier.
65.if we want to operate on 3 arguments then tripredicate?
❖ There are no Tripredicate or trifunction
66. Introduction to java Streams API-
1.The stream API are related to the collection Frameworks/group of objects.these streams are very
different forms io streams,io streams are the sequence of data.
2.stream api are used to performs the bulk operations and process the objects of the collections.
3.streams API reduce the code length.
67. without using stream API and with using Stream API code.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.*;
public class StreamMain1 {
public static void main(String[] args) {
// create a List and filter all even numbers from lists
//without stream
List<Integer> list1=new ArrayList<>();
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
list1.add(6);
list1.add(7);
list1.add(8);
List<Integer> evennumber=new ArrayList<>();
for(Integer i:list1)
{
if(i%2==0)
{
evennumber.add(i);
}
}
System.out.println(list1);
System.out.println(evennumber);

//using streamAPI
Stream<Integer> stream=list1.stream();
List<Integer> newlist=stream.filter(i->i%2==0).collect(Collectors.toList());
System.out.println(newlist);

List<Integer> greater=list1.stream().filter(i->i>=10).collect(Collectors.toList());
System.out.println(greater);

68.Difference between streams and java.io.stream?


❖ Java io streams is a sequence of charaters or binary data which is used to be written to a file or to
read data from a file.
❖ While streams is not related to the files,its related to the collection objects.
❖ We need to perform some operation on collection there we go for streams.

69.Difference between streams and collection?


❖ To represent the group of collection as single entity then we should use collection concept.
❖ If we want to perform operation on bulk object then we should use the streams.
70.steps to create and process stream?
❖ Firstly stream works on the collection object.
❖ We can get the stream object by:
• Stream s=collectionObject.stream();
❖ Once we get stream object we can process the object of collection.
❖ Processing of streams can be done in two steps:
• Configuration of stream
• Processing that configuration
❖ Configuration can be done by
• Map
• Filter
71.how to filter the stream objects
❖ We filtering the stream object using stream filter() method.
❖ Example-Stream s=collectionObject.stream().filter(i->i%2==0);
72.how to map the stream objects?
❖ We mapping the stream object using map() method.
❖ Example:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamMappingExample {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// Using map to double each number in the stream


List<Integer> doubledNumbers = numbers.stream()
.map(n -> n * 2)
.collect(Collectors.toList());

System.out.println("Original numbers: " + numbers);


System.out.println("Doubled numbers: " + doubledNumbers);
}
}
73.difference between Filter and Map method
Method Purpose Function Signature Example
Transforms
elements in a Stream<T> map(Function<? List<Integer> doubledNumbers =
super T, ? extends R> numbers.stream().map(n -> n *
map() stream mapper) 2).collect(Collectors.toList());
Selects elements
based on a Stream<T> List<Integer> evenNumbers =
filter(Predicate<? super numbers.stream().filter(n -> n % 2 ==
filter() condition T> predicate) 0).collect(Collectors.toList());

74.why do we need static or default methods?


❖ Default methods in Java were introduced to provide a way to add new methods to interfaces
without breaking existing code.
❖ Defaults methods provides the flexibility to the code.
❖ Static methods in interfaces allow you to define utility methods related to the interface that can
be called directly on the interface itself, without requiring an instance of a class that implements
the interface.
❖ Interface static methods helps us in providing security by not allowing implementation classes to
override them.
❖ Interface static methods are good for providing utility methods,for example null cheking ie whose
definition never change.
75.static methods and default methods differences
Aspect Static Methods Default Methods
Provide utility methods Define a default implementation for interface
Purpose related to the interface methods
Accessed through an instance of a class
Accessed using the implementing the interface, can be overridden if
Invocation interface name needed
Cannot be overridden in Can be optionally overridden in implementing
Overriding implementing classes classes
Interface name followed by Interface method can call default method using
Interface Call method call this keyword

Not inherited by Inherited by implementing classes, can be


Inheritance implementing classes overridden
Multiple Allows multiple interfaces
Inheritance with static methods Allows multiple interfaces with default

76.can you achieve dynamic polymorphism using the instance variables?


❖ No you cannot achieve the dyanamic polymorphism using the instance variable.
❖ Only you can achieve the dyanamic polymorphism using method overriding
77.write the default method example in java?
❖ // Define an interface with a default method
❖ interface MyInterface {
❖ // Regular abstract method
❖ void regularMethod();

❖ // Default method with an implementation
❖ default void defaultMethod() {
❖ System.out.println("This is a default method.");
❖ }
❖ }

❖ // Create a class that implements the interface
❖ class MyClass implements MyInterface {
❖ // Implementing the abstract method from the interface
❖ public void regularMethod() {
❖ System.out.println("Implemented regularMethod.");
❖ }
❖ }

❖ // Main class to demonstrate the usage
❖ public class Main {
❖ public static void main(String[] args) {
❖ // Create an object of the implementing class
❖ MyClass obj = new MyClass();

❖ // Call the regular method implemented in the class
❖ obj.regularMethod(); // Output: Implemented regularMethod.

❖ // Call the default method from the interface
❖ obj.defaultMethod(); // Output: This is a default method.
❖ }
❖ }
77.diamond problem in interfaces
❖ Diamond problem is arises due to implementing the defaults methods in interfaces.
❖ Consider the scenario where 2 or more interfaces having same default method implemented in
respective interfaces.Then child classes implementing both interfaces will be confused which
default implementation to accept.
❖ Diamond problem arises when same default method is used in multiple interfaces.
❖ Example-
❖ interface A {
❖ default void display() {
❖ System.out.println("A");
❖ }
❖ }

❖ interface B extends A {
❖ default void display() {
❖ System.out.println("B");
❖ }
❖ }

❖ interface C extends A {
❖ default void display() {
❖ System.out.println("C");
❖ }
❖ }

❖ class D implements B, C {
❖ public void display() {
❖ B.super.display(); // To explicitly call display() of interface B
❖ C.super.display(); // To explicitly call display() of interface C
❖ }
❖ }

❖ public class Main {
❖ public static void main(String[] args) {
❖ D d = new D();
❖ d.display();
❖ }
❖ }
78.what are the categories of java design patterns?
❖ 1.Creational
❖ 2.Behavioral patterns
❖ 3.structural pattens
❖ 4.j2EE patterns
79.what do we need design pattern?
❖ They are language neutral and so can be applied to any language that supports the object-
orientation
❖ design patterns in Java are like proven recipes or templates that help solve common software
design problems.
❖ They provide a structured way to create flexible, reusable, and maintainable code
80.what are the creational Patterns?
❖ Creational design patterns are related to way of creating objects.
❖ This pattern is used to define and describe how objects are created at class instantiation time.
❖ E.g-
Employee emp = new Employee();
Here we are creating the instance using the new keyword.
81.categories of creational Design patterns?
❖ Factory pattern method
❖ Abstract factory
❖ Builder
❖ Prototype
❖ Singleton
82.what is the factory pattern?
❖ It is also known as the virtual constructor.
❖ The Factory pattern creates objects without exposing the instantiation logic to the client .
❖ Steps-
o Create main class which calls factory class
o Factory class returns required class instance.
❖ Example:
// Vehicle interface
public interface Vehicle {
void manufacture();
}
// Car class implementing Vehicle interface
public class Car implements Vehicle {
@Override
public void manufacture() {
System.out.println("Car is being manufactured.");
}
}

// Bike class implementing Vehicle interface


public class Bike implements Vehicle {
@Override
public void manufacture() {
System.out.println("Bike is being manufactured.");
}
}
// VehicleFactory class
public class VehicleFactory {
public Vehicle createVehicle(String vehicleType) {
if (vehicleType.equalsIgnoreCase("Car")) {
return new Car();
} else if (vehicleType.equalsIgnoreCase("Bike")) {
return new Bike();
}
return null;
}
}
public class Main {
public static void main(String[] args) {
VehicleFactory factory = new VehicleFactory();

// Create a car
Vehicle car = factory.createVehicle("Car");
car.manufacture(); // Output: Car is being manufactured.

// Create a bike
Vehicle bike = factory.createVehicle("Bike");
bike.manufacture(); // Output: Bike is being manufactured.
}
}

83.what is the abstract factory patterns?


❖ The Abstract Factory Pattern is another creational design pattern that provides an
interface for creating families of related or dependent objects without specifying their
concrete classes.
84.Builder pattern in java
❖ Builder design pattern is the one of the creational design pattern.
❖ Used when we have too many arguments to send in constructor and its hard to maintain the
order.
❖ When we don’t want to send all parameters in object initialization.
Steps:
• We create a static nested class which contains all arguments of outer class.
• As per naming convention,if class name is vehicle,builder class should be vehicleBuilder
• Builder class have a public constructor with all required parameters.
• Builder class have a methods of optional parameters.method will return the builder object
• A ‘build()’ method will return the final object.
85.what is the prototype pattern?
❖ The Prototype Pattern in Java is a creational design pattern that allows the creation of new objects
by cloning or copying existing instances, known as prototypes
❖ For Example-
❖ // Prototype interface
❖ interface Prototype {
❖ Prototype clone();
❖ }

❖ // Concrete prototype
❖ class ConcretePrototype implements Prototype {
❖ private int value;

❖ public ConcretePrototype(int value) {
❖ this.value = value;
❖ }

❖ // Implementing the clone method to create a copy
❖ @Override
❖ public Prototype clone() {
❖ return new ConcretePrototype(this.value);
❖ }

❖ public int getValue() {
❖ return value;
❖ }
❖ }

❖ public class Main {
❖ public static void main(String[] args) {
❖ // Creating a prototype instance
❖ ConcretePrototype prototype = new ConcretePrototype(10);

❖ // Cloning the prototype to create a new object
❖ ConcretePrototype clonedObject = (ConcretePrototype) prototype.clone();

❖ // Outputting the value of the cloned object
❖ System.out.println("Cloned object value: " + clonedObject.getValue());
❖ }
❖ }
86.singleton pattern?
❖ In Java, the Singleton pattern is a creational design pattern that ensures a class has only one
instance and provides a global point to access that instance.
❖ Example-
public class Singleton {
// The singleton instance
private static Singleton instance;

// Private constructor to prevent instantiation from outside the class


private Singleton() {
// Initialization code, if needed
}

// Public method to provide the singleton instance


public static Singleton getInstance() {
// Lazy initialization: create the instance if it doesn't exist yet
if (instance == null) {
instance = new Singleton();
}
return instance;
}

// Other methods, if needed


}

87.What are the Structural Patterns?


❖ Structural design patters show you how to assemble different piecescof systems together
in a flexible and extensible fashion.
❖ They help you guarantee that when one part changes,the entire structrure does not need
to change.
88.categories of java Design Patterns?
❖ Proxy design pattern
❖ flyweight design pattern
❖ facade design pattern
❖ composite design pattern
❖ Adapter design pattern
❖ Decorator design pattern
89.what is the proxy design pattern in java?
❖ Proxy design pattern provides a substitute or placeholder for another object.to control access to
it.
// Step 1: Create an interface that both the RealSubject and Proxy will implement.
interface Subject {
void request();
}
// Step 2: Create the RealSubject, the actual object that Proxy represents.
class RealSubject implements Subject {
@Override
public void request() {
System.out.println("RealSubject: Handling request.");
}
}

// Step 3: Create the Proxy, which will act as a surrogate for RealSubject.
class Proxy implements Subject {
private RealSubject realSubject;

// Step 4: Implement the same interface as RealSubject.


@Override
public void request() {
// Step 5: Check if the RealSubject has been created; if not, create it.
if (realSubject == null) {
realSubject = new RealSubject();
}

// Step 6: Delegate the request to the RealSubject.


realSubject.request();

// Additional functionality, if needed, can be added before or after the delegation.


// For example, you can add logging, access control, or caching here.
}
}

// Step 7: Client code that uses the Proxy to interact with the RealSubject.
public class ProxyPatternExample {
public static void main(String[] args) {
// Create a Proxy object instead of directly creating a RealSubject object.
Subject proxy = new Proxy();

// The client interacts with the Proxy, but the RealSubject is created and used as needed.
proxy.request();
}
}
90.what is the flyweight design patterns?
❖ The Flyweight Design Pattern is a structural pattern that aims to minimize memory usage
or computational expenses by sharing as much as possible with related objects
❖ it is used for efficiency and optimization
91.what is the façade design pattern in java?
❖ The Facade Design Pattern is a structural pattern that provides a simplified interface to a
set of interfaces in a subsystem.
❖ It defines a higher-level interface that makes the subsystem easier to use, hiding the complexities
of the subsystem from the client.
92.what is the composite design pattern in java?
❖ The Composite Design Pattern is a structural pattern that composes objects into tree
structures to represent the hierarchies
❖ It allows clients to treat individual objects and compositions of objects uniformly.
93.what is the adapter design pattern in java?
❖ The Adapter Design Pattern is a structural pattern that allows incompatible interfaces to work
together.
❖ It acts as a bridge between two incompatible interfaces by converting the interface of a class into
another interface that a client expects.
94.what is the decorator design pattern in java?
❖ The Decorator Design Pattern is a structural pattern that allows behavior to be added to an
individual object, either statically or dynamically, without affecting the behavior of other objects
from the same class.
95.What is the spring Boot?
❖ Spring Boot is the spring module.
❖ Elaborating spring boot is a framework for RAD build using Spring framwork with extra support of
auto-configuration and embedded application server.
❖ It provides rapid application development.
❖ It helps us in creating efficient,fast,stand alone,which you can just run it basically removes a lot of
configuration and dependencies.
96.what is RAD-
❖ RAD is the modified waterfall model which focuses on the development of software in a short
time.
❖ Following are the some phases of of RAD-
• Business modelling-buisness model is desiged for product to be developed.
• Data modelling-Data model is designed.
• Process modelling-Process model is designed.
• Application generation-The actual product is bulit using coding.
• Testing and turnover-The Product is tested and if changes are required then whole
process starts again.
97.Is this possible to change the port of Embedded Tomcat server in spring boot?
❖ Yes.
❖ Using put.port properties in application properties.
98.can we override or replace the Embedded Tomcat server in spring Boot?
❖ Yes ,we can replace the Embedded Tomcat with any other server by using Starter dependencies.
❖ Like-You can use Spring-boot-Starter-jetty as a dependency for each project as you need.
99.can we disable the default web server in the spring boot application?
❖ The major strong point in spring is to provide flexibility to build your application loosely coupled.
❖ Spring provides the features to disable the web server in a quick configuration.
100.How to disable a specific autoconfiguration class?
101.Interview Bit websites-
1. Why is Java a platform independent language?
❖ Java language was developed so that it does not depend on any hardware or software
because the compiler compiles the code and then converts it to platform-independent
byte code which can be run on multiple systems.
2. Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed.
On the other hand, Heap memory is the portion that was not allocated to the java program but it will be
available for use by the java program when it is required, mostly during the runtime of the program.

Java Utilizes this memory as -

• When we write a java program then all the variables, methods, etc are stored in the stack memory.
• And when we create any object in the java program then that object was created in the heap
memory. And it was referenced from the stack memory

3 How is Java different from C++?

• C++ is only a compiled language, whereas Java is compiled as well as an


interpreted language.
• C++ allows users to use pointers in the program. Whereas java doesn’t allow it.
Java internally uses pointers.
• C++ supports the concept of Multiple inheritances whereas Java doesn't support this.

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

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code
simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential
errors. Moreover, security is also compromised if pointers are used because the users can directly
access memory with the help of pointers.

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

❖ Instance variables are those variables that are accessible by all the methods in the class. They
are declared outside the methods and inside the class.
❖ Local variables are those variables present within a block, function, or constructor and can be
accessed only inside them. Whenever a local variable is declared inside a method, the other
class methods don’t have any knowledge about the local variable.

8. What are the default values assigned to variables and instances in java?

• There are no default values assigned to the variables in java. We need to initialize the value
before using it. Otherwise, it will throw a compilation error of (Variable might not be
initialized).
• But for instance, if we create the object, then the default value will be initialized
by the default constructor depending on the data type.
• If it is a reference, then it will be assigned to null.
• If it is numeric, then it will assign to 0.
• If it is a boolean, then it will be assigned to false. Etc

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

equals() ==
This is a method defined in the Object class. It is a binary operator in Java.
The .equals() Method is present in the Object
class, so we can override our custom
They always compare the HashCode.
.equals() method in the custom class, for
objects comparison.
This operator is used for comparing
This method is used for checking the
addresses (or references), i.e checks if
equality of contents between two objects as
both the objects are pointing to the same
per the specified business logic.
memory location.
10. How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions

• Using For Loop:

for (;;)
{
// Business logic
// Any break logic
}

• Using while loop:

while(true){
// Business logic
// Any break logic
}

• Using do-while loop:

do{
// Business logic
// Any break logic
}while(true);
11. Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we
want.
class Main {
public static void main(String args[]) {
System.out.println(" Main Method");
}
public static void main(int[] args){
System.out.println("Overloaded Integer array Main Method");
}
public static void main(char[] args){
System.out.println("Overloaded Character array Main Method");
}
public static void main(double[] args){
System.out.println("Overloaded Double array Main Method");
}
public static void main(float args){
System.out.println("Overloaded float Main Method");
}
}
12. Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and
represents the non-access modifier.

• final variable:
o When a variable is declared as final in Java, the value can’t be modified once it has
been assigned.
o
• final method:
o A method declared as final cannot be overridden by its children's classes.

• final class:
o No classes can be inherited from the class declared as final.

13. Is it possible that the ‘finally’ block will not be executed? If yes then list the case.

Yes. It is possible that the ‘finally’ block will not be executed. The cases are-

• Suppose we use System.exit() in the above statement


• If there are fatal errors like Stack overflow, Memory access error, etc.

14. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but
differing input parameters.
15. Why is the main method static in Java?
The main method is always static because static members are those methods that belong to
the classes, not to an individual object.

So if the main method will not be static then for every object, It is available.

And that is not acceptable by JVM. JVM calls the main method based on the class name itself.
Not by creating the object.

16. Difference between static methods, static variables, and static classes in java.
❖ Static Methods and Static variables are those methods and variables that belong to the class of
the java program, not to the object of the class. This gets memory where the class is loaded. And
these can directly be called with the help of class names.
❖ For example - We have used mathematical functions in the java program like - max(),
min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly
with the class name. Like - Math.max(), Math.min(), etc. So that is a static method.
❖ Static classes - A class in the java program cannot be static except if it is the inner class.
If it is an inner static class, then it exactly works like other static members of the class

17.What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the
unnecessary and unreachable objects during the Java program execution by deleting
those unreachable objects.

18. What is a ClassLoader?

• Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task
of ClassLoader is to load the required classes and interfaces to the JVM when required.
• Example- To get input from the console, we require the scanner class. And the Scanner
class is loaded by the ClassLoader.

19. What are shallow copy and deep copy in java?

To copy the object's data, we have several methods like deep copy and shallow copy.

Example -

class Rectangle{
int length = 5;
int breadth = 3;
}

Object for this Rectangle class - Rectangle obj1 = new Rectangle();

• Shallow copy - The shallow copy only creates a new reference and points to the
same object. Example - For Shallow copy, we can do this by -
Rectangle obj2 = obj1;

Now by doing this what will happen is the new reference is created with the name obj2
and that will point to the same memory location.

• Deep Copy - In a deep copy, we create a new object and copy the old object
value to the new object. Example -

Rectangle obj3 = new Rectangle();


Obj3.length = obj1.length;
Obj3.breadth = obj1.breadth;
20. Apart from the security aspect, what are the reasons behind making strings
immutable in Java?
1.Thread safety-Immutable string can be safely shared among multiple threads without the risk of data
corruption or unexpected behavior.

2. Hashcode Stability: Since strings are widely used as keys in hash-based collections like HashMap,
immutability ensures that the hashcode of a string remains constant throughout its lifecycle, providing
consistency in hashing.

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

• Storage area: In string, the String pool serves as the storage area. For
StringBuilder and StringBuffer, heap memory is the storage area.

• Mutability: A String is immutable, whereas both the StringBuilder and


StringBuffer are mutable.
• Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in
performing operations.
• // String
• String first = "InterviewBit";
• String second = new String("InterviewBit");
• // StringBuffer
• StringBuffer third = new StringBuffer("InterviewBit");
• // StringBuilder
• StringBuilder fourth = new StringBuilder("InterviewBit");

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

• This statement is completely false.


• Static methods are not related to the objects they are declared only the class
level.
• Private methods are only restricated to the parent class.
23. What makes a HashSet different from a TreeSet?

• Although both HashSet and TreeSet are not synchronized and ensure that duplicates are
not present.
• Implementation: For a HashSet, the hash table is utilized for storing the
elements in an unordered manner. However, TreeSet makes use of the red-black
tree to store the elements in a sorted manner.
• Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In
the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or
null objects.

24. Why is the character array preferred over string for storing confidential
information?
❖ In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it
continues to stay in the string pool as long as it is not removed in the form of garbage.
❖ As a result, vital information can be harmed by hackers.
❖ Such risks can be eliminated by using mutable objects or structures like character
arrays for storing any variable.

25. What are the differences between HashMap and HashTable in Java?
HashMap HashTable
HashMap is not synchronized thereby
HashTable is synchronized and hence it
making it better for non-threaded
is suitable for threaded applications.
applications.
Allows only one null key but any number of This does not allow null in both keys or
null in the values. values.

26. What is the importance of reflection in Java?


❖ Reflection in Java allows for dynamic inspection and manipulation of class, methods, fields, and
other entities at runtime.
❖ It's essential for tasks like creating generic code, frameworks, and tools that need to work with
classes in a flexible and extensible manner.

27. What are the different types of Thread Priorities in Java? And what is the default
priority of a thread assigned by JVM?

There are a total of 3 different types of priority available in Java.

MIN_PRIORITY: It has an integer value assigned with 1.


MAX_PRIORITY: It has an integer value assigned with 10.
NORM_PRIORITY: It has an integer value assigned with 5.
28. What is the difference between the program and the process?

❖ A program can be defined as a line of code written in order to accomplish a


particular task. Whereas the process can be defined as the programs which are
under execution.
❖ A program doesn't execute directly by the CPU. First, the resources are allocated to the
program and when it is ready for execution then it is a process.

29. What are the differences between constructor and method of a class in Java?
Constructor Method
Constructor is used for initializing
Method is used for exposing the object's behavior.
the object state.
Method should have a return type. Even if it does
Constructor has no return type.
not return anything, return type is void.
Constructor gets invoked
Method has to be invoked on the object
implicitly.
The constructor name should be The name of the method can have any name or
equal to the class name. have a class name too.

30. Java works as “pass by value” or “pass by reference” phenomenon?


❖ Java always works as a “pass by value”

31. What is the ‘IS-A ‘ relationship in OOPs java?

❖ ‘IS-A’ relationship is another name for inheritance. When we inherit the super
class class from the child class, then it forms a relationship between the classes.
So that relationship is termed an ‘IS-A’ Relationship.

Consider a Television (Typical CRT TV). Now another Smart TV that is inherited from
television class. So we can say that the Smart iv is also a TV. Because CRT TV things
can also be done in the Smart TV.

32. Which among String or String Buffer should be preferred when there are lot of
updates required to be done in the data?
❖ StringBuffer is mutable and dynamic in nature whereas String is immutable. Every
updation / modification of String creates a new String thereby overloading the string
pool with unnecessary objects
❖ Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it
will reduce the overhead of the creation of multiple String objects in the string pool.

33. How to not allow serialization of attributes of a class in Java?

• In order to achieve this, the attribute can be declared along with the usage
of transient keyword.
34. What happens if the static modifier is not included in the main method signature in
Java?
❖ There is a no such compilation error.but jvm throws the “No such method Error” at
runtime.

35. Can we make the main() thread a daemon thread?

❖ In java multithreading, the main() threads are always non-daemon


threads. And there is no way we can change the nature of the non-
daemon thread to the daemon thread

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

❖ The program can't compile as the compiler says that the method has
been already defined inside the class.

37. What do you understand by Object Cloning and how do you achieve it in Java?

❖ It is the process of creating an exact copy of any object. In order to


support this, a java class has to implement the Cloneable interface of
java.lang package and override the clone() method provided by the
Object class. the syntax of which is:

protected Object clone() throws CloneNotSupportedException{


return (Object)super.clone();
}

• In case the Cloneable interface is not implemented and just the method is overridden, it
results in CloneNotSupportedException in Java.

38. How does an exception propagate in the code?

❖ When an exception occurs, first it searches to locate the matching


catch block.
❖ In case, the matching catch block is located, then that block would be
executed.
❖ Else, the exception propagates through the method call stack and goes
into the caller method where the process of matching the catch block
is performed.
❖ This propagation happens until the matching catch block is found. If
the match is not found, then the program gets terminated in the main
method.
39. How do exceptions affect the program if it doesn't handle them?
Exceptions are runtime errors. Suppose we are making an android application with java. And it
all works fine but there is an exceptional case when the application tries to get the file from
storage and the file doesn’t exist (This is the case of exception in java). And if this case is not
handled properly then the application will crash. This will be a bad experience for users.

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

No, it is not necessary for a catch block to be present after a try block.

41. Will the finally block get executed when the return statement is written at the end of
try block and catch block as shown below?
public int someMethod(int i){
try{
//some statement
return 1;
}catch(Exception e){
//some statement
return 999;
}finally{
//finally block statements
}
}

finally block will be executed irrespective of the exception or not. The only case where
finally block is not executed is when it encounters ‘System.exit()’ method anywhere in
try/catch block.

42. Can you call a constructor of a class inside the another constructor?
❖ Yes, the concept can be termed as constructor chaining and can be achieved using this()

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

In the case of ArrayList, data storing in the form of primitive data types (like int, float,
etc.) is not possible. The data members/objects present in the ArrayList have
references to the objects which are located at various sites in the memory. Thus,
storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes
place in various memory locations.

44. Why does the java array index start with 0?

❖ Because 0 index array avoids the extra arithmetic oprations to calculate the
memory address.
❖ When the index position is 0 then the memory address is calculated by using the
❖ Formula:

Memory address=[base address+index*no.of bytes)

❖ When the index position is 1 then the memory address is calculated by using the
❖ Formula:

Memory address=[base address+(index-1)*no.of bytes)

45. Why is the remove method faster in the linked list than in an array?

❖ In the linked list, we only need to adjust the references when we want to delete
the element from either end or the front of the linked list. But in the array,
indexes are used.

46. What are Memory storages available with JVM?


❖ Class(Method) Area: stores class-level data of every class such as the
runtime constant pool, field, and method data, and the code for methods.
❖ Heap: Objects are created or objects are stored. It is used to allocate
memory to objects during run time.
❖ Stack: stores data and partial results which will be needed while
returning value for method.
❖ Program Counter Register: stores the address of the Java virtual machine
instruction currently being executed.
❖ Native Method Stack: stores all the native methods used in the
application.

47. Explain public static void main(String args[]) in Java.


public: the public is the access modifier responsible for mentioning who can
access the element or the method and what is the limit.
static: static is a keyword used so that we can use the element without
initiating the class so to avoid the unnecessary allocation of the memory.
void: void is a keyword and is used to specify that a method doesn’t return
anything
main: main represents that the function declared is the main function.
String args[]: It stores Java command-line arguments
48. What is Java String Pool?
A Java String Pool is a place in heap memory where all the strings defined in
the program are stored.
Example:
String str1="Hello";
// "Hello" will be stored in String Pool
// str1 will be stored in stack memory

49. What will happen if we declare don’t declare the main as static?
We can declare the main method without using static and without getting any
errors. But, the main method will not be treated as the entry point to the
application or the program.

50. Why Packages are used? /advantages


Packages are used in Java in order to prevent naming conflicts, control access,
and make searching/locating and usage of classes, interfaces, etc easier.

51. How many types of packages are there in Java?


There are two types of packages in Java
• User-defined packages
• Build In packages

52.Explain different data types in Java.


There are 2 types of data types in Java as mentioned below:
1. Primitive Data Type
2. Non-Primitive Data Type or Object Data type
Primitive Data Type: Primitive data are single values with no special
capabilities. There are 8 primitive data types:
• boolean: stores value true or false
• byte: stores an 8-bit signed two’s complement integer
• char: stores a single 16-bit Unicode character
• short: stores a 16-bit signed two’s complement integer
• int: stores a 32-bit signed two’s complement integer
• long: stores a 64-bit two’s complement integer
• float: stores a single-precision 32-bit IEEE 754 floating-point
• double: stores a double-precision 64-bit IEEE 754 floating-point
Non-Primitive Data Type: Reference Data types will contain a memory address
of the variable’s values because it is not able to directly store the values in the
memory. Types of Non-Primitive are mentioned below:
• Strings
• Array
• Class
• Object
• Interface

53. When a byte datatype is used?


A byte is an 8-bit signed two-complement integer. The minimum value
supported by bytes is -128 and 127 is the maximum value. It is used in
conditions where we need to save memory and the limit of numbers needed is
between -128 to 127.

54. What is the default value of byte datatype in Java?


The default value of the byte datatype in Java is 0.

55. What is the default value of float and double datatype in Java?
The default value of the float is 0.0f and of double is 0.0d in Java.

56. Why do we need wrapper classes?


The wrapper class is an object class that encapsulates the primitive data types,
and we need them for the following reasons:
1. Wrapper classes are final and immutable
2. Provides methods like valueOf(), parseInt(), etc.
3. It provides the feature of autoboxing and unboxing.

57.what is autoboxing and unboxing in java?


❖ . Autoboxing refers to the conversion of a primitive value into an object
of the corresponding wrapper class is called autoboxing. For example,
converting int to Integer class.
❖ Unboxing on the other hand refers to converting an object of a wrapper
type to its corresponding primitive value. For example conversion of
Integer to int
58.

Primitive Type Wrapper Class

boolean Boolean

byte Byte

char Character

float Float

int Integer

long Long

short Short

double Double

59. What are the default values assigned to variables and instances in
Java?
In Java When we haven’t initialized the instance variables then the compiler
initializes them with default values. The default values for instances and
variables depend on their data types. Some common types of default data
types are:
• The default value for numeric types (byte, short, int, long, float, and
double) is 0.
• The default value for the boolean type is false.
• The default value for object types (classes, interfaces, and arrays) is
null.
60. What is a Class Variable?
In Java, a class variable (also known as a static variable) is a variable that is
declared within a class but outside of any method, constructor, or block.

// Java program to demonstrate use of Clas Variable

class GFG {

public static int ctr = 0;

public GFG() { ctr++; }

public static void main(String[] args)

GFG obj1 = new GFG();

GFG obj2 = new GFG();

GFG obj3 = new GFG();

System.out.println("Number of objects created are "

+ GFG.ctr);

61. What is the default value stored in Local Variables?


There is no default value stored with local variables. Also, primitive variables
and objects don’t have any default values.

62. Explain the difference between instance variable and a class variable.
Instance Variable: A class variable without a static modifier known as an
instance variable is typically shared by all instances of the class.
Class Variable: Class Variable variable can be declared anywhere at the class
level using the keyword static. These variables can only have one value when
applied to various objects.

63. What is a static variable?


The static keyword is used to share the same variable or method of a given
class. Static variables are the variables that once declared then a single copy
of the variable is created and shared among all objects at the class level.

64. What is the difference between System.out, System.err, and


System.in?
❖ System.out-It is the printstream used to output the data on command
Line interfaces like terminal and console.
❖ System.err – It is used to display error messages.
❖ System.in – It is an InputStream used to read input from the terminal
Window.
65. What do you understand by an IO stream?
Java brings various Streams with its I/O package that helps the user to perform
all the input-output operations.

66. What is the difference between the Reader/Writer class hierarchy and
the InputStream/OutputStream class hierarchy?
❖ The key difference between them is that byte stream data is read and
written by input/output stream classes.
❖ Characters are handled by the Reader and Writer classes.

67. What are the super most classes for all the streams?
❖ All the stream classes can be divided into two types of classes that are
ByteStream classes and CharacterStream Classes.
❖ The ByteStream classes are further divided into InputStream classes and
OutputStream classes.
❖ CharacterStream classes are also divided into Reader classes and Writer
classes. The SuperMost classes for all the InputStream classes is
java.io.InputStream and for all the output stream classes is
java.io.OutPutStream. Similarly, for all the reader classes, the super-most
class is java.io.Reader, and for all the writer classes, it is java.io.Writer.

68. What are the FileInputStream and FileOutputStream?


FileInputStream in Java is used to read data from a file as a stream of bytes. It
is mostly used for reading binary data such as images, audio files, or serialized
objects.

In Java, the FileOutputStream function is used to write data byte by byte into a
given file or file descriptor. Usually, raw byte data, such as pictures, is written
into a file using FileOutputStream.

69. What is the purpose of using BufferedInputStream and


BufferedOutputStream classes?
When we are working with the files or stream then to increase the
Input/Output performance of the program we need to use the
BufferedInputStream and BufferedOutputStream classes.

70. What are FilterStreams?


❖ Stream filter or Filter Streams returns a stream consisting of the
elements of this stream that match the given predicate.

71. What is an I/O filter?


An I/O filter also defined as an Input Output filter is an object that reads from
one stream and writes data to input and output sources.

72. How many ways you can take input from the console?
There are two methods to take input from the console in Java mentioned
below:
1. Using Command line argument
2. Using Buffered Reader Class
3. Using Console Class
4. Using Scanner Class
73. Difference in the use of print, println, and printf.
print, println, and printf all are used for printing the elements but print prints
all the elements and the cursor remains in the same line. println shifts the
cursor to next line. And with printf we can use format identifiers too.

74. What are operators?


Operators are the special types of symbols used for performing some
operations over variables and values.

75. How many types of operators are available in Java?


All types of operators in Java are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
76. Explain the difference between >> and >>> operators.
>> operator shifts the sign bits and the >>> operator is used in shifting out the
zero-filled bits.

77. Which Java operator is right associative?


There is only one operator which is right associative which is = operator.

78. What is dot operator?


The Dot operator in Java is used to access the instance variables and methods
of class objects

79. What is covariant return type?


❖ The covariant return type specifies that the return type may vary in the
same direction as the subclass.
• Avoids confusing type casts present in the class hierarchy and makes
the code readable, usable, and maintainable.

• Help in preventing run-time ClassCastExceptions on returns.


80. What is the transient keyword?

❖ The transient keyword is used at the time of serialization if we don’t


want to save the value of a particular variable in a file

81. What’s the difference between the methods sleep() and wait()?

Sleep() Wait()

The sleep() method belongs to the Wait() method belongs to the object
thread class. class.

This method is a static method. This method is not a static method.

Mainly used to delay a thread for Mainly used to pause a thread until
some specific time duration. notified by another thread.

82. Why is StringBuffer called mutable?


StringBuffer class in Java is used to represent a changeable string of
characters.

It offers an alternative to the immutable String class by enabling you to change


a string’s contents without constantly creating new objects.

83. How is the creation of a String using new() different from that of a
literal?
❖ String using new() is different from the literal as when we declare string
it stores the elements inside the stack memory whereas when it is
declared using new() it allocates a dynamic memory in the heap memory.
84. On which memory arrays are created in Java?
Arrays in Java are created in heap memory. When an array is created with the
help of a new keyword, memory is allocated in the heap to store the elements
of the array. In Java, the heap memory is managed by the Java Virtual
Machine(JVM) and it is also shared between all threads of the Java Program.

85. There are two types of arrays i.e., Primitive arrays and References Arrays.
• Single-Dimensional Arrays: Arrays that have only one dimension i.e.,
an array of integers or an array of strings are known as single-
dimensional arrays.
• Multi-Dimensional Arrays: Arrays that have two or more dimensions
such as two-dimensional or three-dimensional arrays.

86. What is the difference between int array[] and int[] array?
❖ Both int array[] and int[] array are used to declare an array of integers in
java. The only difference between them is on their syntax no
functionality difference is present between them.
❖ int arr[] is a C-Style syntax to declare an Array.

❖ int[] arr is a Java-Style syntax to declare an Array.

87. How to copy an array in Java?


❖ clone() method in Java:This method in Java is used to create a
shallow copy of the given array which means that the new
array will share the same memory as the original array.
• int[] Arr = { 1, 2, 3, 5, 0};
• int[] tempArr = Arr.clone();
❖ arraycopy() method: To create a deep copy of the array we can
use this method which creates a new array with the same
values as the original array.
❖ copyOf() method: This method is used to create a new array
with a specific length and copies the contents of the original
array to the new array.
❖ copyOfRange() method: This method is very similar to the
copyOf() method in Java, but this method also allows us to
specify the range of the elements to copy from the original
array.

88. What do you understand by the jagged array?


❖ A jagged Array in Java is just a two-dimensional array in which each row
of the array can have a different length.
❖ This feature is very useful in conditions where the data has varying
lengths or when memory usage needs to be optimized.
❖ int[][] Arr = new int[][] {
❖ {1, 2, 8},
❖ {7, 5},
❖ {6, 7, 2, 6}
❖ };
89. Is it possible to make an array volatile?
In Java, it is not possible to make a volatile. Volatile keywords in Java can only
be applied to individual variables but not to arrays or collections

90. What is an object-oriented paradigm?


❖ Paradigm is nothing but the pattern.
❖ Programming paradigms are the methods to solve a program that is of
four types namely, Imperative, logical, functional, and object-oriented.
When objects are used as base entities upon which the methods are
applied, encapsulation or inheritance functionalities are performed, it is
known as an object-oriented paradigm.

91. What is the difference between an object-oriented programming


language and an object-based programming language?

Object-Oriented Programming Object-Based Programming


Language Language

Object-oriented programming
The scope of object-based
language covers larger concepts like
programming is limited to the usage
inheritance, polymorphism,
of objects and encapsulation.
abstraction, etc.
Object-Oriented Programming Object-Based Programming
Language Language

It doesn’t support all the built-in


It supports all the built-in objects
objects

Examples: Java script, visual basics,


Examples: Java, C#, etc.
etc.

92. How is the ‘new’ operator different from the ‘newInstance()’ operator
in Java?
the new operator is used to create objects, but if we want to decide the type of
object to be created at runtime, there is no way we can use the new operator.
In this case, we have to use the newInstance() method.

93. What is the difference between static (class) method and instance
method?

Static(Class) method Instance method

Static method is associated with a The instance method is associated


class rather than an object. with an object rather than a class.

Static methods do not have access Instance methods have access


to this keyword. to this keyword.

This method can access only static This method can access both static
members of the class and non-static methods of the class.

94. What is this keyword in Java?


‘this’ is a keyword used to reference a variable that refers to the current object.
95. What are Brief Access Specifiers and Types of Access Specifiers?
Access Specifiers in Java help to restrict the scope of a class, constructor,
variable, method, or data member. There are four types of Access Specifiers in
Java mentioned below:
1. Public
2. Private
3. Protected
4. Default

96. What will be the initial value of an object reference which is defined
as an instance variable?
The initial value of an object reference which is defined as an instance variable
is a NULL value.

97. What are the different ways to create objects in Java?


Methods to create objects in Java are mentioned below:
1. Using new keyword
2. Using new instance
3. Using clone() method
4. Using deserialization
5. Using the newInstance() method of the Constructor class

98. What are the advantages and disadvantages of object cloning?


Advantages-

• We reducing the size of the code.


• In Java, the ‘=’ assignment operator cannot be used for cloning as it
simply creates a copy of reference variables.
• Disadvantages-As the Object.clone() method is protected, so need to
provide our own clone() and indirectly call Object.clone() from it.
99. What is the constructor?
Constructor is a special method that is used to initialize objects. Constructor is
called when a object is created. The name of constructor is same as of the
class.
Example:
// Class Created
class XYZ{
private int val;

// Constructor
XYZ(){
val=0;
}
};
100. What happens if you don’t provide a constructor in a class?
❖ If you don’t provide a constructor in a class in Java, the compiler
automatically generates a default constructor with no arguments and no
operation which is a default constructor.

101. How many types of constructors are used in Java?


There are two types of constructors in Java as mentioned below:
1. Default Constructor
2. Parameterized Constructor
Default Constructor: It is the type that does not accept any parameter value. It
is used to set initial values for object attributes.
class_Name();
// Default constructor called

Parameterized Constructor: It is the type of constructor that accepts


parameters as arguments. These are used to assign values to instance
variables during the initialization of objects.
class_Name(parameter1, parameter2......);
// All the values passed as parameter will be
// allocated accordingly

102. What is a marker interface?


What is a marker interface?
An Interface is recognized as an empty interface (no field or methods) it is
called a marker interface. Examples of marker interfaces are Serializable,
Cloneable, and Remote interfaces.
103. What are the differences between abstract class and interface?

Abstract Class Interface Class

Both abstract and non-abstract


The interface contains only abstract
methods may be found in an abstract
methods.
class.

Multiple inheritance is not supported Multiple inheritances is supported by


by the Abstract class. Interface Class.

extend keyword is used to extend an implements Keyword is used to


Abstract Class. implement the interface.

Abstract Class has members like All class members are public by
protected, private, etc. default.

104. What do you mean by aggregation?


❖ Aggregation is a term related to the relationship between two classes
best described as a “has-a” relationship.
❖ It is a unidirectional association means it is a one-way relationship. It
contains the reference to another class and is said to have ownership of
that class.

105. Is there any limitation to using Inheritance?


❖ Tight Coupling: Inheritance can lead to tight coupling between classes, making the code more
interconnected and harder to maintain.
❖ Inflexibility: Subclasses are dependent on the implementation details of the superclass, making it
difficult to modify the superclass without affecting its subclasses.
❖ Diamond Problem: In languages that support multiple inheritance, conflicts can arise when a
class inherits from two classes that have a common ancestor, leading to ambiguity in method
resolution.

106. What is an association?


The association is a relation between two separate classes established
through their Objects. It represents Has-A’s relationship.
107. State the difference between Composition and Aggregation.

Aggregation Composition

It defines a “has a” relationship


It represents the part-of relationship
between the objects

Objects are independent of each


Objects are dependent on each other.
other.

Represent it by using the filled Represent it by using the empty


diamond. diamond.

Child objects don’t have a lifetime. Child objects have a lifetime.

108. Can the constructor be inherited?


No, we can’t inherit a constructor.

109. Can we override the static method?


No, as static methods are part of the class rather than the object so we can’t
override them.

110. Can we override the overloaded method?


❖ Yes, since the overloaded method is a completely different method in the
eyes of the compiler. Overriding isn’t the same thing at all.
111.

Method Overloading Method Overriding

When two or multiple methods are in When a subclass provides its own
the same class with different implementation of a method that is
parameters but the same name. already defined in the parent class.
Method Overloading Method Overriding

Method overloading can only happen


Method overriding can only happen in
in the same class or between a
Subclass.
subclass or parent class.

Example of Compile Time


Example of Run Time Polymorphism.
Polymorphism.

112. Can we override the private methods?


It is not possible to override the private methods in Java.

113. Can we change the scope of the overridden method in the subclass?
❖ In Java, it is not possible to modify the overridden method’s scope.

114. Can you have virtual functions in Java?


Yes, Java supports virtual functions. Functions are by default virtual and can be
made non-virtual using the final keyword.

115. How can you synchronize an ArrayList in Java?


An ArrayList can be synchronized using two methods mentioned below:
1. Using Collections.synchronizedList()
2. Using CopyOnWriteArrayList
116. Why do we need a synchronized ArrayList when we have Vectors
(which are synchronized) in Java?
ArrayList is in need even when we have Vectors because of certain reasons:
1. ArrayList is faster than Vectors.
2. ArrayList supports multithreading whereas Vectors only supports
single-thread use.
117. Why can’t we create a generic array?
Generic arrays can’t be created because an array carries type information of its
elements at runtime because of which during runtime it throw
‘ArrayStoreException’ if the elements’ type is not similar.
118. Explain the method to convert ArrayList to Array and Array to
ArrayList.

1.conversion of Array to ArrayList

// Java program to demonstrate conversion of

// Array to ArrayList of fixed-size.

import java.util.*;

// Driver Class

class GFG {

// Main Function

public static void main(String[] args)

String[] temp = { "Abc", "Def", "Ghi", "Jkl" };

// Conversion of array to ArrayList

// using Arrays.asList

List conv = Arrays.asList(temp);

System.out.println(conv);

2.conversion of ArrayList to array methods.


// Java program to demonstrate working of

// Objectp[] toArray()

import java.io.*;

import java.util.List;

import java.util.ArrayList;

// Driver Class

class GFG {

// Main Function

public static void main(String[] args)

// List declared

List<Integer>

arr = new ArrayList<Integer>();

arr.add(1);

arr.add(2);

arr.add(3);

arr.add(2);

arr.add(1);

// Conversion

Object[] objects = arr.toArray();

// Printing array of objects

for (Object obj : objects)

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


}

119.What is a Vector in Java?


1.Vector is implemented using a dynamic array as the size of the vector
increases and decreases depending upon the elements inserted in it.
2.Elements of the Vector using index numbers.
3.Vectors are synchronized in nature means they only used a single thread (
only one process is performed at a particular time ).

120. How to make Java ArrayList Read-Only?


An ArrayList can be made ready only using the method provided by
Collections using the Collections.unmodifiableList() method.
Syntax:
array_readonly = Collections.unmodifiableList(ArrayList);

121. What is a priority queue in Java?


A priority queue is an abstract data type similar to a regular queue or stack
data structure. Elements stored in elements are depending upon the priority
defined from low to high. The PriorityQueue is based on the priority heap.

122. Explain the LinkedList class.


LinkedList class is Java that uses a doubly linked list to store elements. It
inherits the AbstractList class and implements List and Deque interfaces.
Properties of the LinkedList Class are mentioned below:
1. LinkedList classes are non-synchronized.
2. Maintains insertion order.
3. It can be used as a list, stack, or queue.
Syntax:
❖ LinkedList<class> list_name=new LinkedList<class>();

123. What is Set in the Java Collections framework and list down its
various implementations?
❖ Sets are collections that don’t store duplicate elements. They don’t keep
any order of the elements.
❖ HashSet: HashSet in Java, stores the elements in a has table which
provides faster lookups and faster insertion. HashSet is not ordered.
❖ LinkedHashSet: LinkedHashSet is an implementation of HashSet which
maintains the insertion order of the elements.
❖ TreeSet: TreeSet stores the elements in a sorted order that is
determined by the natural ordering of the elements
124. What is EnumSet?
numSet is a specialized implementation of the Set interface for use with
enumeration type. A few features of EnumSet are:
1. It is non-synchronized.
2. Faster than HashSet.
3. All of the elements in an EnumSet must come from a single
enumeration type.
125. What is the ConcurrentHashMap in Java and do you implement it?
❖ ConcurrentHashMap is implemented using Hashtable.
126. Can you use any class as a Map key?
❖ Yes.
127. What is an enumeration?
Enumeration is a user-defined data type. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain. The
main objective of the enum is to define user-defined data types.
Example:
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
RED, GREEN, BLUE;
}

128. What is the difference between Collection and Collections?

Collection Collections

The Collection is an Interface. Collections is a class.


Collection Collections

It provides the standard functionality It is to sort and synchronize the


of data structure. collection elements.

It provides the methods that can be It provides static methods that can be
used for the data structure. used for various operations.

129. Differentiate between Array and ArrayList in Java.

Array ArrayList

Single-dimensional or
Single-dimensional
multidimensional

length keyword returns the size of the size() method is used to compute the
array. size of ArrayList.

The array has Fixed-size. ArrayList size is dynamic

130.What is the difference between Array and Collections in Java?

Array Collections

Array in Java has a fixed Collections in Java have dynamic


size. sizes.

In Collections, Elements are not


In an Array, Elements are stored in
necessarily stored in contiguous
contiguous memory locations.
memory locations.

Objects and primitive data types can be We can only store objects in
stored in an array. collections.
131. Difference between ArrayList and LinkedList.

ArrayList LinkedList

LinkedList Elements are stored


in non-contiguous memory
locations as each element has a
In ArrayList, Elements are stored reference to the next and
in contiguous memory locations previous elements.

ArrayLists are faster for random LinkedLists are faster for


access. insertion and deletion operations

ArrayLists are more memory LinkedList is less memory


efficient. efficient
132. Differentiate between ArrayList and Vector in Java.

rrayLists are implemented as an Vector is Implemented as a growable


expandable array. array.

ArrayList is not synchronized. The vector is synchronized.

ArrayLists are Faster for non- Vector is Slower for non-concurrent


concurrent operations. operations

133.What is the difference between Iterator and ListIterator?

Iterator ListIterator

Can traverse elements present in Can traverse elements present in


Collection only in the forward Collection both in forward and
direction. backward directions.

Can only traverse List and not the


Used to traverse Map, List, and Set.
other two.
134. Differentiate between HashMap and HashTable.

HashMap HashTable

HashMap is not synchronized HashTable is synchronized

One key can be a NULL value NULL values not allowed

135. What is the difference between Iterator and Enumeration?

Iterator Enumeration

The Iterator is fail-fast. Enumeration is not fail-fast.

The Iterators are slower. Enumeration is faster.

The Iterator can perform a The Enumeration can perform


remove operation while only traverse operations on the
traversing the collection. collection.
136. What is the difference between Comparable and Comparator?

Comparable Comparator

The interface is present in The Interface is present in


java.lang package. java.util package.

Provides compareTo() method to Provides compare() method to


sort elements. sort elements.

It provides single sorting It provides multiple sorting


sequences. sequences.
137. What is the difference between Set and Map?

Set Map

It can extend the collection It does not extend the collection


interface. interface.

It does not allow duplicate values. It allows duplicate values.

The set can sort only one null The map can sort multiple null
value. values.

138. Difference between an Error and an Exception.

Errors Exceptions

Recovering from Errors is not Recover from exceptions by either


possible. using a try-catch block

It includes both checked as well as


Errors are all unchecked types in Java.
unchecked types that occur.

Errors can occur at compile time as All exceptions occur at runtime but
well as run time. Compile Time: Syntax checked exceptions are known to the
Error, Run Time: Logical Error. compiler while unchecked are not.

Examples: Checked Exceptions:


SQLException, IOException
Examples:
Unchecked Exceptions:
java.lang.StackOverflowError,
ArrayIndexOutOfBoundException,
java.lang.OutOfMemoryError
NullPointerException,
ArithmeticException.

139. What is exception propagation?


Exception propagation is a process in which the exception is dropped from to
the top to the bottom of the stack
140. What is the difference between this() and super() in Java?

this( ) super( )

It represents the current instance of It represents the current instance of


the class. the parent class.

Access the methods of the same Access the methods of the parent
class. class.

141.what is the multitasking?

❖ Multitasking is the programs ability to performs many tasks at a time.


142. Differentiate between process and thread?

Process Thread

A thread is a single sequence of


A process is a program in execution.
instructions within a process.

The process takes more time to The thread takes less time to
terminate. terminate.

The process takes more time for The thread takes less time for context
context switching. switching.

The process is less efficient in terms Thread is more efficient in terms of


of communication. communication.

143. Explain suspend() method under the Thread class.


• The suspend() method of the Thread class in Java temporarily suspends
the execution of a thread.
• Syntax:
• public final void suspend();
144. Explain the main thread under Thread class execution.
❖ The main thread is automatically created when the program starts
running.

145. What is a daemon thread?


A daemon thread in Java is a low-priority thread that is used to perform
background operations or tasks which are used to perform continuously.

146. Why Garbage Collection is necessary in Java?


For Java, Garbage collection is necessary to avoid memory leaks which can
cause the program to crash and become unstable.

147. What is the drawback of Garbage Collection?


❖ The main drawback to Garbage collection is that it can cause pauses in
an application’s execution as it works to clear the memory which slows
down the performance of the application.

148. Explain the difference between a minor, major, and full garbage
collection.
❖ Minor garbage collection: Also known as young generation garbage
collection, this type of garbage collection is used to collect and reclaim
memory that is used by short-lived objects (objects that are quickly
created and discarded).
❖ Major garbage collection: Also known as old-generation garbage
collection, this type of garbage collection is used to collect and reclaim
memory that is used by long-lived objects

❖ Full garbage collection: During full garbage collection, memories from


all generations are collected and reclaimed, including memories of
young and old.

149. How will you identify major and minor garbage collections in Java?
we can identify both of them based on the output where the minor collection
prints “GC”, whereas the major collection prints “Full GC” for the case where
the garbage collection logging is enabled
150. What is a memory leak, and how does it affect garbage collection?
In Java Memory leaks can be caused by a variety of factors, such as not closing
resources properly, holding onto object references longer than necessary, or
creating too many objects unnecessarily.

There are situations in which garbage collector does not collect objects
because there is a reference to those objects.

151. Name some classes present in java.util.regex package.


Regular Expressions or Regex in Java is an API used for searching and
manipulating of strings in Java. It creates String patterns that can extract the
data needed from the strings or can generalize a pattern.
There are 3 Classes present in java.util.regex mentioned below:
• Pattern Class: Can define patterns
• Matcher Class: Can perform match operations on text using patterns
• PatternSyntaxException Class: Can indicate a syntax error in a regular
expression pattern.
152. Name some classes present in java.util.regex package.
❖ Regular Expressions or Regex in Java is an API used for searching and
manipulating of strings in Java.

There are 3 Classes present in java.util.regex mentioned below:


• Pattern Class: Can define patterns
• Matcher Class: Can perform match operations on text using patterns
• PatternSyntaxException Class: Can indicate a syntax error in a regular
expression pattern.
153. What is JDBC?
JDBC standard API is used to link Java applications and relational databases. It
provides a collection of classes and interfaces that let programmers to use the
Java programming language to communicate with the database

154. There are generally four components of JDBC by which it interacts with
the database:
• JDBC API
• JDBC Driver manager
• JDBC Test Suite
• JDBC-ODBC Bridge Drivers
155. What is JDBC Driver?
JDBC Driver is a software component that is used to enable a Java application
to interact with the database. JDBC provides the implementation of the JDBC
API for a specific database management system, which allows it to connect the
database, execute SQL statements and retrieve data. There are four types of
JDBC drivers:
• JDBC-ODBC Bridge driver
• Native-API driver
• Network Protocol driver
• Thin driver
156. What are the JDBC API components?
JDBC API components provide various methods and interfaces for easy
communication with the databases

156. What is JDBC Connection interface?


Java database connectivity interface (JDBC) is a software component that
allows Java applications to interact with databases.

156. What does the JDBC ResultSet interface?


JDBC ResultSet interface is used to store the data from the database and use it
in our Java Program.

157. What is the JDBC Rowset?


A JDBC RowSet provides a way to store the data in tabular form.

You might also like