Java Interview question
Java Interview question
• JDK stands for Java Development Kit. It is a software development kit used by Java developers to
create Java applications.
• 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.
• 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
• 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.
•
• Singletone class is the class whose only one instance is created at the given time in one
jvm.
• 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.
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.
• 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());
• }
• 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");
• }
• 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?
• 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.
• 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).
• 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.
• 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:
System.out.println(vector.get(i));
System.out.println(element);
// Using iterators
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
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.
Similar to ArrayList, if you create a Vector without specifying an initial capacity, it starts with an
initial capacity of 10.
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.
You can add elements to the top of the Stack using the push() method:
stack.push(5);
stack.push(10);
Elements can be removed from the top of the Stack using the pop() method:
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:
The Stack class in Java is inherited from Vector, which is synchronized and therefore thread-safe.
if (stack.empty()) {
// Stack is empty
} else {
Yes, a Stack in Java can contain null elements since it's designed to hold any object references.
• 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-
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.
• 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-
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
➢ 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.
➢ 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.
➢ 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
➢ 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 .
int value;
this.value = value;
obj.value = 5;
}
public static void main(String[] args) {
modifyObjectReference(obj);
• 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
29. what is the difference between equal method and == operator in java tabular formats
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
32. In Java, what are the differences between heap and stack memory?
Memory
Access
Whenever you create an object, it is always stored away in the heap space.
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.
Packages in Java allow developers to modularize the code and optimize its reuse easily
Packages can also contain hidden classes that are not visible to the outer classes and are only
used within the package.
➢ 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-
❖ 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
➢ }
➢ 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.
❖ 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.
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
(a,b) ->system.out.println(a+b);
❖ 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.
❖ 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.
❖ 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.
• 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();
❖ 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.
import java.util.function.Predicate;
// Creating predicate
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.
//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);
// 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.
}
}
// Step 3: Create the Proxy, which will act as a surrogate for RealSubject.
class Proxy implements Subject {
private RealSubject realSubject;
// 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.
• 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
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.
❖ 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
for (;;)
{
// Business logic
// Any break logic
}
while(true){
// Business logic
// Any break logic
}
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-
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
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.
• 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.
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;
}
• 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 -
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.
22. In Java, static as well as private method overriding is possible. Comment on the
statement.
• 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.
27. What are the different types of Thread Priorities in Java? And what is the default
priority of a thread assigned by JVM?
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.
❖ ‘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.
• 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.
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?
• In case the Cloneable interface is not implemented and just the method is overridden, it
results in CloneNotSupportedException in Java.
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.
❖ 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:
❖ When the index position is 1 then the memory address is calculated by using the
❖ Formula:
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.
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.
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.
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.
class GFG {
+ GFG.ctr);
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.
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.
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.
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.
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.
Mainly used to delay a thread for Mainly used to pause a thread until
some specific time duration. notified by another thread.
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.
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
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?
This method can access only static This method can access both static
members of the class and non-static methods of the class.
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.
// 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.
Abstract Class has members like All class members are public by
protected, private, etc. default.
Aggregation Composition
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
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.
import java.util.*;
// Driver Class
class GFG {
// Main Function
// using Arrays.asList
System.out.println(conv);
// Objectp[] toArray()
import java.io.*;
import java.util.List;
import java.util.ArrayList;
// Driver Class
class GFG {
// Main Function
// List declared
List<Integer>
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(2);
arr.add(1);
// Conversion
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;
}
Collection Collections
It provides the methods that can be It provides static methods that can be
used for the data structure. used for various operations.
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.
Array Collections
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
Iterator ListIterator
HashMap HashTable
Iterator Enumeration
Comparable Comparator
Set Map
The set can sort only one null The map can sort multiple null
value. values.
Errors Exceptions
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.
this( ) super( )
Access the methods of the same Access the methods of the parent
class. class.
Process Thread
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.
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
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.
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