1. What kind of variables can a class consist of?
Ans:
Class variables − Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a block. There would only
be one copy of each class variable per class, regardless of how many objects are created
from it.
Instance variables − Instance variables are declared in a class, but outside a method.
When space is allocated for an object in the heap, a slot for each instance variable value is
created. Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout
the class.
Local variables − Local variables are declared in methods, constructors, or blocks. Local
variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor, or block.
public class VariableExample{
int myVariable; //instance variable
static int data = 30; //class variable
public static void main(String args[]){
int a = 100; //local variable
VariableExample obj = new VariableExample();
[Link]("Value of instance variable myVariable:
"+[Link]);
[Link]("Value of static variable data:
"+[Link]);
[Link]("Value of local variable a: "+a);
}
}
What is Singleton’s class?
Ans:
• Singleton pattern is one of the simplest design patterns in Java.
• This pattern involves a single class which is responsible to create an object while
making sure that only single object gets created.
• This class provides a way to access its only object which can be accessed directly
without need to instantiate the object of the class.
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
[Link]("Hello World!");
}
}
2. List the three steps for creating an Object for a class.
Ans:
An object is created from a class using the new keyword.
There are three steps when creating an object from a class −
Declaration − A variable declaration with a variable name with an object type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
public class Sample {
public static void main (String args []){
Sample s = new Sample ();
}
}
3. When is a byte datatype used?
Ans;
The byte data type is an example of primitive data type.
Its value-range lies between -128 to 127 (inclusive).
Its minimum value is -128 and maximum value is 127.
Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings
is most required.
It can also be used in place of "int" data type
4. What do you mean by Access Modifier?
Ans:
The access specifiers are used to define the access restriction on the class and members
of a class.
The private access modifier is the most restrictive access level. Class and interfaces
cannot be private. Members that are declared private can not be accessed outside the
class.
The public access modifier can be associated with class, method, constructor, interface,
etc. public can be accessed from any other class. Therefore, fields, methods, blocks
declared inside a public class can be accessed from any class.
The protected access modifier can be associated with variables, methods, and
constructors, which are declared protected in a superclass can be accessed only by the
subclasses in other package or any class within the package of the protected members'
class.
The default access modifier does not have keyword a variable or method declared
without any access control modifier is available to any other class in the same package.
Ans:-
The parseInt() method is a method of Integer class under [Link] package
static int parseInt(String s)
static int parseInt(String s, int radix)
s − This is a string representation of decimal.
radix − This would be used to convert String s into integer.
5. When is a super keyword used?
Ans: The super keyword in Java is a reference variable which is used to refer immediate
parent class object
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. [Link](color);//prints color of Dog class
8. [Link]([Link]);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. [Link]();
15. }}
super can be used to invoke immediate parent class method.
The super keyword can also be used to invoke parent class method. It
should be used if subclass contains the same method as parent class.
In other words, it is used if method is overridden.
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){[Link]("eating bread...");}
6. void bark(){[Link]("barking...");}
7. void work(){
8. [Link]();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. [Link]();
16. }}
super() can be used to invoke immediate parent class constructor.
The super keyword can also be used to invoke the parent class
constructor.
Let's see a simple example:
1. class Animal{
2. Animal(){[Link]("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. [Link]("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
6. What’s the purpose of using Break in each case of Switch Statement?
Ans:
In a switch-case statement, the break is used to terminate a case and
prevent the program from falling through to the next case. Without a
break, the program will continue executing the subsequent case statements
until it encounters a break or reaches the end of the switch block
switch (value) {
case 1:
printf("One\n");
break; // Terminates the case here
case 2:
printf("Two\n");
// No break here, so it will continue to case 3
case 3:
printf("Three\n");
break;
}
7. How can we execute any code even before the main method?
Ans:
Yes, we can execute a java program without a main method by using
a static block.
Static block in Java is a group of statements that gets executed only
once when the class is loaded into the memory by Java ClassLoader,
It is also known as a static initialization block. Static initialization
block is going directly into the stack memory.
class StaticBlock_EX{
static{
[Link]("class without a main method");
[Link](0);
}
}
In the above example, we can execute a java program without a main
method (works until Java 1.6 version).
Java 7 and newer versions don’t allow this because JVM checks the
presence of the main method before initializing the class.
8. Can we use a class’s default constructor even if an explicit constructor is
defined?
Ans: In Java, if you define an explicit constructor for a class, the compiler
does not automatically provide a default constructor. The default
constructor is only generated if no constructors are explicitly declared in
the class. If you want to have a default constructor in addition to explicit
constructors, you must define it yourself.
Here’s an example to illustrate this in Java:
Java
public class Example {
int value;
// Explicit constructor
public Example(int newValue) {
value = newValue;
}
// User-defined default constructor
public Example() {
value = 0;
}
}
public class Main {
public static void main(String[] args) {
Example obj1 = new Example(); // Allowed, calls user-defined default
constructor
Example obj2 = new Example(10); // Allowed, calls explicit
constructor with parameter
}
}
In the Example class above, we have an explicit constructor that takes
an int parameter.
We also define a default constructor that initializes value to 0.
This allows us to create instances of Example with or without
providing an initial value.
Without the user-defined default constructor, you would not be able
to instantiate Example using new Example() without passing
parameters.
9. Can we override a method by using the same method name and arguments
but different return types?
Ans: In Java, method overriding is a concept where a method in a subclass
has the same name, parameters, and compatible return type as a method
in its superclass.
The return type is considered compatible if it is the same or a subtype
(covariant return type) of the method’s return type in the superclass1
Here’s a simple example:
class Animal {
Animal getAnimal() {
return new Animal();
}
}
class Dog extends Animal {
@Override
Dog getAnimal() {
return new Dog(); // This is allowed because Dog is a subtype of
Animal
}
}
In the example above, the getAnimal method in the Dog class
overrides the getAnimal method in the Animal class.
The return type Dog is a subclass of Animal, making it a compatible
return type.
You cannot override a method if the return type is not compatible.
For instance, if the superclass method returns an Animal, you cannot
override it in the subclass to return a String, as they are not related
in the class hierarchy and String is not a subtype of Animal.
To summarize, overriding a method with a different return type is
possible only if the new return type is a subclass of the original return
type,
10. What is a Comparable Interface?
Ans: Java Comparable interface is used to order the objects of the
user-defined class.
This interface is found in [Link] package and contains only one
method named compareTo(Object).
It provides a single sorting sequence only, i.e., you can sort the
elements on the basis of single data member only.
compareTo(Object obj) method:-
public int compareTo(Object obj):
It is used to compare the current object with the specified object.
It returns positive integer, if the current object is greater than the
specified object.
negative integer, if the current object is less than the specified object.
zero, if the current object is equal to the specified object.
Methods of Java Comparator Interface
Method Description
public int compare(Object obj1, Object obj2) It compares the first object with the second object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
11. Why IS the Java application platform independent?
Ans: Java is known for its platform independence, which means that Java
applications can run on any device or operating system.
Here’s how it works:
Compilation: When you compile a Java program, the Java compiler
(javac) converts the source code into bytecode
JVM: This bytecode is not specific to any type of hardware or
operating system. Instead, it is executed by the JVM, which is a
platform-dependent component
Execution: The JVM reads the bytecode and translates it into native
machine code that can be executed directly by the hardware
It’s important to note that while Java itself is platform-independent,
the JVM is platform-dependent.
12. What are the actions present in the JVM?
Ans: The Java Virtual Machine (JVM) performs a series of actions to run Java
applications.
Class Loading: The JVM loads class files into memory.
Execution: The JVM’s execution engine interprets the bytecode, or compiles it into
native machine code using the Just-In-Time (JIT) compiler, and executes it
1. Runtime Memory Management: The JVM manages and optimizes memory usage
during runtime, which includes the heap for object allocation, stack for method calls,
and method area for class data and code.
2. Garbage Collection: The JVM automatically manages the deletion of objects that are no
longer needed by the application to free up memory resources.
3. JVM Instructions: The JVM has instructions for tasks such as load and store, arithmetic
operations, type conversion, object creation and manipulation, operand stack
management (push/pop), control transfer (branching), method invocation and return
13. What is the current version of JDK?
Ans:17
14. Which data structure set is used?
Ans:
In Java, the Set interface is part of the Java Collections Framework and
represents a collection of objects where each object is unique, meaning no
duplicates are allowed.
The Set interface extends the Collection interface and is implemented by
several classes
HashSet:. It uses a hash table for storage, providing constant time
performance for basic operations like add, remove, and contains, assuming
the hash function disperses elements properly1
LinkedHashSet: This is a subclass of HashSet with a predictable iteration
order. It maintains a doubly-linked list across all elements, which defines
the iteration ordering, which is typically the order in which elements were
inserted into the set.
TreeSet: This class implements the NavigableSet [Link] stores
elements in a sorted (ascending) order and provides guaranteed log(n)
time cost for basic operations
15. Is wrapper classes override hashcode and equals method?
Ans:
Yes, in Java, wrapper classes like Integer, Character, Boolean, and
others do override the hashCode and equals methods.
The equals method is overridden to provide value-based equality,
which means two objects of a wrapper class are considered equal if
they represent the same value, even if they are different objects in
memory.
For example, two Integer objects with the value 5 would be
considered equal
Integer a = new Integer(5);
Integer b = new Integer(5);
boolean isEqual = [Link](b); // This will be true
The hashCode method is also overridden to ensure that two equal
objects will have the same hash code, which is a requirement for
objects that are stored in hash-based collections like HashSet or
HashMap.
This is important because it allows wrapper objects to be used
effectively as keys in hash-based collections
16. What is the default method in the java 8 interface?
Ans: In Java 8, the concept of default methods was introduced in
interfaces.
A default method is a method that has an implementation within the
interface itself.
This was a significant addition because it allows interfaces to have
methods with a body, which wasn’t possible in earlier versions of
Java.
Here’s why default methods are useful:
They enable interfaces to provide a default implementation for a
method, which all implementing classes can use without the need to
override it.
They help in evolving interfaces without breaking existing
implementations. If a new method is added to an interface, all the
classes that implement this interface would not need to change unless
they want to override the new method.
The default method is defined using the default keyword before the
method signature, and it must provide a body.
Here’s an example:
public interface MyInterface {
// Abstract method
void abstractMethod();
// Default method
default void defaultMethod() {
[Link]("Default Method Executed");
}
}
In the example above, defaultMethod provides a “default”
implementation. Classes implementing MyInterface can call
defaultMethod directly, or they can provide their own
implementation
17. What is the difference between StringBuffer and StringBuilder?
Ans: Strings in Java are the objects that are backed internally by a
char array.
Since arrays are immutable(cannot grow), Strings are immutable as
well.
Whenever a change to a String is made, an entirely new String is
created. java provides multiple classes through which strings can be
used. Two such classes are StringBuffer and StringBuilder
In Java, both StringBuffer and StringBuilder are classes used to create
mutable strings
18. What exceptional handling
Ans: Exception handling in Java is a powerful mechanism to handle
runtime errors, ensuring that the normal flow of the application can be
maintained.
It allows a program to continue executing even after encountering an error,
rather than crashing completely.
Here’s a brief overview of how exception handling works in Java:
Try Block: You write the code that might throw an exception within a
try block.
Catch Block: If an exception occurs, it is caught by a catch block that
follows the try block. You can have multiple catch blocks to handle
different types of exceptions.
Finally Block: A finally block contains code that is always executed,
whether an exception is thrown or not. It’s typically used for cleanup
code.
Throw: You can also manually throw an exception using the throw
keyword.
Throws: If a method is capable of causing an exception that it does
not handle, it must declare this behavior so that callers of the method
can guard themselves against that exception.
Here is an example of exception handling in Java:
public class ExceptionExample {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
} finally {
[Link]("This is the finally block");
}
}
}
In the example above, dividing by zero would cause an
ArithmeticException, which is caught and handled in the catch block.
The finally block is executed regardless of the exception.
The advantage of exception handling is that it separates the error-
handling code from the regular code and provides a structured way
to handle error conditions.
Exception handling is essential for building robust applications that
can handle unexpected events without failing.
19. What is JDBC
Ans: JDBC stands for Java Database Connectivity.
It is an API (Application Programming Interface) provided by Java
that allows Java applications to interact with databases.
JDBC serves as a bridge between Java programs and data sources,
enabling programs to execute SQL statements, retrieve results, and
perform other database operations.
20. What is the JDBC driver
Ans: A JDBC driver is a software component that enables Java
applications to interact with databases.
It acts as a bridge, translating Java calls into database-specific
commands. The JDBC driver interface allows applications to execute
queries and update data across different database systems
21. What are the steps involved in database connectivity
Ans: To connect a Java application with a database using JDBC, you
typically follow these steps:
Register the Driver class: Load the JDBC driver by calling
[Link]() with the driver’s class name. This step is optional
since JDBC 4.0 as the driver is automatically loaded from the
classpath1.
Create a Connection object: Use [Link]() with
the appropriate URL, username, and password to establish a
connection to the database1.
Create a Statement object: Create a Statement or PreparedStatement
object to help you execute SQL queries1.
Execute the query: Use the executeQuery() method of the Statement
object to run the SQL query and return a ResultSet if it’s a SELECT
query, or use executeUpdate() for queries like INSERT, UPDATE, or
DELETE1.
Process the ResultSet: If you have a ResultSet, process the data
retrieved from the database
Close the connection: Finally, close the Connection, Statement, and
ResultSet objects to free up resources
[Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}catch(Exception e){ [Link](e);}
}
22. What is the difference between while and do-while
Ans: The while and do-while loops are both used to execute a block of
code multiple times, but they differ in their execution check:
while loop: It checks the condition before executing the block of code. If
the condition is false from the beginning, the code block inside the while
loop may not execute even once.
while (condition) {
// Code to execute
}
do-while loop: It executes the code block once before checking the
condition. This means the code block will always execute at least once,
regardless of the condition being true or false.
do {
// Code to execute
} while (condition);
Here’s a simple way to remember it:
Use a while loop when you want to check the condition first.
Use a do-while loop when you want the code to run at least once and
check the condition after.
int i = 1;
int i = 1;
do {
while (i <= 5) {
sop("%d\n", i); sop("%d\n", i);
i++; i++;
} } while (i <= 5);
return 0; return 0;
23. From which method the execution of java programs begins?
Ans: The execution of Java programs begins from the main() method.
This method serves as the entry point for the Java Virtual Machine (JVM)
to start the execution of a Java application. The main() method must have
a specific signature to be recognized by the JVM:
public static void main(String[] args) {
// Code goes here
}
Here’s a breakdown of the main() method signature:
public: An access specifier that allows the JVM to access the method.
static: Indicates that the method can be called without creating an
instance of the class.
void: Specifies that the method does not return any value.
main: The name of the method that the JVM looks for as the starting
point.
String[] args: An array of String that can store command-line
arguments passed to the program.
If the main() method is not present or not correctly defined, the JVM
will not execute the program and will throw an error
24. Which name will be checked by the compiler for the execution of the
program?
Ans: In Java, the compiler does not execute the program; it only compiles
the source code into bytecode.
The Java Virtual Machine (JVM) is responsible for executing the compiled
bytecode.
When you run a Java program, the JVM looks for the main() method in the
class you specify and starts execution from there.
To execute a Java program, you use the java command followed by the class
name. The class name should be the name of the class containing the
main() method without the .class extension. For example, if your class file
is [Link], you would execute the program using:
The JVM will then look for the public static void main(String[] args)
method in MyProgram and begin execution from that point.
25. Which name will be checked by the JVM after compiling the program?
Ans: After a Java program is compiled, the Java Virtual Machine (JVM)
checks the name of the main class when executing the program.
The main class is the one that contains the main() method, which serves
as the entry point for the application.
The JVM uses the class name to locate and load the correct .class file into
memory for execution1.
During the execution phase, the JVM goes through several stages,
including:
Class Loading: The main class is loaded into memory.
Bytecode Verification: The bytecode of the loaded class is verified for
correctness.
Just-In-Time Compilation: The bytecode may be compiled to native
machine code for better performance.
26. Can we have the filename and class name as same?
Ans: Yes, in Java, it is a common convention to have the filename and the
public class name be the same.
If a public class is defined within a file, the filename must match the class
name exactly, including case sensitivity1.
Here’s a breakdown of the rules:
If the class is public, the filename must be the same as the class name.
If there is no public class within the file, the filename can be different from
the class names inside the file1.
For example:
If you have a public class named MyClass, the filename should be
[Link].
If your class is not public, you can name the file something else, like
[Link], but it’s still a good practice to match the filename with the
class name for clarity and maintainability
27. Tell me about Hash Map implementation
Ans: A HashMap in Java is an implementation of the Map interface that
provides efficient storage and retrieval of key-value pairs.
Data Structure: Internally, HashMap uses an array of nodes, where each
node is a bucket that can hold one or more entries (key-value pairs). These
entries are instances of an inner class called Entry<K,V>.
Hashing: When a key-value pair is added to a HashMap, the key’s
hashCode() method is called to compute a hash code, which is then used to
determine the index of the bucket where the entry should be stored.
Collision Handling: If two keys produce the same hash code and are
allocated to the same bucket, a collision occurs. HashMap handles
collisions by using a linked list or a balanced tree (since Java 8) to store
multiple entries in the same bucket.
Dynamic Resizing: The HashMap can dynamically resize its array of
buckets if the number of entries exceeds a certain threshold defined by the
load factor.
Performance: The get and put operations typically have constant-time
complexity, O(1), but in the worst-case scenario (e.g., many hash
collisions), the complexity could degrade to O(n).
Null Values: HashMap allows one null key and multiple null values.
import [Link];
public class Example {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
[Link]("apple", 10);
[Link]("banana", 20);
[Link]("cherry", 30);
[Link]("Value for 'apple': " + [Link]("apple"));
}
}
Method:--
put(K key, V value):
Associates the specified value with the specified key in the map.
If the map already contains a mapping for the key, the old value is replaced.
Example:
HashMap<String, Integer> map = new HashMap<>();
[Link]("vishal", 10);
[Link]("sachin", 30);
[Link]("vaibhav", 20);
get(Object key):
Returns the value associated with the specified key.
Example:
if ([Link]("vishal")) {
Integer a = [Link]("vishal");
[Link]("Value for key \"vishal\" is: " + a);
}
isEmpty():
Returns true if the map contains no key-value mappings.
Example:
boolean empty = [Link]();
size():
Returns the number of key-value mappings in the map.
Example:
int mapSize = [Link]();
28. Difference between Linked List and Array List
Ans:
The ArrayList and LinkedList classes in Java both implement the List
interface but have some key differences in their implementation and
performance:
Underlying Data Structure:
ArrayList is backed by a dynamic array. This means that elements are
stored in contiguous memory locations1.
LinkedList is implemented as a doubly linked list. Each element (node)
contains pointers to both the next and previous nodes1.
Performance:
ArrayList offers fast random access to elements because it uses an array
internally. Accessing any element takes constant time O(1)1.
LinkedList provides faster insertion and deletion at the cost of slower
random access. Access time for any element is O(n) because it requires
traversal from the start or end to the desired index1.
Memory Overhead:
ArrayList has less memory overhead per element because it only stores the
data and the array’s size1.
LinkedList has more memory overhead because each node stores the data
and two references (next and previous)1.
Manipulation:
In ArrayList, adding or removing elements can be slow because it may
require resizing the array and shifting elements1.
In LinkedList, adding or removing elements is generally faster, especially
if the operations are near the head or tail, because no shifting is required1.
Use Cases:
ArrayList is preferable when you need efficient random reads and don’t
frequently insert or remove elements2.
LinkedList is better when you need to frequently add or remove elements
from the beginning, middle, or end of the list
29. How to make a map a synchronized map
Ans: In Java, you can make a map synchronized by using the
[Link]() method. This method wraps an existing
map and returns a synchronized (thread-safe) version of it. Here’s how you
can synchronize a HashMap:
import [Link];
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
// Creating a HashMap
Map<String, Integer> map = new HashMap<>();
// Synchronizing the HashMap
Map<String, Integer> synchronizedMap =
[Link](map);
// Now 'synchronizedMap' is thread-safe
}
}
When you have a synchronized map, it’s important to synchronize on the
map when iterating over any of its collection views, such as keySet,
entrySet, or values.
30. What is the difference between [Link](m) and
concurrent hash map
Ans The difference between [Link](m) and
ConcurrentHashMap lies in their approach to thread-safety and performance:
[Link](m):
Wraps a given map and synchronizes all of its methods.
Ensures thread safety by making each method call atomic and mutually
exclusive.
Can lead to contention and reduced throughput if many threads access the map
concurrently because only one thread can access the map at a time11.
Requires manual synchronization when iterating over collections views (like
keySet, entrySet, or values) to avoid ConcurrentModificationException11.
ConcurrentHashMap:
Does not synchronize every method call but uses a concurrent data structure
that allows concurrent reads and updates.
Provides better scalability by dividing the map into segments and locking only a
portion of the map for updates11.
Allows multiple readers to access the map without blocking, and a limited
number of writers can modify it concurrently without causing contention11.
Does not throw ConcurrentModificationException if the map is modified during
iteration11.
Does not allow null keys or values, unlike [Link](m)
which does
31. Difference between forEach and iterator
Ans:The forEach method and an Iterator are both used to traverse
collections in Java
Modification: With an Iterator, you can remove elements from the
collection during iteration using the remove() method.
The forEach method does not support structural modifications to the
collection during iteration.
Use Cases: If you need to modify the collection while iterating, you should
use an Iterator. If you’re only reading from the collection or you prefer a
cleaner syntax, forEach is the better choice
Iterator<String> it = [Link]();
while ([Link]()) {
String element = [Link]();
// You can remove elements here
[Link]();
}
[Link](element -> {
[Link](element);
// You cannot remove elements here
});
In summary, choose an Iterator when you need to modify the collection during
iteration, and use forEach for more concise code when modification is not
required.
32. Can we instantiate the interface? If not, then why?
Ans: No, you cannot instantiate an interface. Generally, it contains abstract
methods (except default and static methods introduced in Java8), which are
incomplete.
Still if you try to instantiate an interface, a compile time error will be generated
saying “MyInterface is abstract; cannot be instantiated”.
In the following example we an interface with name MyInterface and a class
with name InterfaceExample.
In the interface we have an integer filed (public, static and, final) num and
abstract method demo().
interface MyInterface{
public static final int num = 30;
public abstract void demo();
}
public class InterfaceExample implements MyInterface {
public void demo() {
[Link]("This is the implementation of the demo method");
}
public static void main(String args[]) {
MyInterface interfaceObject = new MyInterface();
[Link]([Link]);
}
}
To access the members of an interface you need to implements it and provide
implementation to all the abstract methods of it.
interface MyInterface{
public int num = 30;
public void demo();
}
public class InterfaceExample implements MyInterface {
public void demo() {
[Link]("This is the implementation of the demo method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
[Link]();
[Link]([Link]);
}
}
33. Can we create non static variables in an interface using java?
Ans: Interface in Java is similar to class but, it contains only abstract
methods and fields which are final and static.
Since all the methods are abstract you cannot instantiate it. To use it, you
need to implement this interface using a class and provide body to all the
abstract methods int it.
No you cannot have non-static variables in an interface. By default,
All the members (methods and fields) of an interface are public
All the methods in an interface are public and abstract (except static and
default).
All the fields of an interface are public, static and, final by default
If you declare/define fields without public or, static or, final or, all the three
modifiers. Java compiler places them by default
34. What is the difference between classNotFoundException and
NoClassDefError in which situation will we face this?
Ans: The ClassNotFoundException and NoClassDefFoundError in Java are
related to the absence of classes at runtime, but they occur in different situations
and have distinct causes
ClassNotFoundException:
It is a checked exception that occurs when an application tries to load a class at
runtime using methods like [Link]() or [Link]() and the
class is not found in the classpath11.
This exception often occurs when you try to run an application without updating
the classpath with the required JAR files or when there is a discrepancy in the
class loader hierarchy11.
It must be explicitly handled in the code, typically with a try-catch block11.
NoClassDefFoundError:
It is an error, not an exception, which means it’s a more serious problem that is
not meant to be caught22.
This error occurs when a class was present during compile-time (hence the code
compiled successfully), but the class definition was not found in the classpath at
runtime22.
It can happen if a class fails to load due to a static initialization failure or if the
class was removed after the application was compiled.
35. Can we declare an interface with in another interface in java?
Ans: Java allows declaring interfaces within another interface, these are
known as nested interfaces.
While implementing you need to refer to the nested interface as
[Link].
Example
In the following Java example, we have an interface with name
Cars4U_Services which contains two nested interfaces: CarRentalServices
and, CarSales with two abstract methods each.
From a class we are implementing the two nested interfaces and providing
body for all the four abstract methods.
interface Cars4U_Services {
interface CarRentalServices {
public abstract void lendCar();
public abstract void collectCar();
}
interface CarSales{
public abstract void buyOldCars();
public abstract void sellOldCars();
}
}
public class Cars4U implements Cars4U_Services.CarRentalServices,
Cars4U_Services.CarSales {
public void buyOldCars() {
[Link]("We will buy old cars");
}
public void sellOldCars() {
[Link]("We will sell old cars");
}
public void lendCar() {
[Link]("We will lend cars for rent");
}
public void collectCar() {
[Link]("Collect issued cars");
}
public static void main(String args[]){
Cars4U obj = new Cars4U();
36. Can we declare an interface as final in java?
Ans: Interface in Java is similar to class but, it contains only abstract
methods and fields which are final and static.
Since all the methods are abstract you cannot instantiate it. To use it, you
need to implement this interface using a class and provide body to all the
abstract methods int it.
If you declare a class final cannot extend it. If you make a method final you
cannot override it and, if you make a variable final you cannot modify it.
i.e. use final with Java entities you cannot modify them further.
If you make an interface final, you cannot implement its methods which
defies the very purpose of the interfaces. Therefore, you cannot make an
interface final in Java. Still if you try to do so, a compile time exception is
generated saying “illegal combination of modifiers − interface and final”.
In the following example we are defining an interface with name MyInterface and using the final
modifier with it.
public final interface MyInterface{
public static final int num = 10;
public abstract void demo();
}
Compile time error
37. Can we define an interface inside a Java class?
Ans: Yes, you can define an interface inside a class and it is known as a
nested interface. You can’t access a nested interface directly; you need to
access (implement) the nested interface using the inner class or by using
the name of the class holding this nested interface.
public class Sample {
interface myInterface {
void demo();
}
class Inner implements myInterface {
public void demo() {
[Link]("Welcome to Tutorialspoint");
}
}
public static void main(String args[]) {
Inner obj = new Sample().new Inner();
[Link]();
}
}
Output
Welcome to Tutorialspoint
38. Can we define a class inside a Java interface?
Ans Yes, you can define a class inside an interface. In general, if the
methods of the interface use this class and if we are not using it anywhere
else we will declare a class within an interface.
interface Library {
void issueBook(Book b);
void retrieveBook(Book b);
public class Book {
int bookId;
String bookName;
int issueDate;
int returnDate;
}
}
public class Sample implements Library {
public void issueBook(Book b) {
[Link]("Book Issued");
}
public void retrieveBook(Book b) {
[Link]("Book Retrieved");
}
public static void main(String args[]) {
Sample obj = new Sample();
[Link](new [Link]());
[Link](new [Link]());
}
}
Output
Hello welcome to tutorialspoint
If we need to provide a default implementation of the interface, we will define a class inside an
interface as:
Example
interface Library {
void issueBook(Book b);
void retrieveBook(Book b);
public class Book implements Library {
int bookId;
String bookName;
int issueDate;
int returnDate;
public void issueBook(Book b) {
[Link]("book issued");
}
public void retrieveBook(Book b) {
[Link]("book retrieved");
}
}
}
public class Sample {
public void demo() {
[Link]("Hello welcome to tutorialspoint");
}
public static void main(String args[]) {
Sample obj = new Sample();
[Link]();
}
}
39. Can we define constructor inside an interface in java?
Ans No, you cannot have a constructor within an interface in Java.
You can have only public, static, final variables and, public, abstract, methods
as of Java7.
From Java8 onwards interfaces allow default methods and static methods.
From Java9 onwards interfaces allow private and private static methods.
Moreover, all the methods you define (except above mentioned) in an
interface should be implemented by another class (overridden). But, you
cannot override constructors in Java.
Still if you try to define constructors in an interface it generates a compile
time error.
Example
In the following Java program, we are trying to define a constructor within an interface.
public interface MyInterface{
public abstract MyInterface();
/*{
[Link]("This is the constructor of the interface");
}*/
public static final int num = 10;
public abstract void demo();
}
Compile time error
40. Can we write an interface without any methods in java?
Ans Yes, you can write an interface without any methods. These are
known as marking interfaces or, tagging interfaces.
A marker interface i.e. it does not contain any methods or fields by
implementing these interfaces a class will exhibit a special behavior with
respect to the interface implemented.
41. Can we declare the method of an Interface final in java?
Ans By default, all the methods of an interface are public and abstract.
For example, In the following Java program, we are having a declaring a
method with name demo.
public interface MyInterface{
void demo();
}
it gets compiled without errors. You can observe that the compiler has placed
the public and, abstract modifiers before the method by default
In addition to this as of Java9 you can have default, static, private, private
and static with the methods of an interface. Except these you cannot use any
other modifiers with the methods of an interface.
if you declare a method final you cannot override/implement it and, an
abstract method must be overridden or implemented. Therefore, you cannot
declare the method of an interface final.
If you still do so, it generates a compile time error saying “modifier final not
allowed here”.
42. Can we overload methods of an interface in Java?
Ans Overloading is one of the mechanisms to achieve polymorphism where
a class contains two methods with the same name and different parameters.
Whenever you call this method the method body will be bound with the
method call based on the parameters.
Yes, you can have overloaded methods (methods with the same name
different parameters) in an interface. You can implement this interface and
achieve method overloading through its methods.
import [Link];
interface MyInterface{
public void display();
public void display(String name, int age);
}
public class OverloadingInterfaces implements MyInterface{
String name;
int age;
public void display() {
[Link]("This is the implementation of the display method");
}
public void display(String name, int age) {
[Link]("Name: "+name);
[Link]("Age: "+age);
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
OverloadingInterfaces obj = new OverloadingInterfaces();
[Link]();
[Link](name, age);
}
}
43. What are keywords, data type, constant and variable
Ans: Keywords: These are predefined, reserved words used by
programming languages that have special meanings. Keywords are part of
the language’s syntax and cannot be used as identifiers for variables or
other user-defined elements1.
Data Types: A data type specifies the type of data that a variable can hold,
such as integers, floating-point numbers, characters, etc. Data types define
the operations that can be performed on the data and the form in which
they are stored2.
Constants: Constants are values that do not change during the execution
of a program. Once a constant is defined and assigned a value, it cannot be
altered. Constants are used to make code more readable and maintainable3.
Variables: Variables are named storage locations that can hold data. The
data stored in a variable can be changed during program
execution. Variables are essential for storing and manipulating data in
computer programs
44. What is the conditional statement?
Ans: In Java, a conditional statement is used to perform different actions
based on whether a specified condition is true or false. It’s a way to control
the flow of execution in a program.
if statement: It tests a condition and executes a block of code if the condition
is true.
if (condition) {
// code to execute if condition is true
}
if-else statement: It provides an alternative block of code to execute if the
condition is false
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
else-if ladder: It allows multiple conditions to be tested in sequence, executing
the block of code corresponding to the first true condition.
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if none of the conditions are true
}
switch statement: It tests the variable against multiple cases and executes the
block of code corresponding to the matching case.
switch (variable) {
case value1:
// code if variable equals value1
break;
case value2:
// code if variable equals value2
break;
default:
// code if variable does not match any case
break;
}
45. What is if—else statement
Ans: An if-else statement is a control flow statement in programming
that allows you to execute different blocks of code based on whether a
condition is true or false. Here’s the basic structure:
Java
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
The if part evaluates the condition inside the parentheses.
If the condition is true, the code block following the if is executed.
If the condition is false, the code block following the else is executed
instead11.
This statement is fundamental for decision-making in programs, enabling
them to respond dynamically to different situations
46. What are switch case statements?
Ans In Java, a switch case statement is a control flow structure that
allows you to execute different parts of code based on the value of an
expression. It’s an alternative to a series of if-else statements and is
particularly useful when you have a variable that can take one out of a
small set of possible values.
Here’s how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
If no case matches, and a default case is provided, the code in the default
block is executed.
Here’s the syntax for a switch case statement in Java:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
case x: A label that matches a possible value of the expression.
break: Terminates the switch block and transfers control to the code
following the switch statement. Without it, the program continues to the
next case (fall-through).
default: An optional case that runs if none of the case labels match the
expression.
Here’s an example that uses a switch case to print the name of a day based
on its number:
int day = 4;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day number");
break;
}
47. What is the iterative statement?
Ans In Java, an iterative statement is a statement that allows a block of
code to be executed repeatedly based on a condition. These are commonly
known as loops and are a fundamental part of controlling the flow of a
program. Java provides several types of iterative statements:
for loop: Used for iterating a set number of times or over a range of values.
for (int i = 0; i < 10; i++) {
// Code to be executed
}
while loop: Executes a block of code as long as a specified condition is true.
while (condition) {
// Code to be executed
}
do-while loop: Similar to the while loop, but it guarantees that the block of
code is executed at least once.
do {
// Code to be executed
} while (condition);
for-each loop: Enhanced for loop for iterating over elements in an array or
a collection.
for (type var : array) {
// Code to be executed
}
48. What is sorting
Ans Sorting in Java refers to the process of arranging elements of a list
or array in a specific order, typically in ascending (natural order) or
descending order. This can be done with numerical values, characters,
strings, or even objects based on a property.
Java provides several ways to perform sorting:
Using Loops: Implementing basic sorting algorithms like bubble sort,
selection sort, or insertion sort using loops.
Time Complexity: Generally O(N^2) for simple algorithms.
Auxiliary Space: O(1) since it’s an in-place sorting method.
Using [Link]() Method: A convenient method for sorting arrays. It
uses a Dual-Pivot Quicksort algorithm for primitives and TimSort for object
arrays.
Time Complexity: O(N log N) on average.
Auxiliary Space: O(1) for primitives and O(N) for object arrays due to the
use of TimSort.
Using [Link]() Method: Used to sort lists like ArrayList and
LinkedList. It also uses TimSort.
Time Complexity: O(N log N) on average.
Auxiliary Space: O(N) due to the use of TimSort.
Using Streams: Java 8 introduced streams, which can be used to sort
collections in a functional style.
Here’s an example of sorting an array of integers using [Link]():
Java
import [Link];
public class Main {
public static void main(String[] args) {
int[] numbers = { 3, 1, 4, 1, 5, 9 };
[Link](numbers);
[Link]([Link](numbers)); // Output: [1, 1, 3, 4,
5, 9]
}
}
And here’s an example of sorting a list of strings using [Link]():
import [Link];
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
[Link]("Orange");
[Link]("Apple");
[Link]("Banana");
[Link](fruits);
[Link](fruits); // Output: [Apple, Banana, Orange]
}
}
49. Explain the type of user-defined function
Ans
In Java, user-defined functions, also known as methods, are blocks of code
designed to perform specific tasks. They are defined by the programmer
and can be called multiple times within a program to perform the operation
they are designed to do. Here are the components that make up a user-
defined function in Java:
1. Function Prototype (Declaration): This is where the method is declared
with its return type, name, and parameters (if any). It defines the method’s
signature.
Java
public int add(int a, int b);
2. Function Definition: This is the part of the method where the actual code
or logic is written. It’s where you implement what the method is supposed
to do.
Java
public int add(int a, int b) {
return a + b;
}
3. Calling Function (Accessing): This is when you invoke or call the method
to execute the code it contains.
Java
int sum = add(5, 10); // Calls the 'add' method
4. Function Argument (Parameter): These are the inputs you pass to the
method when you call it. They allow the method to accept data to work
with.
Java
public int add(int a, int b) { // 'a' and 'b' are parameters
return a + b;
}
5. Return Value by the Function: This is the output that a method sends back
to the caller. Not all methods have a return value; some may return void,
which means they do not return anything.
Java
public int add(int a, int b) {
return a + b; // The sum of 'a' and 'b' is returned
}
50. What is a recursive function?
Ans In Java, a recursive function is a method that calls itself to solve a
problem. It’s a powerful concept used to solve problems that can be broken
down into smaller, similar sub-problems. Here’s how it works:
Base Case: This is the condition under which the recursion ends. It’s the
simplest form of the problem that can be solved without further recursion.
Recursive Case: This is where the method calls itself with a modified
argument, moving closer to the base case.
For instance, let’s look at a simple example of a recursive method in Java
that calculates the factorial of a number:
class Factorial {
// Recursive method to calculate factorial
int fact(int n) {
if (n <= 1) // base case
return 1;
else
return n * fact(n - 1); // recursive case
}
}
class Main {
public static void main(String[] args) {
Factorial factorial = new Factorial();
[Link]("Factorial of 5 is " + [Link](5));
}
}
In this example, fact(1) is the base case, and fact(n) for n > 1 is the
recursive case. The method fact calls itself with n-1 until it reaches the base
case1.
51. What is stack
Ans In Java, a stack is a linear data structure that follows the Last-In-First-
Out (LIFO) principle.
This means that the last element added to the stack will be the first one to be
removed.
It’s used to store a collection of objects and is particularly useful for tasks
such as backtracking, parsing, and maintaining function calls (call stack).
Here’s a brief overview of the Stack class in Java:
Extends Vector: The Stack class extends the Vector class and provides
additional methods suitable for a stack.
Methods:
push(E item): Adds an item to the top of the stack.
pop(): Removes and returns the item at the top of the stack.
peek(): Returns the item at the top of the stack without removing it.
empty(): Checks if the stack is empty.
search(Object o): Searches for an object in the stack and returns its
position from the top.
Here’s an example of how you might use a stack in Java:
import [Link];
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
// Pushing elements onto the stack
[Link](10);
[Link](20);
[Link](30);
// Popping elements from the stack
while (![Link]()) {
int topElement = [Link]();
[Link](topElement);
}
}
}
In this example, the push method adds elements to the stack, and the pop
method removes them in the reverse order they were added, demonstrating
the LIFO behavior.
52. What is queue
Ans In Java, a queue is an interface that extends the Collection interface
and represents a collection of elements that are processed in a First-In-
First-Out (FIFO) order. This means that elements are added to the end of
the queue and removed from the beginning.
Here are some key points about the Queue interface in Java:
FIFO Principle: Elements are added at the rear and removed from the front,
adhering to the FIFO order.
Methods: The Queue interface provides several methods such as add(),
offer(), remove(), poll(), element(), and peek() for manipulating elements
in the queue1.
Implementations: Common classes that implement the Queue interface
include LinkedList, PriorityQueue, and ArrayDeque. Each of these classes
has its own specific use case and characteristics12.
Here’s a simple example of using a queue in Java:
import [Link];
import [Link];
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// Adding elements to the queue
[Link]("Element1");
[Link]("Element2");
[Link]("Element3");
// Accessing elements from the queue
[Link]("Head of queue: " + [Link]());
// Removing elements from the queue
while (![Link]()) {
[Link]("Removed: " + [Link]());
}
}
}
In this example, offer() is used to add elements to the queue, peek() to look
at the head of the queue without removing it, and poll() to remove and
return the head of the queue, demonstrating the FIFO behavior
53. What is a link list
Ans: In Java, the LinkedList class is part of the Java Collections
Framework and provides an implementation of a doubly linked list. Let’s
explore some key points about Java LinkedList:
Data Structure:
A linked list is a linear data structure where elements are stored in a
sequence of containers (nodes).
Each container holds data and has a reference to the next container in the
sequence.
Unlike arrays, linked lists allow for efficient insertions and removals of
elements from any position in the list.
Common Methods (among others):
add(E e): Appends an element to the end of the list.
add(int index, E element): Inserts an element at a specified position.
addAll(Collection<? extends E> c): Appends elements from a collection to
the end of the list.
addFirst(E e): Inserts an element at the beginning of the list.
addLast(E e): Appends an element to the end of the list.
clear(): Removes all elements from the list.
get(int index): Returns the element at a specified position.
remove(int index): Removes the element at a specified position.
Remember that LinkedLists are useful when you need dynamic sizing and
efficient insertions/removals
54. What is polymorphism
Ans:
Polymorphism refers to the ability of an object to take on multiple forms.
In simpler terms, it allows a single method or function to be displayed in
different ways.
Example: Consider a person who can simultaneously exhibit different
roles (e.g., a father, a husband, and an employee). Similarly, in
programming, polymorphism enables different behaviors for the same
method in various situations1.
Types of Polymorphism in Java:
Compile-Time Polymorphism (Static Polymorphism):
Achieved through function overloading or operator overloading.
Function Overloading: When multiple functions have the same name but
different parameters (number or type of arguments).
class Helper {
static int Multiply(int a, int b) {
return a * b;
}
static double Multiply(double a, double b) {
return a * b;
}
}
// Usage:
[Link]([Link](2, 4)); // Output: 8
[Link]([Link](5.5, 6.3)); // Output: 34.65
class Helper {
static int Multiply(int a, int b) {
return a * b;
}
static int Multiply(int a, int b, int c) {
return a * b * c;
}
}
// Usage:
[Link]([Link](2, 4)); // Output: 8
[Link]([Link](2, 7, 3)); // Output: 42
Runtime Polymorphism (Dynamic Method Dispatch):
Achieved through method overriding.
Resolves function calls to overridden methods at runtime.
Example:
class Animal {
public void animalSound() {
[Link]("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
[Link]("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
[Link]("The dog says: bow wow");
}
}
// Usage:
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();
[Link](); // Output: The animal makes a sound
[Link](); // Output: The pig says: wee wee
[Link](); // Output: The dog says: bow wow
Why Use Inheritance and Polymorphism?:
Code reusability: Inheritance allows us to reuse attributes and methods
from existing classes when creating new ones.
55. What is abstraction
Ans: Abstraction is a process of hiding the implementation details from the
user, only the functionality will be provided to the user. In other words, the
user will have the information on what the object does instead of how it does
it. In Java programming, abstraction is achieved using Abstract
classes and interfaces
Java Abstract Classes
A Java class which contains the abstract keyword in its declaration is known as
abstract class.
Java abstract classes may or may not contain abstract methods, i.e., methods
without body ( public void get(); )
But, if a class has at least one abstract method, then the class must be
declared abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all
the abstract methods in it.
To create an abstract class in Java, just use the abstract keyword before the class
keyword, in the class declaration.
/* File name : [Link] */
public abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
[Link]("Constructing an Employee");
[Link] = name;
[Link] = address;
[Link] = number;
}
public double computePay() {
[Link]("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
[Link]("Mailing a check to " + [Link] + " " + [Link]);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
You can observe that except abstract methods the Employee class is same as
normal class in Java. The class is now abstract, but it still has three fields, seven
methods, and one constructor.
If you want a class to contain a particular method but you want the actual
implementation of that method to be determined by child classes, you can declare
the method in the parent class as an abstract.
abstract keyword is used to declare the method as abstract.
You have to place the abstract keyword before the method name in the
method declaration.
An abstract method contains a method signature, but no method body.
Instead of curly braces, an abstract method will have a semoi colon (;) at the
end.
56. What is inheritance
Ans: A class that inherits the properties and method from parent class called
inheritance
Superclass (Parent Class): The existing class whose features are inherited is
called the superclass or parent class.
Subclass (Child Class): The new class created by inheriting properties from
the base class is called the subclass or child class. The subclass can add its
own fields and methods in addition to the superclass fields and methods.
Why Do We Need Java Inheritance?
Code Reusability: The code written in the superclass is common to all
subclasses. Child classes can directly use the parent class code.
Method Overriding: Method overriding (changing the implementation of a
method in the subclass) is achievable only through inheritance. It enables
runtime polymorphism.
Abstraction: Inheritance allows abstraction, where you don’t have to provide
all details. Abstraction shows only the functionality to the user.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance.
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical
inheritance.
57. What is a static keyword
58. What final in java
Ans:Final is keyword where we can use it with variable method and class
Final Variables:
When a variable is declared as final, its value cannot be changed once it has been
initialized.
This is useful for declaring constants or other values that should remain fixed
throughout the program.
Final Methods:
When a method is declared as final, it cannot be overridden by a subclass.
This is useful for methods that are part of a class’s public API and should not be
modified by subclasses.
Final Classes:
When a class is declared as final, it cannot be extended by a subclass.
This is useful for classes that are intended to be used as is and should not be
modified or extended.
Initialization:
Final variables must be initialized either at the time of declaration or in the
constructor of the class.
This ensures that the value of the variable is set and cannot be changed.
59. What is the difference between abstract and interface?
60. Between HashSet and TreeSet collections in Java, which one is better?
Ans:
HashSet is faster, unsorted, and efficient for basic operations.
TreeSet is slower but provides sorted elements and maintains order
61. When does JVM call the finalize() method?
Ans The finalize() method in Java is invoked by the JVM when an object
becomes eligible for garbage collection.
It’s a crucial part of the cleanup process, allowing you to release system
resources or perform other necessary tasks before the object is reclaimed by
the garbage collector
The primary purpose of the finalize() method is to perform cleanup activities
on an object just before it is destroyed by the garbage collector
When an object becomes eligible for garbage collection, the JVM calls the
finalize() method (if it has been overridden in the object’s class).
This happens just before the memory occupied by the object is reclaimed.
Note that the finalize() method is not a reserved keyword; it’s a regular
method defined in the Object class.
By default, the finalize() method in the Object class has an empty
implementation.
If you want to define your own cleanup activities, you can override this
method in your class.
To do so, explicitly define and call the finalize() method within your code
62. When do you use Exceptions or Errors in Java? What is the difference
between these two?
Ans: In Java, Exception, and Error both are subclasses of the Java Throwable
class that belongs to [Link] package.
It is an event that occurs during the execution of the program and interrupts the
normal flow of program instructions. These are the errors that occur at compile
time and run time. It occurs in the code written by the developers. It can be
recovered by using the try-catch block and throws keyword. There are two types
of exceptions i.e. checked and unchecked.
NullPointerException: Thrown when a null reference is accessed.
IllegalArgumentException: Thrown when an illegal argument is passed to a
method.
IOException: Thrown when an I/O operation fails.
Errors are problems that mainly occur due to the lack of system resources. It
cannot be caught or handled. It indicates a serious problem. It occurs at run time.
These are always unchecked. An example of errors is OutOfMemoryError,
LinkageError, AssertionError, etc. are the subclasses of the Error class.
OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) runs out of
memory.
StackOverflowError: Thrown when the call stack overflows due to too many
method invocations.
NoClassDefFoundError: Thrown when a required class cannot be found.
63. In Java, what is the difference between throw and throws keywords?
Ans: throw Keyword:
The throw keyword is used to explicitly throw an exception from within a
method or a block of code.
When you encounter an exceptional situation that cannot be handled locally,
you can use throw to raise an exception.
It is followed by an instance of an exception class that you want to throw.
public class TestThrow {
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot
calculate square");
} else {
[Link]("Square of " + num + " is " + (num * num));
}
}
public static void main(String[] args) {
TestThrow obj = new TestThrow();
[Link](-3);
[Link]("Rest of the code..");
}
}
throws Keyword:
The throws keyword is used in the method signature to declare which
exceptions might be thrown by the method during execution.
It specifies the exception classes that the method can propagate to its caller.
You can declare both checked and unchecked exceptions using throws.
However, the throws keyword can be used to propagate checked exceptions
only.
public class TestThrows {
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
[Link]([Link](45, 0));
} catch (ArithmeticException e) {
[Link]("\nNumber cannot be divided by 0");
}
[Link]("Rest of the code..");
}
}
64. What happens to the Exception object after the exception handling is
done?
Ans: After exception handling is done, the exception object follows these
steps:
Exception Thrown:
When an exceptional situation occurs (such as division by zero or accessing a
null reference), an exception is thrown.
The JVM creates an exception object to represent the specific type of exception
(e.g., ArithmeticException, NullPointerException, etc.).
Propagation:
The exception propagates up the call stack until it finds an appropriate
exception handler (either in the same method or in a calling method).
If no handler is found, the program terminates abruptly.
Exception Handling:
When an exception is caught by an appropriate handler (using try-catch
blocks), the control flow jumps to the catch block.
The exception object is passed to the catch block as a parameter.
Inside the catch block, you can perform custom error handling, logging, or
other necessary actions.
Cleanup and Termination:
After the catch block executes, the program continues with the remaining
code (if any).
The exception object is no longer needed for further processing.
If the exception was handled successfully, the program continues normally.
If the exception was not handled, the program terminates.
Garbage Collection:
The exception object becomes eligible for garbage collection.
The JVM eventually reclaims the memory occupied by the exception object.
Note that the finalize() method (if overridden) may be called before the object
is actually garbage-collected.
In summary, the exception object is created when an exception occurs, used
during exception handling, and eventually becomes eligible for garbage
collection once its purpose is fulfilled
65. Why does Java not support operator overloading?
66. Why String class is Immutable or Final in Java?
Ans: Immutable objects are objects which once declared elements can’t be
modified after it.
The String pool cannot be possible if String is not immutable in Java. A lot of
heap space is saved by JRE.
The same string variable can be referred to by more than one string variable
in the pool.
String interning can also not be possible if the String would not be
immutable.
If we don’t make the String immutable, it will pose a serious security threat
to the application.
For example, database usernames, and passwords are passed as strings to
receive database connections.
The socket programming host and port descriptions are also passed as
strings. The String is immutable, so its value cannot be changed. If the String
doesn’t remain immutable, any hacker can cause a security issue in the
application by changing the reference value.
The String is safe for multithreading because of its immutableness. Different
threads can access a single “String instance”.\It removes the synchronization
for thread safety because we make strings thread-safe implicitly.
For example, suppose we have an instance where we try to load
[Link] class but the changes in the referenced value to the
[Link] connection class does unwanted things to our database.
67. What are the rules of method overloading and method overriding in
Java?
Ans: If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method
overriding.
Usage of Java Method Overriding
Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
Method Overloading:
If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for
you as well as other programmers to understand the behavior of the method
because its name differs.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
68. What is the difference between a class and an object in Java?
Ans:
69. Can we create an abstract class that extends another abstract class?
Ans: it is possible to create an abstract class that extends another abstract
class.
Abstract Class Inheritance:
When one abstract class extends another abstract class, it forms an
inheritance hierarchy.
The child abstract class inherits both the abstract methods and any non-
abstract methods (with implementations) from its parent abstract class.
Consider the following example where we have two abstract classes:
AbstractParent and AbstractChild.
AbstractParent defines an abstract method doSomething(), and AbstractChild
extends AbstractParent while providing an implementation for
doSomething():
abstract class AbstractParent {
abstract void doSomething();
void commonMethod() {
[Link]("Common method in AbstractParent");
}
}
abstract class AbstractChild extends AbstractParent {
@Override
void doSomething() {
[Link]("Implementation in AbstractChild");
}
}
public class Main {
public static void main(String[] args) {
AbstractChild child = new AbstractChild() {
// Anonymous inner class
};
[Link]();
[Link]();
}
}
Output:
Implementation in AbstractChild
Common method in AbstractParent
70. Why do you use Upcasting or Downcasting in Java?
Ans: Upcasting:
Upcasting (also known as generalization or widening) involves
converting a child object to a parent class object.
In upcasting, we assign a reference of a subclass to a reference of its
superclass.
The goal is to access the common features shared by both the parent and
child classes.
class Parent {
void printData() {
[Link]("Method of parent class");
}
}
class Child extends Parent {
void printData() {
[Link]("Method of child class");
}
}
public class UpcastingExample {
public static void main(String[] args) {
Parent obj1 = new Child(); // Upcasting
Parent obj2 = new Child(); // Upcasting
[Link](); // Calls the overridden method in Child class
[Link](); // Calls the overridden method in Child class
}
}
Output:
Method of child class
Method of child class
Downcasting:
Downcasting (also known as specialization or narrowing) involves
converting a parent class reference to a child class reference.
In Java, downcasting is not allowed implicitly. However, it can be done
explicitly.
When we perform downcasting, we must ensure that the actual object
being referred to is an instance of the child class.
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
[Link]("Dog barks");
}
}
public class DowncastingExample {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
// Explicit downcasting
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
[Link](); // Calls the overridden method in Dog class
}
}
}
Output:
Dog barks
Upcasting is commonly used when dealing with polymorphism, where
we want to treat different subclasses uniformly.
Downcasting is useful when we need to access specific features of a
subclass after initially referring to it as a superclass.
71. What is the reason for organizing classes and interfaces in a
package in Java?
Ans: organizing classes and interfaces into packages promotes better
code management, reduces naming conflicts, and enhances code
reusability in Java
Packages help prevent naming conflicts between classes with the same
name.
If two classes from different packages have the same name, they can
coexist without ambiguity.
Packages provide access control through access modifiers (public,
protected, private, and default/package-private).
Classes within the same package have package-level visibility, allowing
them to access each other’s package-private members.
Packages facilitate code reusability
Well-organized packages improve code readability and maintainability.
72. What is information hiding in Java?
Ans:
Data hiding is a technique of hiding internal object details, i.e., data
members.
It is an object-oriented programming technique.
Data hiding ensures, or we can say guarantees to restrict the data access
to class members
Data hiding means hiding the internal data within the class to prevent
its direct access from outside the class
If we talk about data encapsulation so, Data encapsulation hides the
private methods and class data parts, whereas Data hiding only hides
class data components.
Both data hiding and data encapsulation are essential concepts of object-
oriented programming.
Encapsulation wraps up the complex data to present a simpler view to
the user, whereas Data hiding restricts the data use to assure data
security.
73. Why does Java provide a default constructor?
Ans: Default Constructor
It is recommended to provide any of the above-mentioned contractors
while defining a class.
If not Java compiler provides a no-argument, default constructor on your
behalf.
This is a constructor initializes the variables of the class with their
respective default values (i.e. null for objects, 0.0 for float and double,
false for boolean, 0 for byte, short, int and, long).
If you observe the following example, we are not providing any constructor
to it.
If you compile and run the above program the default constructor initializes
the integer variable num with 0 and, you will get 0 as result.
74. What is the difference between super and this keyword in Java?
Ans:
this Keyword:
The this keyword is also a reserved word used to refer to the current
object instance within a class.
Key points about this:
It allows you to access the members (fields and methods) of the current
class.
You can use it to differentiate between local variables and instance
variables with the same name.
It is commonly used to initialize instance variables or call other
constructors within the same class.
class Person {
private String name;
Person(String name) {
[Link] = name; // Assign the parameter to the instance variable
}
}
super Keyword:
The super keyword is a reserved word used to refer to the base class
(parent class) from within a subclass.
Key points about super:
It allows you to access the members (fields and methods) of the parent
class.
You can use it to call the base class constructor or invoke overridden
methods from the parent class.
It is commonly used when you want to extend or customize behavior
inherited from the parent class.
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
[Link]("Dog barks");
}
}
75. Can you override an overloaded method in Java?
Ans:
Method Overloading:
Method overloading is a form of compile-time polymorphism.
It allows you to define multiple methods in the same class with the same
name but different parameter lists (different number or types of
parameters).
The compiler determines which method to call based on the arguments
provided during method invocation.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Method Overriding:
Method overriding is a form of run-time polymorphism.
It occurs when a subclass provides a specific implementation for a
method that is already defined in its superclass.
The overriding method has the same name, number and type of
parameters, and return type as the method it overrides.
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
[Link]("Dog barks");
}
}
Can You Override an Overloaded Method?:
No, you cannot directly override an overloaded method.
Overloaded methods have different signatures (different parameters),
so they are considered separate methods.
When you override a method, you provide a new implementation for the
exact same method signature from the superclass.
If you want to change the behavior of an overloaded method, you need
to override each version of that method separately.
76. How will you make an Object Immutable in Java
Ans: Use the final Keyword:
Declare the class as final. This prevents any subclass from modifying the
behavior.
Mark the instance fields as final. This ensures that their values cannot
be changed after object creation.
77. Which two methods should be always implemented by HashMap
key Object?
Ans: hashCode():
The hashCode() method returns an integer hash code for the object.
It is used by the HashMap to determine the bucket where the key-value
pair should be stored.
A well-implemented hashCode() ensures that objects with equal content
produce the same hash code.
Consistency: The hash code should remain constant as long as the
object’s state doesn’t change.
Equals Consistency: Objects that are equal (according to the equals()
method) should have the same hash code.
equals(Object other):
The equals() method compares the content of two objects for equality.
It is used by the HashMap to check if two keys are equal (i.e., they refer
to the same value).
Symmetry: If [Link](b) is true, then [Link](a) should also be true.
Transitivity: If [Link](b) and [Link](c) are true, then [Link](c)
should also be true.
Reflexivity: An object should be equal to itself (i.e., [Link](a) should
be true).
78. Why should an Object used as a Key in HashMap be Immutable?
Ans:
79. Define Constructor and Constructor Overloading in Java.
Ans: It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one
constructor is called.
It calls a default constructor if there is no constructor available in the
class. In such case, Java compiler provides a default constructor by
default.
There are two types of constructors in Java: no-arg constructor, and
parameterized constructor.
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
They do not have a return type (not even void).
You can use the access specifiers public, protected & private with
constructors.
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter/Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){[Link]("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Rule: If there is no constructor in a class, compiler automatically creates a
default constructor.
Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object
like 0, null, etc., depending on the type.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){[Link](id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
[Link]();
[Link]();
}
}
80. What are the differences between Enumeration and Iterator?
Ans: Iterator and Enumeration both are the cursors to traverse and
access an element from the collection.
They both belong to the collection framework.
Enumeration was added in JDK1.0 and Iterator in the JDK.1.2 version in
the collection framework.
Enumeration can’t make structural changes in the collection because it has
read-only access to the element in the collection.
It has the following methods
*hasMoreElements()
*nextElement()
On the other hand, an iterator can read and remove the element in the
collection.
It has the following methods −
*hasNext()
*next()
*remove()
81. How can we execute any code even before the main method?
Ans: Static Initializers:
You can use static initializer blocks to execute code before the main()
method.
These blocks are executed when the class is loaded by the Java Virtual
Machine (JVM).
public class Test {
static {
[Link]("Static initializer first");
}
public static void main(String[] args) {
[Link]("In main");
}
}
When you run this program, the static initializer block will execute before the
main() method
82. What’s the benefit of using inheritance as a key?
Ans:
Minimizing Duplicate Code:
One of the key advantages of inheritance is code reuse.
When you create a new class based on an existing class (the parent
or superclass), you can share common code among other
subclasses.
This means you don’t have to rewrite identical code in multiple
places. By inheriting from a base class, you automatically gain
access to its methods and fields.
Flexibility: Inheritance makes your code flexible to changes. If you need
to modify behavior or add new features, you can do so in the base class
(superclass). The changes will propagate to all derived classes
(subclasses) without requiring modifications in each subclass
individually.
Method Overriding: With inheritance, you can override methods
defined in the base class. This allows you to provide custom
implementations for specific behaviors in the derived classes. For
example, you can override the toString() method to provide a
meaningful string representation for an object.
Data Hiding: The base class in inheritance can decide which data should
be kept private (using access modifiers like private or protected).
Derived classes cannot alter this private data directly, ensuring
encapsulation and data integrity.
83. In how many ways can the object be created?
Ans
1. new Operator: This is the most popular way to create an object. The
new operator is followed by a call to the constructor, which initializes
the new object. When we create an object, it occupies space in the
heap
public class A {
String str = "hello";
public static void main(String[] args) {
A obj = new A(); // Creating object using new keyword
[Link]([Link]);
}
}
Java [Link]() Method: The [Link]() method
belongs to the Class class in the [Link] package. It creates a new instance
of the class represented by the Class object. It returns the newly created
instance.
public class NewInstanceExample {
String str = "hello";
public static void main(String[] args) {
try {
NewInstanceExample obj =
[Link]();
[Link]([Link]);
} catch (Exception e) {
[Link]();
}
}
}
Java newInstance() Method of Constructor Class: The Constructor class
also has a newInstance() method, similar to the newInstance() method of
the Class class. Both methods are known as reflective ways to create an
object. The newInstance() method of the Class class internally uses the
newInstance() method of the Constructor class.
import [Link];
public class NewInstanceExample1 {
String str = "hello";
public static void main(String[] args) {
try {
Constructor<NewInstanceExample1> obj =
[Link]();
NewInstanceExample1 obj1 = [Link]();
[Link]([Link]);
} catch (Exception e) {
[Link]();
}
}
}
Java [Link]() Method: The clone() method creates a copy of an
existing object. It does not call a constructor.
// Assuming you have a class with a proper implementation of clone()
YourClass originalObj = new YourClass();
YourClass clonedObj = [Link]();
Java Object Serialization and Deserialization: Serialization and
deserialization allow objects to be converted into a byte stream and then
reconstructed back into an object. This process does not directly invoke a
constructor but creates an object from the serialized data.
84. The object which has no reference is called?
Ans An object that has no reference is commonly referred to as an
anonymous object. Let me explain further:
Anonymous Objects in Java:
In Java, an anonymous object is created without giving it a name. These
objects are often used for one-time usage, such as when you need an object
just for a specific operation or method call.
Anonymous objects have expression scope, meaning they are created,
evaluated, and destroyed within a single expression1.
class MyClass {
void display() {
[Link]("Hello from anonymous object!");
}
}
public class Main {
public static void main(String[] args) {
new MyClass().display(); // Creating and using an anonymous object
}
}
85. In Heap memory which variables are created?
Ans Stack Memory:
Stack memory is used for local variables and method call frames.
Variables declared within a method (including method parameters) are allocated
on the stack.
Primitive data types (such as int, double, char, etc.) and references to objects
(including object references) are stored on the stack.
The stack memory is relatively small but efficient for managing local variables.
Heap memory is used for dynamically allocated objects (instances of classes).
Objects created using the new keyword (e.g., instances of classes) are allocated
in the heap.
The heap is a large, open memory space available during the program’s runtime.
Variables declared as instance variables (also known as fields) are part of the
objects they belong to and are stored in the heap.
Arrays, strings, and objects (including their instance variables) are stored in the
heap.
The heap memory is managed by the Java Virtual Machine (JVM) and is more
flexible than stack memory.
public class MemoryExample {
int instanceVar; // Instance variable (stored in heap)
public static void main(String[] args) {
int localVar = 42; // Local variable (stored in stack)
MemoryExample obj = new MemoryExample(); // Object created in heap
[Link] = 100; // Assign value to instance variable
}
}
In this example:
localVar is a local variable stored on the stack.
obj is an object of the MemoryExample class created in the heap.
instanceVar is an instance variable (field) associated with the obj object.
Summary:
Stack memory is used for method call frames and local variables.
Heap memory is used for dynamically allocated objects (instances of classes)
and their instance variables.
86. In java, how are arrays created?
Ans: In Java, arrays are a fundamental data structure used to store multiple
values of the same type in a single variable.
Array Declaration:
To declare an array in Java, you specify the data type followed by square
brackets ([]) and the array name.
There are two common ways to declare an array:
Using the data type before the array name: int[] myArray;
Using the array name before the data type: int myOtherArray[];
The size of the array is not specified during declaration because only a
reference to the array is created in memory.
Array Instantiation (Allocation):
After declaring an array, you need to allocate memory for it using the
new keyword.
The general form of creating an array is:
arrayName = new dataType[size];
Here:
dataType specifies the type of data the array will hold (e.g., int, double, String,
etc.).
size determines the number of elements in the array.
arrayName is the name of the array variable.
public class ArrayExample {
public static void main(String[] args) {
// Declare an integer array
int[] myIntArray;
// Allocate memory for 5 integers
myIntArray = new int[5];
// Initialize the array elements
myIntArray[0] = 10;
myIntArray[1] = 20;
myIntArray[2] = 30;
myIntArray[3] = 40;
myIntArray[4] = 50;
// Access and print array elements
[Link]("Element at index 0: " + myIntArray[0]);
[Link]("Element at index 3: " + myIntArray[3]);
}
}
Notes:
Arrays in Java are dynamically allocated, meaning their size can be
determined at runtime.
The length property of an array provides the actual number of elements it
contains.
87. Define Runtime Polymorphism.
Ans: Runtime Polymorphism, also known as Dynamic Method Dispatch,
is a fundamental concept in object-oriented programming. It allows a
program to perform a single action (method call) in different ways based
on the actual type of the object at runtime1. Here are the key points about
runtime polymorphism:
Method Overriding:
Runtime polymorphism is achieved through method overriding.
When a subclass provides a specific implementation for a method that is
already defined in its superclass, it overrides the superclass method.
The overridden method in the subclass has the same name, return type,
and parameters as the method in the superclass.
Resolution at Runtime:
During runtime polymorphism, the decision about which method to invoke
is made by the Java Virtual Machine (JVM) at runtime, not during
compilation.
The JVM determines the actual type of the object (based on the reference
variable) and calls the appropriate overridden method.
Upcasting:
Before runtime polymorphism, there is a concept called upcasting.
Upcasting occurs when a reference variable of a parent class refers to an
object of a child class.
88. When does a null pointer exception occur?
Ans:
A NullPointerException (NPE) in Java occurs when a program tries to
access an object reference that has a null value. In simpler terms, it
happens when you attempt to perform an operation on a variable or object
that has not been initialized or has been explicitly set to null
What Causes a NullPointerException?
A NullPointerException arises when you:
Access a method on an object instance, but at runtime, the object is null.
Access variables of an object instance that is null at runtime.
89. When Out of a memory error occurs?
Ans: An OutOfMemoryError in Java occurs when the Java Virtual Machine
(JVM) cannot allocate an object because it has run out of memory. This error
is typically thrown when the heap space (where objects are stored) is
exhausted, and no more memory can be made available by the garbage
collector
90. Can exceptions occur in the catch block?
Ans: Exceptions in catch Blocks:
The catch block is where exceptions are handled after they have been thrown
by the try block.
While it’s not common, exceptions can indeed occur within a catch block.
Here are some scenarios where exceptions might occur in a catch block:
Nested try-catch Blocks:
If you have nested try-catch blocks (i.e., a try block within another catch
block), an exception thrown in the inner catch block can propagate to the
outer catch block.
try {
// Some code that may throw an exception
} catch (Exception e) {
try {
// Nested catch block
// Exception handling here
} catch (Exception nestedException) {
// Exception within the nested catch block
// Handle it or propagate further
}
}
Throwing New Exceptions:
Inside a catch block, you can explicitly throw a new exception.
For example, you might catch a specific exception and then throw a different
exception with additional context.
Example
try {
// Some code that may throw an exception
} catch (IOException e) {
// Handle the IOException
throw new CustomException("An error occurred while processing data",
e);
}
Resource Cleanup Failures:
If your catch block performs resource cleanup (e.g., closing files, releasing
database connections), an exception during cleanup could occur
91. What will happen if we use the throws keyword in the body?
Ans: throws Keyword in Method Signature:
The throws keyword is used in the method signature to declare that a method
might throw one or more exceptions.
When a method is declared with throws, it indicates that the method can
potentially raise certain exceptions during its execution.
The exceptions declared using throws are checked exceptions (i.e., exceptions
that must be handled by the caller or propagated further up the call stack).
Example of throws:
class MyService {
void performTask() throws IOException {
// Some code that may throw an IOException
}
}
92. In Java, Why multiple inheritances are not supported?
Ans: Multiple inheritances lead to ambiguity.
Consider a case where class B extends class A and Class C and both class
A and C have the same method display().
Now java compiler cannot decide, which display method it should
inherit. To prevent such situation, multiple inheritances is not allowed
in java.
93. What is Interface?
Ans: The interface in Java is a mechanism to achieve abstraction.
There can be only abstract methods in the Java interface, not the method
body. It is used to achieve abstraction and multiple inheritances in Java
using Interface.
In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.
To declare an interface, use the interface keyword.
It is used to provide total abstraction.
That means all the methods in an interface are declared with an empty
body and are public and all fields are public, static, and final by default.
A class that implements an interface must implement all the methods
declared in the interface.
To implement the interface, use the implements keyword.
It is used to achieve total abstraction.
Since java does not support multiple inheritances in the case of class, by
using an interface it can achieve multiple inheritances.
94. What is Serialization?
Ans:
95. What is DeSerialization?
96. When an Out of a stack error occurs?
97. Where are all string literals managed?
98. Which condition will result in an Illegal state exception?
99. Which interface will result in sorted order?
100. What is Comparator?
101. Why can we not apply access specifiers to packages, initializers, and
local variables?
102. When we can use final class?
103. Abstract class cannot be instantiated. Why?
104. Abstract method cannot have body, why?
105. What stand is for JDK, JRR and JVM?
106. What is a singleton class?
107. Explain Map
108. What is a checked and unchecked exception?
109. What is a comparable and comparator?
110. What is the best way to create a singleton object in Java?
111. Is it possible to declare a class as Abstract without using any abstract
method?
112. Functions of JVM and JRE?
113. What is a JVM?
114. What’s the difference between the stack and the queue?
115. Explain the keyword of Java.
116. What’s the difference between importing [Link] and [Link]?
*?
117. What is the standard import?
118. Garbage collection in Java?
119. Decision-Making in Java
120. What is a class?
121. What is the difference between heap and stack?
122. What is the difference between an instance variable and a local
variable?
123. What is the difference between Break and Continue?
124. Addition features in Java 8?
125. What is the difference between for and for each loop in java and its
use of it?
126. Can we have multiple public classes within a class?
127. What is inheritance? Types of inheritance? Do multiple inheritances
allow in java? If not, why?
128. What is polymorphism? How can we achieve it?
129. What is the difference between method overloading and method
overriding?
130. Can we achieve method overloading when two methods have only
differences in return type?
131. Method overloading and overriding examples in the Selenium
project?
132. What are IS-A and HAS-A relations in java With examples?
Ans: IS-A Relationship (Inheritance):
The IS-A relationship represents inheritance, where one class (subclass
or derived class) inherits properties and behaviors from another class
(superclass or base class).
It signifies that a subclass is a specialized version of the superclass.
In Java, the IS-A relationship is implemented using the extends keyword.
Example:
Consider a Vehicle superclass with common features like speed and
color.
We create subclasses like Car, Bike, and Truck that inherit from Vehicle.
These subclasses can access the common features and add their specific
features.
Example of IS-A Relationship (Inheritance):
class Vehicle {
int avgSpeed;
String color;
}
class Car extends Vehicle {
int noOfDoors;
void startCar() {
[Link]("Car started!");
}
}
class Bike extends Vehicle {
boolean hasSideStand;
void startBike() {
[Link]("Bike started!");
}
}
Here, Car and Bike IS-A Vehicle.
They inherit the avgSpeed and color properties from the Vehicle class.
HAS-A Relationship (Composition):
The HAS-A relationship represents composition or aggregation.
It signifies that a class has a reference to another class as a part or
component.
Composition allows building complex objects by combining simpler
objects.
Example:
A Car HAS-A Engine.
A Person HAS-A Address.
Example of HAS-A Relationship (Composition):
class Engine {
void startEngine() {
[Link]("Engine started!");
}
}
class Car {
Engine carEngine; // Car HAS-A Engine
void startCar() {
[Link]();
[Link]("Car started!");
}
}
Here, the Car class HAS-A reference to an Engine.
The startCar() method uses the startEngine() method from the Engine class.
133. Can the final/Static method be overloaded?
Ans: Overloading is a one of the mechanisms to achieve polymorphism
where, a class contains two methods with same name and different
parameters.
Whenever you call this method the method body will be bound with the
method call based on the parameters
Yes, we can overload static methods in Java.
public class Calculator {
public static int addition(int a , int b){
int result = a+b;
return result;
}
public static int addition(int a , int b, int c){
int result = a+b+c;
return result;
}
public static void main(String args[]){
[Link]([Link](12, 13));
[Link]([Link](12, 13, 15));
}
}
Output
25
40
Final Static Methods:
A final method cannot be overridden by subclasses.
However, it can still be overloaded (i.e., you can define multiple final
methods with the same name but different parameter lists).
The final modifier prevents a method from being hidden by a subclass
method.
134. Can final/Static methods be overridden?
Ans:
We can declare static methods with the same signature in the subclass,
but it is not considered overriding as there won’t be any run-time
polymorphism. Hence the answer is ‘No’.
If a derived class defines a static method with the same signature as a
static method in the base class, the method in the derived class is hidden
by the method in the base class.
// Superclass
class Base {
// Static method in base class which will be hidden in subclass
public static void display() {
[Link]("Static or class method from Base");
}
// Non-static method which will be overridden in derived class
public void print() {
[Link]("Non-static or Instance method from Base");
}
}
// Subclass
class Derived extends Base {
// This method is hidden by display() in Base
public static void display() {
[Link]("Static or class method from Derived");
}
// This method overrides print() in Base
public void print() {
[Link]("Non-static or Instance method from Derived");
}
}
// Driver class
public class Test {
public static void main(String args[ ]) {
Base obj1 = new Derived();
// As per overriding rules this should call to class Derive's static
// overridden method. Since static method can not be overridden, it
// calls Base's display()
[Link]();
// Here overriding works and Derive's print() is called
[Link]();
}
}
Output
Static or class method from Base
Non-static or Instance method from Derived
135. Can we overload the main method?
Ans: Overloading is one of the mechanisms to achieve polymorphism where
a class contains two methods with the same name and different parameters.
Whenever you call this method the method body will be bound with the
method call based on the parameters.
Yes, we can overload the main method in Java, but When we execute the class JVM starts execution
with public static void main(String[] args) method.
Example
public class Sample{
public static void main(){
[Link]("This is the overloaded main method");
}
public static void main(String args[]){
Sample obj = new Sample();
[Link]();
}
}
136. Can we execute a class without a main method?
Ans:with the help of static block but it worked still java 6 from java 7 it is
not working
137. What is a Package?
Ans: A Java package is a fundamental organizational unit that helps manage
and group related classes, interfaces, enumerations, and annotation types.
Encapsulation: Packages allow you to encapsulate a group of related types
(classes, interfaces, etc.) together. This helps organize your code and makes
it more modular.
Namespace Management: Each package provides a unique namespace for the
types it contains. This prevents naming conflicts between classes with the
same name in different packages.
Access Control: Packages control access to their members. For example,
package-private (default) and protected members are accessible within the
same package or its subclasses.
Ease of Use: By organizing related classes into packages, you can easily
import and use them in your programs.
138. What is an Abstract Class? Write an example code.
Ans: A class is an abstract class if it contains at least one abstract method.
It can contain other non-abstract methods as well. A class can be declared as
abstract by using the abstract keyword. Also, an abstract class cannot be
instantiated.
abstract class Animal {
abstract void sound();
}
class Cat extends Animal {
void sound() {
[Link]("Cat Meows");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog Barks");
}
}
class Cow extends Animal {
void sound() {
[Link]("Cow Moos");
}
}
public class Demo {
public static void main(String[] args) {
Animal a;
a = new Cat();
[Link]();
a = new Dog();
[Link]();
a = new Cow();
[Link]();
}
}
139. Can we use private and protect access modified inside an
Interface?
Ans: The access modifiers that can be used for interface methods are:
public: All interface methods are implicitly public. You don’t need to explicitly
write public for interface methods.
default (package-private): If no access modifier is specified, the method is
considered package-private (i.e., accessible only within the same package).
private: Starting from Java 9, interfaces can have private methods. These
methods are used for internal implementation within the interface itself and
cannot be accessed by implementing classes.
protected: You cannot directly use protected for interface methods. They are
either public or package-private (default).
interface MyInterface {
void publicMethod(); // Implicitly public
default void defaultMethod() {
[Link]("Default method");
}
// Private method (Java 9+)
private void privateMethod() {
[Link]("Private method");
}
}
class MyClass implements MyInterface {
public void publicMethod() {
[Link]("Implemented public method");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
[Link]();
// [Link](); // Error: Cannot access private method
}
}
In this example:
publicMethod() is implicitly public in the interface.
defaultMethod() is a default (package-private) method.
privateMethod() is a private method (available only within the interface).
140. Can multiple inheritances support the Interface?
Ans:ye it support
141. What is an Exception, and what is its base class of it?
Ans:-abonormal event which terminate the normal flow of program
execution
Exception Hierarchy:
All exception and error types in Java are subclasses of the Throwable class.
The Throwable class serves as the base class for both exceptions and errors.
There are two main branches in the hierarchy:
Exception: This class is used for exceptional conditions that user
programs should catch. Examples include NullPointerException,
IOException, and custom exceptions.
Error: The Error class is used by the Java runtime system (JVM) to
indicate errors related to the runtime environment itself (e.g., out-of-
memory errors, stack overflow). These errors are usually beyond the
control of the programmer and should not be caught or handled.
Checked vs. Unchecked Exceptions:
Checked Exceptions:
Checked exceptions are also known as compile-time exceptions.
They are checked by the compiler during compilation.
Examples include IOException, SQLException, and custom checked
exceptions.
Unchecked Exceptions:
Unchecked exceptions are also known as runtime exceptions.
They are not checked by the compiler at compile time.
Examples include NullPointerException,
ArrayIndexOutOfBoundsException, and custom unchecked exceptions.
142. What is Final, Finally, Finalize?
Ans:
143. What is done in finally block?
Ans: Purpose of finally Block:
The finally block contains code that must be executed, no matter what.
It is typically used for cleanup tasks, resource release, or other essential
operations.
Even if an exception is thrown and caught, the code in the finally block runs.
Execution Flow:
When an exception occurs within the try block, the control jumps to the
corresponding catch block (if available).
After executing the catch block (if applicable), the control proceeds to the finally
block.
If no exception occurs, the control directly enters the finally block after
executing the try block.
Common Use Cases:
Resource Cleanup: Close files, release database connections, or free other
resources.
Logging: Log information about the exception or other relevant details.
Final Steps: Perform any necessary final steps before exiting the method or
program.
Example:
Java
public class FinallyExample {
public static void main(String[] args) {
try {
// Code that might throw an exception
int result = divide(10, 0);
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("Cleanup in finally block");
}
}
public static int divide(int a, int b) {
return a / b;
}
}
AI-generated code. Review and use carefully. More info on FAQ.
In this example:
The divide() method throws an ArithmeticException when dividing by zero.
The catch block handles the exception.
The finally block always executes, regardless of whether an exception occurred
or not.
Remember that the finally block ensures that critical cleanup or finalization
tasks are performed, even in exceptional situations.
144. What is garbage collection in java? How it is done?
Ans:
145. What’s the exception?
Ans: An exception in Java refers to an unexpected event or error that occurs
during the execution of a program. When an exception occurs, it disrupts the
normal flow of the program’s instructions
146. What are the types of exceptions?
Ans:Built in exception & User defined exception
147. What is the difference between an error and an exception?
Ans: Errors are problems that mainly occur due to the lack of system
resources. It cannot be caught or handled. It indicates a serious problem. It
occurs at run time. These are always unchecked. An example of errors is
OutOfMemoryError, LinkageError, AssertionError, etc. are the subclasses of
the Error class.
It is an event that occurs during the execution of the program and interrupts
the normal flow of program instructions. These are the errors that occur at
compile time and run time. It occurs in the code written by the developers. It
can be recovered by using the try-catch block and throws keyword. There are
two types of exceptions i.e. checked and unchecked.
148. What is the keyword in exceptional handling?
Ans: try:
The try block is used to enclose a segment of code that might throw an
exception.
It ensures that any exception arising from the enclosed code can be gracefully
managed.
catch:
The catch block follows the try block.
It catches and handles exceptions that occur within the try block.
Multiple catch blocks can be used to handle different types of exceptions.
throw:
The throw keyword is used to explicitly throw an exception.
Developers can create custom exceptions and throw them when specific
conditions are met.
throws:
The throws keyword is used in method signatures to declare that a method
might throw a specific type of exception.
It allows the caller of the method to handle or propagate the exception.
finally:
The finally block is used to define code that always executes, regardless of
whether an exception occurred or not.
It is commonly used for resource cleanup (e.g., closing files, releasing locks).
149. Can you handle a catch in an exception to an exception?
Ans: Nested Exception Handling:
Yes, you can handle exceptions within exceptions by nesting try-catch blocks.
When an exception occurs inside a catch block, you can handle it by enclosing
the problematic code in another try block.
Here’s an example in Java:
Java
public class NestedExceptionHandling {
public static void main(String[] args) {
try {
// Outer try block
int[] arr = { 1, 2, 3 };
[Link](arr[5]); // Throws
ArrayIndexOutOfBoundsException
try {
// Inner try block
String str = null;
[Link]([Link]()); // Throws NullPointerException
} catch (NullPointerException e) {
[Link]("Inner catch: Null pointer exception");
}
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Outer catch: Array index out of bounds");
}
}
}
AI-generated code. Review and use carefully. More info on FAQ.
In this example:
The outer try block attempts to access an invalid array index, resulting in an
ArrayIndexOutOfBoundsException.
Inside the outer catch block, there’s an inner try block that attempts to invoke
a method on a null reference, causing a NullPointerException.
The inner catch block handles the inner exception.
Best Practices:
While nested exception handling is possible, it’s essential to keep it readable
and maintainable.
Avoid excessive nesting, as it can make code harder to follow.
Consider using separate methods or functions to handle specific exceptions,
rather than deeply nested blocks.
150. List out the different access specifiers available for Java classes
Ans: public:
The public access specifier allows unrestricted access from any other class or
package.
A public class, method, or data member can be accessed from anywhere in the
program.
Example:
Java
public class MyClass {
// Public class accessible from any other class
}
protected:
The protected access specifier allows access within the same package and by
subclasses (even if they are in different packages).
It is commonly used for inheritance and method overriding.
Example:
Java
protected void myProtectedMethod() {
// Accessible within the same package and by subclasses
}
Default (Package-Private):
When no access modifier is specified (i.e., no public, protected, or private),
the default access modifier is applied.
Default access allows access within the same package but not from outside
the package.
Example:
class MyDefaultClass {
// Default access (package-private) within the same package
}
Private:
The private access specifier restricts access to within the same class only.
It is commonly used to encapsulate implementation details.
Example:
private int myPrivateField;
// Accessible only within the same class
151. What is the difference between List and a Set?
Ans:-
152. Can we create an object for the abstract class? If not, why?
Ans: Abstract Classes:
An abstract class in Java is a class that cannot be instantiated directly.
It serves as a blueprint for other classes (concrete subclasses) to inherit from.
Abstract classes can contain both abstract methods (methods without
implementation) and concrete methods (methods with implementation).
Creating Objects from Abstract Classes:
You cannot directly create an object (instance) of an abstract class using the
new keyword.
The primary reason is that abstract classes may have incomplete or undefined
behavior due to the presence of abstract methods.
Abstract classes are meant to be extended by concrete subclasses, which
provide implementations for the abstract methods.
How to Use Abstract Classes:
To use an abstract class, you need to:
Extend it by creating a concrete subclass.
Implement all the abstract methods defined in the abstract class.
Instantiate objects of the concrete subclass.
Example:
Java
abstract class Shape {
abstract void draw(); // Abstract method (no implementation)
}
class Circle extends Shape {
void draw() {
[Link]("Drawing a circle");
}
}
public class Main {
public static void main(String[] args) {
// Cannot create an object of Shape directly
// Shape shape = new Shape(); // Error: Cannot instantiate abstract class
// Create an object of Circle (a concrete subclass)
Shape circle = new Circle();
[Link](); // Output: Drawing a circle
}
}
153. In what way we can sort the elements(default and custom sort)
present in the array and any of the collection objects?
Ans:; Default (Natural) Sorting:
Default sorting refers to sorting elements based on their natural order
(defined by the element type).
For primitive data types (e.g., int, double), you can use [Link]() directly.
For objects that implement the Comparable interface, you can use
[Link]() or [Link]().
int[] intArray = { 5, 2, 9, 1, 5 };
[Link](intArray); // Sorts in ascending order
Custom Sorting (Using Comparator):
Custom sorting allows you to define your own sorting criteria using a
Comparator.
Implement the Comparator interface to provide custom comparison logic.
Use [Link]() with a custom comparator to sort objects based on
specific attributes.
class Student {
int rollNumber;
String name;
// Constructor, getters, setters...
@Override
public String toString() {
return rollNumber + ": " + name;
}
}
List<Student> studentList = new ArrayList<>();
[Link](new Student(101, "Alice"));
[Link](new Student(102, "Bob"));
[Link](new Student(103, "Charlie"));
// Custom comparator to sort by roll number
[Link](studentList,
[Link](Student::getRollNumber));
// Print sorted list
for (Student student : studentList) {
[Link](student);
}
Sorting in Descending Order:
To sort in descending order, use [Link]() as the comparator.
Example: Sorting a List of Integers in Descending Order
Java
List<Integer> integerList = new ArrayList<>();
[Link](5);
[Link](2);
[Link](9);
[Link](integerList, [Link]()); // Sorts in
descending order
154. Do you know whether the constructor returns any value in Java?
Ans:
A constructor is similar to method and it is invoked at the time creating an object
of the class, it is generally used to initialize the instance variables of a class. The
constructors have same name as their class.
A constructor doesn’t have any return type.
The data type of the value retuned by a method may vary, return type of a method
indicates this value.
A constructor doesn’t return any values explicitly, it returns the instance of the
class to which it belongs.
155. Is it possible to make a constructor final?
156. Is it possible to overload the constructors?
Ans: In Java, we can overload constructors like methods. The constructor
overloading can be defined as the concept of having more than one constructor
with different parameters so that every constructor can perform a different task.
Here, we need to understand the purpose of constructor overloading.
Sometimes, we need to use multiple constructors to initialize the different values
of the class.
We must also notice that the java compiler invokes a default constructor when
we do not use any constructor in the class. However, the default constructor is
not invoked if we have used any constructor in the class, whether it is default or
parameterized. In this case, the java compiler throws an exception saying the
constructor is undefined.
157. Mention the class, which is the superclass for the entire class.
Ans: The superclass for all Java classes is the Object class. Every class, whether
predefined or user-defined, implicitly inherits from the Object class. This class
is part of the [Link] package and provides fundamental methods and
behaviors that are common to all objects in Java
158. Define Aggregation
Ans:
159. Is it possible to use both “this()” and “super()” in a constructor?
Ans: No, you cannot have both this() and super() in a single constructor.
You cannot use both this() and super() in the same constructor.
The reason is that both must be the first statement in the constructor.
If allowed, you could end up calling the superclass constructor twice, leading to ambiguity.
160. Is it possible for you to declare a constructor as final?
Ans: No constructors cannot be inherited in Java therefore, there is no
need to write final before constructors. Therefore, java does not allow final
keyword before a constructor. If you try a compile time error is generated
In inheritance whenever you extend a class. The child class inherits all the
members of the superclass except the constructors.
In other words, constructors cannot be inherited in Java therefore you cannot
override constructors.
So, writing final before constructors makes no sense. Therefore, java does not
allow final keyword before a constructor.
If you try, make a constructor final a compile time error will be generated saying
“modifier final not allowed here”
Purpose of Constructors:
Constructors are special methods used to initialize objects when they are
created.
They have the same name as the class and do not have a return type.
Constructors are not inherited by subclasses, which means they cannot be
overridden.
Final Keyword and Constructors:
The final keyword is used to prevent methods from being overridden by
subclasses.
However, constructors are not subject to hiding or overriding because they
are not inherited.
Since constructors cannot be modified in subclasses, there is no need to make
them final.
Example: Attempting to Declare a Final Constructor:
If you try to declare a constructor as final, the compiler will generate an error:
Java
class MyClass {
final MyClass() {
// Error: modifier final not allowed here
[Link]("This constructor cannot be declared as final.");
}
}
161. Mention the difference between the abstract and the final method
Ans: Abstract Methods:
An abstract method is declared using the abstract keyword within an abstract
class.
Characteristics:
Incomplete: An abstract method does not have a body (implementation). It
only provides a method signature (name, parameters, and return type).
Must Be Overridden: Any class that extends the abstract class must provide
an implementation for all its abstract methods.
abstract class Shape {
public abstract double area(); // Abstract method
}
Final Methods:
A final method is declared using the final keyword within any class (abstract
or non-abstract).
Characteristics:
Complete: A final method has a complete implementation (body) and cannot
be overridden by subclasses.
Cannot Be Overridden: Once a method is marked as final, it cannot be
modified or overridden in any subclass.
Purpose: Final methods are used when you want to prevent further
modification of a specific method.
Abstract classes can have final methods.
The final method within an abstract class is treated like any other method
(with a body) and cannot be overridden by subclasses.
abstract class Animal {
public final void breathe() {
// Implementation for breathing
}
public abstract void makeSound(); // Abstract method
}
162. Explain the purpose of encapsulation
Ans: Encapsulation is one of the fundamental principles of object-oriented
programming (OOP). It refers to the practice of bundling data (attributes or
fields) and the methods (functions) that operate on that data into a single unit
called a class. Here’s why encapsulation is important:
Data Hiding and Abstraction:
Encapsulation hides the internal details of an object from the outside world.
By marking certain fields as private (or protected), we prevent direct access to
them from outside the class.
This abstraction allows us to focus on the essential aspects of an object without
worrying about its implementation details
We can define which members are accessible from outside the class (public
interface) and which are not.
Access modifiers (such as public, private, protected, and package-private) allow
us to enforce this control.
Keep Fields Private: Make fields private to prevent direct modification from
outside the class.
Provide Accessors (Getter Methods): Use getter methods to allow read-only
access to fields.
Provide Mutators (Setter Methods): Use setter methods to allow controlled
modification of fields.
Validate Inputs: Validate input parameters in mutator methods to maintain data
consistency.
163. Define Java Collections
Ans: Java Collections refer to a framework that provides an architecture for
storing and manipulating groups of objects. These collections allow you to
perform various operations such as searching, sorting, insertion, manipulation,
and deletion on data.
Collections represent a group of objects single unit
The Java Collection framework resides in the [Link] package.
It includes various interfaces and classes for different types of collections.
In summary, Java Collections offer a powerful framework for managing and
manipulating groups of objects, making it easier to work with data in a
structured manner
164. What are the operations of collections?
Ans: Logical Operations:
These operations involve combining or comparing two collections:
AND: Intersection of elements between two collections.
OR: Union of elements from both collections (including duplicates).
NOT: Difference between elements in one collection and those not present in
another.
XOR: Elements that are unique to either of the two collections (excluding
common elements).
Other Operations on Collections:
These operations are based on class methods provided by the Collection and
Stream classes:
add(E e): Inserts an element into the collection.
addAll(Collection<? extends E> c): Inserts elements from another collection.
remove(Object element): Deletes an element from the collection.
removeAll(Collection<?> c): Deletes all elements from the invoking collection
that are also present in the specified collection.
removeIf(Predicate<? super E> filter): Deletes elements from the collection
based on a specified predicate.
retainAll(Collection<?> c): Deletes all elements from the invoking collection
except those present in the specified collection.
size(): Returns the total number of elements in the collection.
165. List out the interfaces available in Java collections
Ans: Collection Interface:
The Collection interface is a root interface for all collections.
It defines basic methods that are common to all collection types.
Subinterfaces of Collection include:
Set: Represents a collection of unique elements (no duplicates).
List: Represents an ordered collection (allows duplicates).
Queue: Represents a collection with specific queue behavior (e.g., FIFO or
priority).
Set Interface:
A set is an unordered collection of objects in which duplicate values cannot
be stored.
Subinterfaces of Set include:
HashSet: Implements a hash table for efficient lookup.
LinkedHashSet: Maintains insertion order.
TreeSet: Maintains elements in sorted order.
List Interface:
A list represents an ordered collection of elements.
Subinterfaces of List include:
ArrayList: Implements a dynamic array.
LinkedList: Implements a doubly linked list.
Vector: Similar to ArrayList but synchronized (legacy class).
Queue Interface:
A queue represents a collection with specific queue behavior (e.g., FIFO or
priority).
Subinterfaces of Queue include:
PriorityQueue: Implements a priority queue.
ArrayDeque: Implements a double-ended queue.
Map Interface:
A map represents a key-value pair association (not a true collection but often
grouped with collections).
Subinterfaces of Map include:
HashMap: Implements a hash table for efficient key-value lookups.
LinkedHashMap: Maintains insertion order.
TreeMap: Maintains keys in sorted order.
166. List out the Classes available in Java collections
Ans:
ArrayList:
The ArrayList class implements the List interface. It uses a dynamic array to
store the duplicate element of different data types. The ArrayList class
maintains the insertion order and is non-synchronized. The elements stored
in the ArrayList class can be randomly accessed
import [Link].*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
LinkedList:
Implements a doubly linked list.
Efficient for insertions and deletions at both ends.
Useful for implementing queues and stacks.
LinkedList implements the Collection interface. It uses a doubly linked list
internally to store the elements. It can store the duplicate elements. It
maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.
import [Link].*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
Vector:
Similar to ArrayList but synchronized (legacy class).
Provides thread-safe operations.
Less commonly used due to better alternatives.
Vector uses a dynamic array to store the data elements. It is similar to
ArrayList. However, It is synchronized and contains many methods that are
not the part of Collection framework.
import [Link].*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link]("Ayush");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list
that is used to hold the elements which are about to be processed. There are various classes
like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
The PriorityQueue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.
Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables us to
perform the operations at both the ends.
HashSet:
Implements a hash table for efficient lookup.
Stores unique elements (no duplicates).
Order of elements is not guaranteed.
HashSet class implements Set Interface. It represents the collection that uses
a hash table for storage. Hashing is used to store the elements in the HashSet.
It contains unique items.
import [Link].*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
LinkedHashSet:
Maintains insertion order.
Combines features of HashSet and LinkedList.
LinkedHashSet class represents the LinkedList implementation of Set
Interface. It extends the HashSet class and implements Set interface. Like
HashSet, It also contains unique elements. It maintains the insertion order
and permits null elements.
Consider the following example.
import [Link].*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
TreeSet:
Maintains elements in sorted order (natural order or custom comparator).
Implemented as a self-balancing binary search tree.
Java TreeSet class implements the Set interface that uses a tree for storage.
Like HashSet, TreeSet also contains unique elements. However, the access and
retrieval time of TreeSet is quite fast. The elements in TreeSet stored in
ascending order.
import [Link].*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
HashMap:
Implements a hash table for key-value pairs.
Efficient for lookups by key.
Keys are unique, and order is not guaranteed.
LinkedHashMap:
Maintains insertion order (based on order of addition).
Combines features of HashMap and LinkedList.
Java LinkedHashMap class is Hashtable and Linked list implementation of the
Map interface, with predictable iteration order. It inherits HashMap class and
implements the Map interface.
import [Link].*;
class LinkedHashMap1{
public static void main(String args[]){
LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
[Link](100,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
}
}
}
TreeMap:
Maintains keys in sorted order (natural order or custom comparator).
Implemented as a self-balancing binary search tree.
PriorityQueue:
Implements a priority queue (min-heap or max-heap).
Elements are ordered based on their priority.
ArrayDeque:
Implements a double-ended queue (deque).
Supports insertion and removal at both ends efficiently.
167. List out the maps available in Java collections
Ans: A map contains values on the basis of key, i.e. key and value pair. Each
key and value pair is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis
of a key.
There are two interfaces for implementing Map in java: Map and SortedMap,
and three classes: HashMap, LinkedHashMap, and TreeMap
[Link] Interface
Entry is the subinterface of Map. So we will be accessed it by [Link] name.
It returns a collection-view of the map, whose elements are of this class. It
provides methods to get key and value.
168. Provide the features of the Hashtable method
Ans: Java Hashtable class implements a hashtable, which maps keys to
values. It inherits Dictionary class and implements the Map interface.
Points to remember
A Hashtable is an array of a list. Each list is known as a bucket. The position
of the bucket is identified by calling the hashcode() method. A Hashtable
contains values based on the key.
Java Hashtable class contains unique elements.
Java Hashtable class doesn't allow null key or value.
Java Hashtable class is synchronized.
The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
import [Link].*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
[Link](100,"Amit");
[Link](102,"Ravi");
[Link](101,"Vijay");
[Link](103,"Rahul");
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
}
}
}
169. Explain HashSet
Ans: Java HashSet class is used to create a collection that uses a hash table
for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
HashSet stores the elements by using a mechanism called hashing.
HashSet contains unique elements only.
HashSet allows null value.
HashSet class is non synchronized.
HashSet doesn't maintain the insertion order. Here, elements are inserted on
the basis of their hashcode.
HashSet is the best approach for search operations.
The initial default capacity of HashSet is 16, and the load factor is 0.75.
import [Link].*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link]("Four");
[Link]("Five");
Iterator<String> i=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
170. Explain TreeSet
Ans: Java TreeSet class implements the Set interface that uses a tree for
storage. It inherits AbstractSet class and implements the NavigableSet
interface. The objects of the TreeSet class are stored in ascending order.
The important points about the Java TreeSet class are:
Java TreeSet class contains unique elements only like HashSet.
Java TreeSet class access and retrieval times are quiet fast.
Java TreeSet class doesn't allow null element.
Java TreeSet class is non synchronized.
Java TreeSet class maintains ascending order.
Java TreeSet class contains unique elements only like HashSet.
Java TreeSet class access and retrieval times are quite fast.
Java TreeSet class doesn't allow null elements.
Java TreeSet class is non-synchronized.
Java TreeSet class maintains ascending order.
import [Link].*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
171. How do you decide which type of Inner Class – Static or Non-Static to
use in Java?
Ans:
172. What are the situations in which you choose HashSet or TreeSet?
Ans: HashSet:
Use HashSet when you need a collection of unique elements and order does
not matter.
Key points about HashSet:
Faster performance for basic operations (add, remove, contains) due to
constant time complexity.
Elements are not ordered.
Allows null objects.
Implemented using a hash table.
Suitable for scenarios where you want a simple set without any specific
ordering constraints
TreeSet:
Use TreeSet when:
You want a sorted set (elements are maintained in ascending order). It
offers several methods to deal with the ordered set like first(), last(),
headSet(), tailSet(), etc.
You need operations like:
Finding the highest or lowest element.
Retrieving elements in a range.
TreeSet maintains ordering based on the natural ordering of elements (or
a provided Comparator).
Key points about TreeSet:
Takes O(log n) time for search, insert, and delete operations (slower
than HashSet).
Backed by a self-balancing binary search tree (usually a Red-Black
Tree).
Does not allow null objects (throws a NullPointerException if
attempted).
HashSet allows null object. TreeSet doesn’t allow null Object and
throw NullPointerException, Why, because TreeSet uses compareTo()
method to compare keys and compareTo() will throw
[Link].
Useful when you require a sorted collection with additional
operations beyond basic set functionality
173. What is the use of method references in Java?
Ans: In Java, method references provide a concise way to refer to methods
or constructors using the double colon (::) notation. This feature was
introduced in Java 8
174. Why do we use static initializers in Java?
Ans: A static initializer block is a piece of code that executes when a class
is loaded into memory.
It allows us to perform initialization tasks before any objects of the class are
created.
Common use cases include initializing static variables, registering JDBC
drivers,
static {
// Code to execute during class loading
}
Static initializer blocks always execute before instance initializer blocks and
before the main() method.
Suppose we have the following class with two static blocks:
public class StaticBlockExample {
static {
[Link]("static block 1");
}
static {
[Link]("static block 2");
}
public static void main(String[] args) {
[Link]("Main Method");
}
}
Besides static blocks, there are also instance initializer blocks.
Instance initializer blocks initialize instance data members (non-static
fields).
They execute at the time of instance creation (when an object is constructed).
175. Using a regular expression, how can you check if a String is a
number?
How to Check If A String Is a Number (Numeric) using Regex (C++/Javascript) ? | Algorithms,
Blockchain and Cloud ([Link])
Ans: An integer number can have an optional sign (+ or -) followed by one or
more digits.
Here’s a regular expression to validate integer numbers:
[+-]?[0-9]+
This pattern allows an optional sign (+ or -) followed by one or more digits
String input1 = "abc";
String input2 = "1234";
String regex = "[+-]?[0-9]+";
Pattern p = [Link](regex);
Matcher m = [Link](input1);
if ([Link]() && [Link]().equals(input1))
[Link](input1 + " is a valid integer number");
else
[Link](input1 + " is not a valid integer number");
m = [Link](input2);
if ([Link]() && [Link]().equals(input2))
[Link](input2 + " is a valid integer number");
else
[Link](input2 + " is not a valid integer number");
Output:
abc is not a valid integer number
1234 is a valid integer number
176. What is the difference between the expressions String s =
“Temporary” and String s = new String(“Temporary “)? Which one is
better and more efficient?
Ans:
177. In Java, can two equal objects have different hash codes?
Ans: Yes, in Java, it is possible for two equal objects to have different hash
codes. Let me explain why:
Hash Codes and Equality:
In Java, every object has a hash code, which is an integer value generated by
the hashCode() method.
The hash code is used for efficient storage and retrieval in hash-based data
structures like hash maps and hash sets.
When you override the equals() method in your custom class, you should also
override the hashCode() method to ensure consistency between equality and
hash code.
178. How can we print an Array in Java?
Ans: Java array is a data structure where we can store the elements of
the same data type. The elements of an array are stored in a contiguous
memory location. So, we can store a fixed set of elements in an array.
Java for loop
Java for loop is used to execute a set of statements repeatedly until a
particular condition is satisfied.
In the following example, we have created an array of length four and
initialized elements into it. We have used for loop for fetching the values
from the array. It is the most popular way to print array in Java.
public class PrintArrayExample1
{
public static void main(String args[])
{
//declaration and instantiation of an array
int arr[]=new int[4];
//initializing elements
arr[0]=10;
arr[1]=20;
arr[2]=70;
arr[3]=40;
//traversing over array using for loop
for(int i=0;i<[Link];i++) //length is the property of the array
[Link](arr[i]);
}
}
Java for-each loop
Java for-each loop is also used to traverse over an array or collection. It works on the basis
of elements. It returns elements one by one in the defined variable
In the following example, we have created an array of String type of length
four and initialized elements into it. We have used for-each loop to traverse
over the array.
public class PrintArrayExample2
{
public static void main(String args[])
{
// declaration and instantiation of an array
String[] city = new String[4];
//initializing elements
city[0] = "Delhi";
city[1] = "Jaipur";
city[2] = "Gujarat";
city[3] = "Mumbai";
//traversing over array using for-each loop
for (String str : city)
{
[Link](str);
}
}
}
Java [Link]() method
Java [Link]() is a static method of Arrays class which belongs to [Link] package
It contains various methods for manipulating array.
It accepts an array of any primitive type as an argument. It returns a string
representation of an array that contains a list of array's elements. The
elements of an array are converted to String by [Link](int) .
import [Link];
public class PrintArrayExample3
{
public static void main(String[] args)
{
//declaring and initializing array
int array[] = {34,-10, 56, -9, -33};
//returns string representation of the specified array
[Link]([Link](array));
}
}
179. What is the difference between pass-by-reference and pass-by-value?
Ans: Pass by Value:
In pass by value, the value of a function parameter is copied to another
location in memory.
When accessing or modifying the variable within the function, it operates on
the copied value, not the original.
Changes made to the copied value do not affect the original value.
This method is commonly used in languages like C, C++, and Java.
int findNewValue(int value) {
int newValue = value * 2;
return newValue;
}
Pass by Reference:
In pass by reference, the memory address (reference) of the actual variable is
passed to the function.
The function can directly access and modify the original variable.
Changes made to the referenced variable affect the original value.
This method is commonly used in languages like Python (for mutable objects)
and C++ (using references).
def modify_list(lst):
[Link](42)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # [1, 2, 3, 42]
Pass by value copies the value, while pass by reference passes the memory
address (reference) to the original variable
180. What are the different ways to sort a collection in Java?
Ans: Using [Link]():
The [Link]() method is part of the [Link] class.
It sorts the elements in a specified list (e.g., ArrayList, LinkedList, etc.) in
ascending order.
ArrayList<String> myList = new ArrayList<>();
[Link]("Geeks For Geeks");
[Link]("Friends");
[Link]("Dear");
[Link]("Is");
[Link]("Superb");
[Link](myList);
[Link]("List after sorting: " + myList);
// Output: [Dear, Friends, Geeks For Geeks, Is, Superb]
Using [Link]() for Descending Order:
You can sort in descending order by providing a custom comparator using
[Link]().
[Link](myList, [Link]());
[Link]("List after sorting (descending): " + myList);
// Output: [Superb, Is, Geeks For Geeks, Friends, Dear]
Using [Link]():
Starting from Java 8, the List interface has a sort() method.
It allows you to sort a list in ascending order.
[Link]([Link]());
Using the Comparator Interface:
You can define custom sorting criteria using the Comparator interface
class Student {
int rollno;
String name, address;
// Constructor and other methods...
public String toString() {
return rollno + " " + name + " " + address;
}
}
List<Student> students = new ArrayList<>();
// Add students to the list...
[Link](students, new Comparator<Student>() {
public int compare(Student a, Student b) {
return [Link] - [Link];
}
});
Using the Comparable Interface:
Implement the Comparable interface in your class to define natural ordering.
class Student implements Comparable<Student> {
// Fields and methods...
public int compareTo(Student other) {
return [Link] - [Link];
}
}
181. Does java support multiple inheritances?
Ans: Yes, Java supports single inheritance but not multiple inheritance
directly.
Multiple inheritance occurs when a class inherits from more than one
superclass.
Java does not allow multiple inheritance of classes (i.e., a class cannot extend
multiple classes).
The reason behind this restriction is to avoid the “diamond problem.”
The diamond problem occurs when a class inherits from two classes that have
a common superclass. If both parent classes have the same method, which one
should the child class inherit?
To address this, Java uses interfaces (which allow multiple inheritance of
method signatures) instead of multiple inheritance of classes.
interface A {
void methodA();
}
interface B {
void methodB();
}
class MyClass implements A, B {
public void methodA() {
// Implementation for methodA...
}
public void methodB() {
// Implementation for methodB...
}
}
182. Can we define final methods in an interface?
Ans: By default, all the methods of an interface are public and abstract
If we don’t provide public,abstarct then complier has placed the public and, abstract
modifiers before the method by default
In addition to this as of Java9 you can have default, static, private, private and
static with the methods of an interface. Except these you cannot use any other
modifiers with the methods of an interface.
Moreover, if you declare a method final you cannot override/implement it and,
an abstract method must be overridden or implemented. Therefore, you cannot
declare the method of an interface final.
If you still do so, it generates a compile time error saying “modifier final not
allowed here”.
183. Can we develop a final abstract class?
Ans:no we can not
Ans:
A final class is one that cannot be subclassed or extended further.
When you declare a class as final, it means that no other class can inherit
properties or methods from it.
If you attempt to extend a final class, Java will give you a compile-time error.
An abstract class is declared using the abstract keyword.
It serves as a blueprint for other classes and can have both abstract methods
(without a body) and concrete methods (with a body).
Abstract classes are meant for implementing the concept of abstraction.
Unlike normal (non-abstract) classes, abstract classes can have abstract
methods.
All abstract methods declared in an abstract class must be overridden by its
subclasses.
184. Can we develop a static method in an abstract class?
Ans: Yes, you can have static methods in an abstract class.
A static method is associated with the class itself, not with any specific
instance of the class.
Since static methods do not rely on instance-specific properties, they can be
defined in an abstract class.
abstract class AbstractClassExample {
static void myStaticMethod() {
[Link]("This is a static method in an abstract class.");
}
// Other abstract or concrete methods can also be defined here
}
public class Main {
public static void main(String[] args) {
[Link](); // Calling the static method
}
}
Why Static Methods Can Exist in Abstract Classes:
Static methods do not require an instance of the class to be invoked.
Since abstract classes cannot be instantiated directly (you can’t create objects
of an abstract class), there’s no conflict with the concept of abstraction.
However, you cannot declare a static method as abstract because it would be
impossible to provide an implementation for it (since static methods cannot
be overridden).
Interface Consideration:
In contrast to abstract classes, interfaces cannot declare static methods
(although they can declare default and static methods since Java 8).
The decision not to allow static methods in interfaces was likely made to
prevent misuse of interfaces.
185. Can we declare a variable in the interface without initializing it?
Ans: In Java, all variables declared within an interface are implicitly public,
static, and final.
This means that they are treated as constants and must be initialized when
declared.
The reason for this requirement is that interface variables are meant to define
constants or shared values across implementing classes.
Since interfaces cannot have constructors (they only define behavior), there’s
no way to initialize these variables later.
Therefore, you must provide an initial value for any variable declared in an
interface.
186. What is the difference between JDK and JRE?
Asn: JDK (Java Development Kit):
The JDK is used for developing Java applications and applets.
It provides a software development environment with tools necessary for
writing, compiling, and debugging Java code.
Key features of JDK:
Contains the Java Runtime Environment (JRE).
Includes development tools like compilers, debuggers, and archivers.
Platform-specific (separate installers for Windows, macOS, and Unix systems).
Allows developers to create and run Java programs on their local machines.
Supports multiple JDK versions on the same computer.
JRE (Java Runtime Environment):
The JRE is the implementation of the JVM (Java Virtual Machine).
It provides an environment for executing Java programs.
Key features of JRE:
Contains the Java Virtual Machine (JVM), which interprets and executes Java
bytecode.
Includes Java binaries (class libraries) required for program execution.
Platform-dependent like JDK (separate versions for different platforms).
Does not include development tools (no compiler or debugger).
Used when you only need to run Java programs without development or
compilation.
Relationship:
JDK = JRE + additional development tools.
JRE = JVM + class libraries for program execution.
187. What is Java Virtual Machine (JVM)?
Ans: JVM is the abbreviation for Java Virtual Machine which is a
specification that provides a runtime environment in which Java byte code
can be executed i.e. it is something that is abstract and its implementation is
independent of choosing the algorithm and has been provided by Sun and
other companies. It is JVM which is responsible for converting Byte code to
machine-specific code. It can also run those programs which are written in
other languages and compiled to Java bytecode. The JVM performs the
mentioned tasks: Loads code, Verifies code, Executes code, and Provides
runtime environment.
188. What is a JIT compiler?
Ans: A Just-In-Time (JIT) compiler is a critical component in the Java
Runtime Environment (JRE).
Definition:
The JIT compiler is responsible for performance optimization of Java-based
applications during runtime.
Unlike traditional compilers that compile code ahead of time, the JIT compiler
compiles code on the fly as the program executes12.
It dynamically translates bytecode (the intermediate representation of Java
programs) into native machine code that the hardware can execute directly
189. Why did people say Java is a ‘write once and run anywhere’ language?
Ans: In Java, the program is not converted to code directly understood by
Hardware, rather it is converted to bytecode(.class file), which is interpreted
by JVM, so once compiled it generates bytecode file, which can be run
anywhere (any machine) which has JVM( Java Virtual Machine) and hence it
gets the nature of Write Once and Run Anywhere.
190. Do you think ‘main’ used for the main method is a keyword in Java?
Ans: While “main” is not a reserved keyword, it plays a crucial role as the
entry point for Java programs.
Purpose of the main Method:
The main method is the starting point for the Java Virtual Machine (JVM) to
execute a Java program.
When you run a Java program, the JVM looks for a method named main with
a specific signature.
This method is where the program begins its execution.
191. Can we write the main method as public void static instead of the
public static void?
Ans: Method Signature:
The main method serves as the entry point for a Java program.
Its signature must adhere to a specific format: public static void
main(String[] args).
Breaking down the parts:
public: Indicates that the method is accessible from outside the class.
static: Denotes that the method belongs to the class itself (not an instance of
the class).
void: Specifies that the method does not return any value.
main: The name of the method.
(String[] args): The parameter list (used for command-line arguments).
Why It Must Be public static void:
The order of modifiers (public, static, and void) matters:
public static void ensures that the method can be accessed from anywhere.
void specifies that the method doesn’t return a value.
If you change the order (e.g., public void static), it becomes invalid syntax.
192. In Java, if we do not specify any value for local variables, what will
be the default value of the local variables?
Ans: In Java, local variables do not have any default values. Unlike instance
variables (fields) that get default values (e.g., 0 for numeric types, null for
reference types), local variables must be explicitly initialized before you use
them. If you attempt to access an uninitialized local variable, the compiler
will throw an error
public class Example {
public static void main(String[] args) {
int x; // Local variable 'x' declared but not initialized
[Link](x); // Error: Variable 'x' might not have been
initialized
}
}
n the above code, the local variable x is declared but not assigned any value.
If you try to print its value, the compiler will raise an error because it doesn’t
have a default value.
To avoid this error, always initialize local variables before using them in your
code.
193. Let’s say we run a java class without passing any arguments. What
will be the value of the String array of arguments in the Main method?
Ans: When you run a Java class without passing any command-line
arguments, the String array named args in the main method will be empty. In
other words, it will have zero elements.
194. What is the difference between byte and char data types in Java?
Ans:
195. In Java, why do we use a static variable?
Ans: . Java actually doesn’t have the concept of Global variable. To define a
Global variable in java, the keyword static is used.
Suppose there are 25 students in the Production Engineering department of
NIT Agartala. All students have its unique enrollment number, registration
number, and name. So instance data member is good in such a case. Now all
instance data members will get memory each time when the object is created.
Here, “department” refers to the common property of all the objects. If we
make it static, this field will get the memory only once.
Thus static variables can be used to refer to the common property of all
objects (which is not unique for each object), for example, college name of
students, company name of employees, CEO of a company, etc. It makes the
program memory efficient (i.e., it saves memory).
196. What is the purpose of the static method in Java?
Ans: The static keyword is used to construct methods that will exist regardless
of whether or not any instances of the class are generated. Any method that uses
the static keyword is referred to as a static method.
Features of static method:
A static method in Java is a method that is part of a class rather than an instance
of that class.
Every instance of a class has access to the method.
Static methods have access to class variables (static variables) without using the
class’s object (instance).
Only static data may be accessed by a static method. It is unable to access data
that is not static (instance variables).
In both static and non-static methods, static methods can be accessed directly.
197. In what scenario do we use a static block?
Ans: In Java, a static block (also known as a static initializer block or static
initialization block) is a special block of code that gets executed when a class
is loaded into memory by the Java ClassLoader. It is used for static
initialization of a class
Initializing Static Variables:
One common use case for static blocks is to initialize static variables.
When you need to perform some complex initialization logic for a static
variable (e.g., reading configuration files, setting up resources), you can use
a static block.
198. What is the difference between static and instance methods in Java?
Ans: Static Methods:
Definition: Static methods are associated with the class itself, not with any
specific instance (object) of the class.
Access: They can be called using the class name (e.g.,
[Link]()) or through a reference to an object of that class.
Memory Allocation: Static methods are stored in the Permanent Generation
space of the heap (or metaspace from Java 8 onwards).
Access to Variables: They can only access static variables (class-level
variables) directly.
Overriding: Static methods cannot be overridden (they are resolved using
static binding at compile time).
Instance Methods:
Definition: Instance methods require an object of the class to be created
before they can be called.
Access: They are called using an object reference (e.g.,
[Link]()).
Memory Allocation: Instance methods themselves are stored in the Permanent
Generation space (or metaspace), but their parameters, local variables, and
return values are allocated in the stack.
Access to Variables: They can access both static variables and instance
variables.
Overriding: Instance methods can be overridden (they are resolved using
dynamic binding at runtime).
Common Use Cases:
Static Methods:
Utility functions (e.g., [Link]()).
Factory methods for creating objects (e.g., [Link]()).
Instance Methods:
Accessing instance-specific data.
Performing operations on object attributes.
199. How can you change the value of a final variable in Java?
Ans: In Java, a final variable is one that cannot be reassigned once it has
been given a value. However, the behavior of final variables depends on
whether they are primitive types or reference types (objects). Let’s explore
both cases:
Final Primitive Variables:
For primitive types (such as int, double, char, etc.), a final variable cannot be
changed after its initial assignment.
final int x = 10;
// x = 20; // Error: Cannot assign a value to final variable 'x'
Final Reference Variables:
For reference types (such as objects), a final variable means that the reference
itself cannot be changed (i.e., it cannot point to a different object).
However, the state (fields) of the object it refers to can still be modified.
final StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // Valid: Modifying the state of the StringBuilder
// sb = new StringBuilder("New"); // Error: Cannot assign a value to final
variable 'sb'
200. Can a class be marked final in Java?
Ans:Yes we can
Once a class is declared as final, it cannot be further modified by inheritance.
It signifies that the class’s implementation is complete and should not be
extended.
201. How can we create a final method in Java?
Ans:yes we can
Once method is final we can not overide it
202. How can we prohibit inheritance in Java?
Ans:By declaring class as final we prohibit inheritance
203. What is a blank final variable in Java?
Ans: In Java, a blank final variable is a final variable that is not initialized
during its declaration. Instead, it is assigned a value later, typically within a
constructor
A blank final variable is declared with the final keyword but without an initial
value.
It must be assigned a value before it is used (usually within a constructor).
204. How can we initialize a blank final variable?
Ans: Initialization in Constructors:
A blank final variable must be initialized in a constructor.
You cannot directly assign a value to a blank final variable during declaration.
public class MyClass {
final int myValue; // Blank final variable
public MyClass(int value) {
myValue = value; // Initializing in constructor
}
// Other methods and code...
}
Immutable Objects:
Blank final variables are often used to create immutable objects (objects
whose members cannot be changed once initialized).
They ensure that the value remains constant throughout the object’s lifetime.
In summary, initialize a blank final variable in a constructor to create
immutable objects or ensure proper initialization.
205. Is it allowed to declare the main method as final?
Ans: Yes, it is allowed to declare the main() method as final in Java. The
compiler does not throw any error if you mark the main() method as final.
However, it is not a common practice, and its use might not be meaningful in
most scenarios.
Here are some points to consider:
Technical Validity:
You can declare the main() method as final, but it doesn’t significantly impact
the behavior of the program.
Since the main() method is static (and therefore cannot be overridden),
marking it as final doesn’t change its behavior.
Practical Significance:
The main() method is typically the entry point for your program.
It is not meant to be overridden by subclasses (since it is static).
Therefore, making it final doesn’t add much value
206. What is the purpose of the package in Java?
Ans: In Java, a package is a mechanism used to organize related classes,
interfaces, and subpackages. It provides several benefits and serves the
following purposes:
Preventing Naming Conflicts:
Packages help prevent naming conflicts by allowing you to group related
classes together.
For example, if there are two classes named Employee in different packages
(e.g., [Link] and [Link]), the package
structure ensures that their names remain unique.
Organizing Code:
By organizing classes into packages, you make your code more modular and
easier to navigate.
Packages provide a way to group related functionality together, making it
easier to locate specific classes.
Access Control:
Packages provide access control:
Protected Access: Members (fields and methods) with the protected access
modifier are accessible within the same package and its subclasses.
Default (Package-Private) Access: Members without any access specifier (i.e.,
no modifier) are accessible only within the same package.
Reusability:
You can reuse existing classes from packages in your program.
By importing classes from existing packages, you can use them as needed.
207. What is [Link] package?
Ans:
208. Which is the most important class in Java?
Ans: [Link]:
The Object class sits at the top of the class hierarchy tree. Every class, whether
predefined or user-defined, is a subclass of Object.
It provides essential methods like equals(), hashCode(), and toString().
You can override these methods in your custom classes to tailor their
behavior.
Learn more about Java Object class.
[Link]:
Strings are widely used in Java programming. They represent sequences of
characters.
The String class provides methods for creating and manipulating strings.
Strings are immutable (their values cannot be changed after creation).
209. Is it mandatory to import [Link] package every time?
Ams No, it is not mandatory to explicitly import the [Link] package every
time you write a Java program. The [Link] package is a default package in
Java, which means that its classes are automatically available to you without
requiring an explicit import statement1. Let me explain why:
Default Package:
When you create a Java class without specifying a package (i.e., you don’t use
the package keyword), it belongs to the default package.
The default package includes all classes in the [Link] package.
Therefore, you can directly use classes like String, Object, and Integer without
importing them explicitly.
210. What is a static import in Java?
Ans: In Java, a static import is a feature introduced in version 1.5 that allows
you to access static members (fields and methods) of a class directly without
specifying the class name or creating an object1
import static [Link];
packageName is the name of the package containing the class.
className is the name of the class.
staticMember is the specific static member being imported.
211. How to handle Exception in java explain?
Ans:By using try catch block
212. Will all the Try blocks in Java ends with Catch Blocks?
Ans: In Java, try-catch blocks are used for handling exceptions. However, it
is not mandatory for every try block to be followed by a corresponding catch
block.
try with catch:
The most common usage is to have a try block followed by one or more catch
blocks.
In this case, if an exception occurs within the try block, the appropriate catch
block will handle it.
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle exception of type 1
} catch (ExceptionType2 e2) {
// Handle exception of type 2
}
try with finally:
You can use a finally block after the try block.
The code in the finally block always executes, whether an exception occurs or
not.
It’s useful for cleanup tasks (e.g., closing resources like files or database
connections).
try {
// Code that may throw an exception
} finally {
// Cleanup code (always executed)
}
try without catch:
Sometimes you might want to handle exceptions at a higher level (e.g., in a
calling method).
In such cases, you can use a try block without a corresponding catch block.
public void someMethod() throws SomeException {
try {
// Code that may throw an exception
} finally {
// Cleanup code (always executed)
}
}
try without catch or finally:
Rarely, you might encounter situations where you only want to execute some
code within a try block.
For example, when using try-with-resources (Java 7+), you can automatically
close resources without explicitly writing a finally block
try (ResourceType resource = new ResourceType()) {
// Code that uses the resource
}
213. Which types of exceptions are caught at compile time?
Ans: Checked Exceptions:
Checked exceptions are also known as compile-time exceptions.
The compiler checks these exceptions during the compilation process to
ensure that the programmer handles them appropriately.
If a method throws a checked exception, the method must either handle the
exception using a try-catch block or specify the exception using the throws
keyword.
Examples of checked exceptions include:
IOException: Occurs when there is an error reading or writing a file.
ClassNotFoundException: Occurs when a class is not found while trying to
load it dynamically.
SQLException: Occurs when there is an error while accessing a database.
Unchecked Exceptions:
Unchecked exceptions (also called runtime exceptions) do not require explicit
handling at compile time.
These exceptions are not checked by the compiler during compilation.
They typically indicate programming errors or unexpected conditions.
Examples of unchecked exceptions include:
NullPointerException: Thrown when you try to access a null reference.
ArrayIndexOutOfBoundsException: Occurs when you access an array index
that is out of bounds.
ArithmeticException: Raised when an arithmetic operation (like division by
zero) is invalid.
In summary, checked exceptions are verified by the compiler, while
unchecked exceptions are not. It’s essential to handle checked exceptions
properly to ensure robust error handling in your Java programs!
214. When is the throw keyword used?
Ans: The throw keyword in Java is used to explicitly throw an exception
within your code. Here are the key points about its usage:
Throwing an Exception:
When you encounter an exceptional situation (such as an error or an
unexpected condition), you can use throw to raise an exception.
The throw statement is followed by an instance of an exception class (usually
a subclass of Throwable).
215. Explain Exception Handling methods.
Ans: try, catch, and finally Blocks:
The try block encloses the code where an exception might occur.
The catch block handles the exception if it occurs. You can have multiple catch
blocks for different exception types.
The finally block (optional) contains cleanup code that always executes,
regardless of whether an exception occurred.
throw Statement:
The throw keyword explicitly throws an exception.
You can throw both built-in exceptions (e.g., NullPointerException) and
custom exceptions (your own classes).
public void divide(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
// Perform division logic here
}
throws Clause:
When defining a method, you can use the throws keyword to declare the
exceptions that the method might throw.
The calling method must handle these exceptions or declare them in its own
throws clause.
public void processInput(int value) throws MyCustomException {
// Code that may throw MyCustomException
}
216. How can we access the private method of a class from outside the
class?
Ans: Reflection: You can use Java’s reflection mechanism to access private
methods. Here’s how:
Instantiate the Method class from the [Link] package, passing the
name of the private method.
Set the method as accessible using setAccessible(true).
Invoke the method using invoke(obj, args), where obj is an instance of the
class containing the private method.
import [Link];
class MyClass {
private void myPrivateMethod() {
[Link]("Accessing a private method!");
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyClass obj = new MyClass();
Method method =
[Link]("myPrivateMethod");
[Link](true);
[Link](obj);
}
}
217. What is Garbage Collection in Java?
Ans: Garbage collection in Java is the automated process of managing
memory by deleting objects that are no longer needed or used. It ensures
efficient memory utilization and frees up memory space during the execution
of Java programs
How It Works:
When Java programs run on the Java Virtual Machine (JVM), objects are
created on the heap, which is a portion of memory dedicated to the program.
The garbage collector (GC) identifies unused objects (those no longer
referenced by any part of the program) and deletes them.
This automatic process prevents memory leaks and ensures that sufficient
memory is available for creating new objects.
218. When does an object become eligible for Garbage Collection in Java?
Ans: An object is eligible for GC if it is unreachable.
After setting a reference to null, the object becomes suitable for garbage
collection.
219. Why do we use finalize() method in Java?
Ans: The finalize() method in Java serves as a crucial part of the garbage
collection process. Let’s explore its purpose and usage:
Overview:
The finalize() method is a protected method defined in the Object class, which
is the superclass of all Java classes.
When an object is no longer used or referenced, it becomes eligible for
garbage collection.
Before the garbage collector destroys an object, it invokes the finalize()
method (if overridden by the class).
The primary purpose of finalize() is to allow an object to perform any
necessary cleanup operations before its memory is reclaimed.
220. How many types of Nested classes are in Java?
Ans: In Java, there are four types of nested classes that allow you to define
classes within other classes.
Inner Classes (Non-Static Nested Classes):
Inner classes are declared inside another class (the outer class).
They have access to all members (including private members) of the outer
class.
To instantiate an inner class, you must first create an instance of the outer
class and then create the inner object within it.
class OuterClass {
// ...
class InnerClass {
// ...
}
}
Static Nested Classes:
Static nested classes are declared as static members of the outer class.
They do not require an instance of the outer class to exist.
Accessed using the enclosing class name: [Link].
class OuterClass {
// ...
static class StaticNestedClass {
// ...
}
}
Local Classes:
Local classes are defined within a method or a block of code.
They have limited scope and are not accessible outside the method/block.
Useful for encapsulating logic within a specific context.
221. Why do we use Nested Classes?
Ans: nested classes provide a powerful way to organize code, improve
encapsulation, and enhance code readability.
222. What is the difference between Nested and Inner classes in Java?
Ans: Nested Classes:
A nested class is any class that is defined within another class.
It can be either a static nested class or an inner class (non-static nested class).
Nested classes are used for logical grouping and to improve code organization.
They have access to members (fields and methods) of the enclosing class, even
if those members are declared private1.
Examples of nested classes:
Static Nested Class:
Declared as a static member of the outer class.
Accessed using the enclosing class name (e.g., [Link]).
Inner Class (Non-Static Nested Class):
Associated with an instance of the outer class.
Requires an instance of the outer class to exist before creating an instance of
the inner class.
Example:
Java
class Outer {
// ...
class Inner {
// ...
}
}
An inner class is a specific type of nested class.
It is a non-static nested class.
Key characteristics:
Associated with an Instance:
An inner class is associated with an instance of the outer class.
It can access all members (including private ones) of the outer class.
Must Be Instantiated via Outer Class:
To create an instance of an inner class, you must first create an instance of
the outer class.
223. What is a Nested interface?
Ans: In Java, a nested interface is an interface that is defined within another
interface or class. It is also known as an inner interface
Purpose of Nested Interfaces:
Nested interfaces are used to group related interfaces together, making them
easier to maintain.
They allow you to encapsulate interfaces within the classes where they are
used.
A nested interface must be accessed through the outer interface or class; you
cannot access it directly.
Points to Remember for Nested Interfaces:
If a nested interface is declared inside an interface, it must be public.
If a nested interface is declared within a class, it can have any access modifier.
Nested interfaces are declared as static.
1. Syntax of Nested Interface (Declared within an Interface):
Java
interface OuterInterface {
// ...
interface NestedInterface {
// ...
}
}
Syntax of Nested Interface (Declared within a Class):
Java
class OuterClass {
// ...
interface NestedInterface {
// ...
}
}
224. How can we access the non-final local variable inside a Local Inner
class?
Ans: The reason non-final local variables cannot be accessed inside a local
inner class is related to how Java handles these variables.
Local variables exist only during the lifetime of the method invocation where
they are declared.
When an inner class (local or anonymous) accesses a local variable, the
compiler generates an implicit copy of that variable as a member of the inner
class.
If the local variable were not final, it could change its value after the inner
class is created, leading to inconsistent behavior.
225. Can an Interface be defined in a Class?
Ans: In Java, you can define an interface inside a class. This type of
interface is known as a nested interface or an inner interface
Nested Interfaces (Inner Interfaces):
A nested interface is an interface that is declared within another class or interface.
It is used for logical grouping and to improve code organization.
Nested interfaces can be declared as public (within an interface) or with any other access modifier
(within a class).
The syntax for declaring a nested interface is similar to that of a regular interface.
interface OuterInterface {
// Other members of OuterInterface
interface NestedInterface {
// Declare methods and constants here
}
}
226. What are Wrapper classes in Java?
Ans: Wrapper classes in Java are classes that provide a way to use primitive
data types as objects. Each primitive data type has a corresponding wrapper
class, which encapsulates the primitive value and provides additional
functionality.
byte →Byte
short →Short
int →Integer
long →Long
float →Float
double →Double
char →Character
boolean →Boolean
227. What is System, out, and println in [Link] method calls?
Ans: System:
System is a final class defined in the [Link] package.
It provides access to the system environment and resources.
Contains several static fields and methods for interacting with the system.
out:
out is an instance of the PrintStream class.
It is a public and static member field of the System class.
Represents the standard output stream (usually the console).
println():
println() is a method of the PrintStream class.
It prints the argument passed to it and adds a new line to the output.
In summary, [Link]() is used to print data to the standard output
(usually the console) in Java
228. What is a Singleton class?
Ans: A Singleton class in Java is a special class that allows only one instance of
itself to be created. It ensures that there is a global point of access to that single
instance throughout the entire lifetime of a program. Let’s delve into the details
of Singleton classes:
Purpose of Singleton Classes:
In some scenarios, we want to restrict the creation of multiple instances of a
class.
Singleton classes ensure that there is only one instance, which can be accessed
globally.
Common use cases include logging systems, configuration managers, and
database connections.
Characteristics of Singleton Classes:
Single Instance: A Singleton class has only one instance.
Private Constructor: The constructor of a Singleton class is made private to
prevent external instantiation.
Static Method: A static method (often named getInstance()) provides access to
the single instance.
229. What is the difference between the Singleton class and the Static
class?
Ans: A Singleton class ensures that only one instance of itself exists throughout
the lifetime of an application.
It provides a global point of access to that single instance.
Has a private constructor to prevent external instantiation.
Provides a static method (often named getInstance()) to access the single
instance.
Common use cases: logging systems, configuration managers, and database
connections
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() { /* Private constructor */ }
public static Singleton getInstance() { return instance; }
}
Static Class:
Purpose:
A static class is a way of grouping related methods (functions) together in Java.
It does not allow instance variables; all members are class-level (static).
Characteristics:
Contains only static methods (no instance methods).
Cannot be instantiated (no constructor).
Common use cases: utility classes (e.g., Math, Collections).
public class MathUtils {
public static int add(int a, int b) { return a + b; }
public static int multiply(int a, int b) { return a * b; }
}
Comparison:
Instance Creation:
Singleton: Only one instance exists, created when needed.
Static class: No instances; all methods are accessed directly.
Method Access:
Singleton: Accessed via a static method (e.g., [Link]()).
Static class: Accessed directly (e.g., [Link](2, 3)).
230. What Is Collection?
Ans: A collection in Java refers to an object that groups multiple elements into
a single unit. Collections are used to store, retrieve, manipulate, and
communicate aggregate data. They provide a convenient way to work with
groups of objects, allowing you to perform operations such as searching, sorting,
insertion, manipulation, and deletion.
231. What Is List?
Ans: A list in Java is an ordered collection that allows you to store and access
elements sequentially.
Ordered Elements:
A list maintains the order of elements as they are added.
You can access elements by their index (position) within the list.
Duplicates Allowed:
Lists can contain duplicate elements (i.e., multiple occurrences of the same
value).
Unlike sets, which enforce uniqueness, lists allow repetition.
Null Values and Heterogeneous Elements:
You can store null values in a list
232. What Is The Difference Between ArrayList And LinkedList?
233. What Is The Difference Between List, Set, Map
234. What Is the Difference Between Vector And Arraylist?
235. What Is The Difference Between Hashmap And Hashtable
236. What Is The Difference Between Collection And Array?
237. What Is the Difference between HashSet And Linkedhashset
238. What Is Iterator In Java?
Ans: Iterator interface provides the facility of iterating the elements in a
forward direction only.
239. What Is the Difference between Listiterator And Iterator
240. What Is The Default Capacity Of Arraylist And Hashtable?
Ans: Arraylist is 10
Hashtable is 11
241. How To Sort Employee Class Using Comparator?
Ans: Java Comparator interface is used to order the objects of a user-defined
class.
This interface is found in [Link] package and contains 2 methods
compare(Object obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the
basis of any data member, for example, rollno, name, age or anything else.
This class defines comparison logic based on the age. If the age of the first object
is greater than the second, we are returning a positive value. It can be anyone
such as 1, 2, 10. If the age of the first object is less than the second object, we
are returning a negative value, it can be any negative value, and if the age of
both objects is equal, we are returning 0.
242. What Is Super Most Class In Java, And Explain All Methods Of The
Superclass?
Ans:
In Java, the Object class is the parent class of all the Java classes. Every Java
class is a direct or indirect child of the Java Object class. Hence, every Java class
extends the Object class. Therefore, we need not to write the following statement
to inherit the class.
The subclass internally inherits all the methods of the Object class. Hence, we
can say that the Object class is the cosmic superclass in Java. The class belongs
to [Link] package.
243. What Is Collection And A Collections Framework?
Ans: Collection is a interface present in [Link] package. It is used to
represent a group of individual objects as a single unit. It is similar to the
container in the C++ language. The collection is considered as the root interface
of the collection framework. It provides several classes and interfaces to
represent a group of individual objects as a single unit.
The List, Set, and Queue are the main sub-interfaces of the collection interface.
The map interface is also part of the java collection framework, but it doesn’t
inherit the collection of the interface. The add(), remove(), clear(), size(), and
contains() are the important methods of the Collection interface.
Collections is a utility class present in [Link] package. It defines several utility
methods like sorting and searching which is used to operate on collection. It has
all static methods. These methods provide much-needed convenience to
developers, allowing them to effectively work with Collection Framework. For
example, It has a method sort() to sort the collection elements according to
default sorting order, and it has a method min(), and max() to find the minimum
and maximum value respectively in the collection elements
244. What’s The Difference Between Stack And Queue?
Ans:
245. What Is An Array
Ans: Normally, an array is a collection of similar type of elements which has
contiguous memory location.
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
246. What is the difference Between Array And Arraylist?
247. How To Sort The Collections?
Ans: We can sort the elements of:
String objects
Wrapper class objects
User-defined class objects
Collections class provides static methods for sorting the elements of a collection.
If collection elements are of a Set type, we can use TreeSet. However, we cannot
sort the elements of List. Collections class provides methods for sorting the
elements of List type elements.
import [Link].*;
class TestSort1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Viru");
[Link]("Saurav");
[Link]("Mukesh");
[Link]("Tahir");
[Link](al);
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
248. What Is Treeset?
Ans: Java TreeSet class implements the Set interface that uses a tree for
storage. It inherits AbstractSet class and implements the NavigableSet interface.
The objects of the TreeSet class are stored in ascending order.
The important points about the Java TreeSet class are:
Java TreeSet class contains unique elements only like HashSet.
Java TreeSet class access and retrieval times are quiet fast.
Java TreeSet class doesn't allow null element.
Java TreeSet class is non synchronized.
Java TreeSet class maintains ascending order.
Java TreeSet class contains unique elements only like HashSet.
Java TreeSet class access and retrieval times are quite fast.
Java TreeSet class doesn't allow null elements.
Java TreeSet class is non-synchronized.
Java TreeSet class maintains ascending order.
The TreeSet can only allow those generic types that are comparable. For example
The Comparable interface is being implemented by the StringBuffer class.
249. In Which Scenarios, ArrayList And Linkedlist Will Be Used?
Ans: ArrayList provides constant time for search operation, so it is better to
use ArrayList if searching is more frequent operation than add and remove
operation. The LinkedList provides constant time for add and remove operations.
So it is better to use LinkedList for manipulation.
ArrayList has O(1) time complexity to access elements via the get and set
methods.
LinkedList has O(n/2) time complexity to access the elements.
LinkedLinked class implements Deque interface also, so you can get the
functionality of double ended queue in LinkedList. The ArrayList class doesn't
implement Deque interface.
In sort, ArrayList is better to access data wherease LinkedList is better to
manipulate data. Both classes implements List interface.
250. What Happens If You Add the Same Key In The Hashmap?
Ans: The HashMap is a class that implements the Map interface. It is based on
the Hash table. It allows null values and null keys.
You can store key-value pairs in the HashMap object. Once you do so you can
retrieve the values of the respective keys but, the values we use for keys should
be unique
Duplicate values
The put command associates the value with the specified key. i.e. if we add a
key-value pair where the key exists already, this method replaces the existing
value of the key with the new value,
251. Can We Add a Null Key To The Hashmap?
Ans: Yes, you can set null as key in Java HashMap.
import [Link];
import [Link];
public class Demo {
public static final void main(String[] args) {
Map<String,String>map = new HashMap<>();
[Link]("Football", "A");
[Link]("Squash", "B");
[Link]("Cricket", "C");
[Link]("Hockey", "D");
[Link]("Rugby", "E");
[Link]("Golf", "F");
[Link]("Archery", "G");
[Link]("Size of HashMap = " + [Link]());
[Link](null, "H");
[Link]("Updated Size of HashMap = " + [Link]());
[Link]("For null = " + [Link](null));
}
252. What Is The Difference Between StringBuffer & StringBuilder?
253. What Is Difference B/w String S=new String(),string S=””;
Ans: Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance
is returned. If the string doesn't exist in the pool, a new string instance is
created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
254. Is String A Data Type In Java?
Ans: Definitely, String is not a primitive data type. It is a derived data type.
Derived data types are also called reference types because they refer to an object.
They call methods to perform operations. A string is a Class present in [Link]
package. A string can be created directly by assigning the set of characters
enclosed in double-quotes to a variable or by instantiating a String class using
the new keyword
255. Why Is StringBuffer Called Mutable?
Ans:
256. What Are The Different Access Levels In Java? Explain
Ans:=> in Java, Access modifiers help to restrict the scope of a class,
constructor, variable, method, or data member. It provides security,
accessibility, etc to the user depending upon the access modifier used with
the element. Let us learn about Java Access Modifiers, their types, and the
uses of access modifiers in this article.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data
member – It is said to be having the default access modifier by
default. The data members, classes, or methods that are not declared
using any access modifiers i.e. having default access modifiers are
accessible only within the same package.
In this example, we will create two packages and the classes in the
packages will be having the default access modifiers and we will try to
access a class from one package from a class of the second package
// Java program to illustrate default modifier
package p1;
// Class Geek is having Default access modifier
class Geek
{
void display()
{
[Link]("Hello World!");
}
}
// Java program to illustrate error while
// using class from different package with
// default modifier
package p2;
import p1.*;
// This class is having default access modifier
class GeekNew
{
public static void main(String args[])
{
// Accessing class Geek from package p1
Geek obj = new Geek();
[Link]();
}
}
2. Private Access Modifier
The private access modifier is specified using the keyword private. The
methods or data members declared as private are accessible only within
the class in which they are declared.
Any other class of the same package will not be able to access these
members.
Top-level classes or interfaces can not be declared as private because
o private means “only visible within the enclosing class”.
o protected means “only visible within the enclosing class and any
subclasses”
Hence these modifiers in terms of application to classes, apply only to
nested classes and not on top-level classes
In this example, we will create two classes A and B within the same package
p1. We will declare a method in class A as private and try to access this
method from class B and see the result
// Java program to illustrate error while
// Using class from different package with
// Private Modifier
package p1;
// Class A
class A {
private void display()
{
[Link]("GeeksforGeeks");
}
}
// Class B
class B {
public static void main(String args[])
{
A obj = new A();
// Trying to access private method
// of another class
[Link]();
}
}
error: display() has private access in A
[Link]();
3. Protected Access Modifier
The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within
the same package or subclasses in different packages.
In this example, we will create two packages p1 and p2. Class A in p1 is
made public, to access it in p2. The method display in class A is protected
and class B is inherited from class A and this protected method is then
accessed by creating an object of class B.
// Java Program to Illustrate
// Protected Modifier
package p1;
// Class A
public class A {
protected void display()
{
[Link]("GeeksforGeeks");
}
}
// Java program to illustrate
// protected modifier
package p2;
// importing all classes in package p1
import p1.*;
// Class B is subclass of A
class B extends A {
public static void main(String args[])
{
B obj = new B();
[Link]();
}
}
Public Access modifier
The public access modifier is specified using the keyword public.
The public access modifier has the widest scope among all other access
modifiers.
Classes, methods, or data members that are declared as public
are accessible from everywhere in the program. There is no restriction on
the scope of public data members.
257. What Is Singleton Class?
258. What Is Encapsulation?
259. Which Is The Uppermost Class For All The Classes In Java?
260. Explain “toString()” Of Object Class
261. Explain “hashcode()” Of Object Class
262. Explain “equals()” Of Object Class
263. Can A Subclass Override All These Above Methods?
264. What Is The Final Method In Java?
265. What Is The Final Class In Java?
266. What Is The Use Of Finalize() Method In Java?
267. What Is The Use Of The Clone() Method?
268. What Is A Marker Interface? Explain And Mention At Least Two
Available Marker Interface
269. Strings Are Immutable In Java. Justify
270. Can We Have Inherited The String Class? Justify
271. Explain The Behavior Of Tostring(),hashcode() And Equals() Method
Of String Class
272. What Is A String Constant Pool And Non-constant Pool?
273. What Are Arrays?
274. What Is A Primitive Array?
275. What Are Boxing And Unboxing?
276. What Are The Wrapper Classes?
277. What Is A Collection Api/framework?
278. Explain the List Type Of Collection.
279. Explain the Set Type Of Collection.
280. Explain The Queue Type Of Collection.
281. What Are The Exceptions?
282. How To Handle An Exception?
283. What Has Checked Exceptions?
284. What Are Unchecked Exceptions?
285. Different Ways Of Handling Checked Exceptions?
286. What Is The Difference Between Final, Finalize(), And Finally In Java
287. What Is The Use Of The Scanner Class In Java?
288. What Is The Oops Concept Or Opps Principle?
289. What Is Oops
290. List Out The Oops Concepts
291. What Is The Oop Principle, Where You Used Polymorphism In Your
Project?
292. Provide Byte Datatype Default Value In Java
293. Jvm Is A Dependent Or Independent Platform
294. Checked And Unchecked Exception
295. Why String Is Immutable
296. What Is The Return Type Of Getwindowhandles();
297. What Are The Types Of Assertion And What Is An Assertion In Java
298. Difference Between Interface And Abstract Classes
299. What Is A Static Variable
300. What Is The Difference Between Final, Finalize, And Finally
301. What Is The Difference Between Public, Private, And Protected
302. What Is The Difference Between An Interface And An Abstract Class?
303. What is the difference Between Hashmap And Hashtable?
304. How Can You Declare Constant Variables In Java?
305. Can We Declare A Final Global Variable And Use It Without
Initializing It?
306. What Does A Method’s Return Type Signify?
307. What Is Call By Value And Call By Reference?
308. What Is A Constructor?
309. What Are The Two Types Of Constructors?
310. What Is A Default Constructor?
311. What Is This() Calling Statement?
312. What Is Recursion?
313. Recursion While Constructor Overloading Will Result In Compile-
time Or Runtime Error
314. What Is “this” Keyword?
315. What Is The Instance Variable Hiding?
316. What Is The Use Of This Keyword?
317. What Is Inheritance?
318. What Are The Different Types Of Inheritance?
319. What Is Extends Keyword?
320. Does Java Support Multiple Inheritances?
321. What Is The Diamond Problem?
322. Why Doesn’t Java Support Multiple Inheritances?
323. What Is A Super() Calling Statement?
324. What Is A “super” Keyword?
325. What Is The Difference Between Super() Calling And This() Calling
Statement?
326. What Is The Difference Between “super” And “this” Keyword?
327. What Is Method Overriding?
328. Can We Override Static Methods?
329. What Is An Abstract Method?
330. What Is An Abstract Class?
331. Can We Instantiate An Abstract Class?
332. What Is The Rule To Be Followed By The Subclass Of An Abstract Class
333. Can An Abstract Class Inherit Another Abstract Class
334. Is Abstract Class 100% Abstract? Explain
335. What Is An Interface?
336. What Is The Difference Between An Abstract Class And An Interface?
337. Does The Abstract Class Have Constructors? If Yes, Why?
338. Do Interfaces Have Constructors?
339. Can We Instantiate An Interface?
340. What Is The Implements Keyword?
341. Can An Interface Inherit From Another Interface?
342. What Is Casting?
343. What Is Primitive Casting?
344. What Is Auto Widening And Explicit Narrowing?
345. What Is Derived Or Object Casting?
346. What Are Auto Upcasting And Explicit Downcasting?
347. Can We Achieve Object Casting Without Inheritance?
348. Can We Achieve Downcasting Without Upcasting?
349. What Is Polymorphism?
350. Explain Different Types Of Polymorphism.
351. What Is Abstraction?
352. What Are The Packages?
353. Why Packages?
354. What Are The New Features Released In Java 8?
355. What Are The Main Benefits Of New Features Introduced In Java 8?
356. What Is A Default Method In An Interface?
357. How Does Java 8 Solve the Diamond Problem Of Multiple Inheritance?
358. Is It Possible To Have a Default Method Definition In An Interface
Without Marking It With a Default Keyword?
359. Can We Create A Class That Implements Two Interfaces With Default
Methods Of the Same Name And Signature?
360. How Java 8 Supports Multiple Inheritance?
361. In Case, We Create A Class That Extends A Base Class And Implements
An Interface. If Both Base Class And Interface Have A Default Method With
the Same Name And Arguments, Then Which Definition Will Be Picked By
Jvm?
362. If We Create the Same Method And Define It In A Class, In Its Parent
Class, And An Interface Implemented By The Class, Then the Definition
Will Be Invoked If We Access It Using The Reference Of the Interface And
The Object Of the Class?
363. Can We Access A Static Method Of An Interface By Using Reference Of
The Interface?
364. What Are The Main Differences Between An Interface With a Default
Method And An Abstract Class In Java 8?
365. What Is The Difference Between Jdk, Jre, And Jvm?
366. What Is The Difference Between An Inner Class And A Sub-class?
367. What Is the Final Keyword In Java? Give An Example.
368. What’s The Base Class In Java From Which All Classes Are Derived?
369. What Is A Platform?
370. What Is Classloader?
371. What Is The Static Method?
372. Can A Class Have Multiple Constructors?
373. What Is An Interface And Why Interface?
374. What Is An Abstract Class?
375. What Is The Difference Between Abstract Class And Interface And
Concrete Class(Normal Class)
376. Why Abstract Class?
377. What Is Polymorphism?
378. What Are Overloading And Overriding?
379. Explain Static And Nonstatic Members.
380. What Is the Difference between Final, Finalize, And Finally?
381. What Is The Difference Between Equals And == Operator
382. What Is The Case When You Override Hashcode() And Equals()? What
Problem Can Occur If We Don’t Override Hashcode() Method?
383. What Are Immutable Classes?
384. Mention The Access Specifiers Used In Java.
385. What Is Singleton In Java?
386. What Is Jdk?
387. Which Is The Latest Version Of Java?
388. What Is The Advantage Of Java?
389. Javac And Java Commands Are Available In Which Folder?
390. What Is The Signature Of The Main Method?
391. What Is A Keyword? List Some Keywords.
392. What Is An Identifier?
393. What Are Literals?
394. Java Is Platform Independent. Explain
395. What Is Jre?
396. What Is A Variable?
397. Mention All The Primitive Data Types In Java
398. What Are The Primitive Variables?
399. What Are Reference Variables?
400. What Is String In Java?
401. What Is The Method?
402. General Syntax For A Method?
403. What Is Method Overloading?
404. Why Method Overloading?
405. What Are The Members?
406. What Are Static Members?
407. What Are Nonstatic Members?
408. List Out The Differences Between Static And Non-static Members.
409. What Is An Object?
410. What Is A Class?
411. What Are Global Variables?
412. How Can You Access A Static Global Variable Of A Class?
413. How Can You Access Non-static Global Variables Of A Class
414. What Will Be The Default Value For Global Variables?
415. What Will Be The Default Value For Reference Variables?
416. What Is The Default Value For The Boolean Variable?
417. What Are The Differences Between Local And Global Variables?
418. List Any Five Features Of Java.
419. Why Is Java Considered Dynamic?
420. Define Class.
421. Define JVM, JDK And JRE?
422. What Is Abstraction?
423. What Is Encapsulation?
424. Can We Override A Static Method Or a Main Method?
425. What Is The Method Of Hiding?
426. What Is the Difference between Comparable And Comparator?
427. What Is Treeset?
428. Why Is Java Known As The Platform Independent Programming
Language?
429. Name The Data Types That Java supports.
430. Throw Some Light On The Main Features Of Java.
431. Define Autoboxing And Unboxing.
432. Explain Java Heap Space And Garbage Collection.
433. What Is The Difference Between Final, Finalize, And Finally?
434. What Is Wrapper Class?
435. What Is An Immutable Class?
436. What Is Array?
437. What Is String? What is the difference Between StringBuilder And
Strinngbuffer?
438. What Is Function?
439. What Is Class?
440. What Is Object?
441. What Is Polymorphism?
442. What Is Function Overloading?
443. What Is Function Overriding?
444. Why Use Super And This Keyword In Java?
445. What Is Inheritance?
446. Describe The Types Of Inheritance.
447. What Is Scope? Describe The Types Of Scope.
448. Types Of Access Specifiers?
449. What Is Encapsulation?
450. What Is Abstraction?
451. Is There Any Difference Between A = A + B And A += B Expressions?
452. Can We Use Multiple Main Methods In Multiple Classes?
453. Does Java Allow You To Override A Private Or Static Method?
454. What Happens When You Put A Key Object In A Hashmap That Is
Already Present?
455. How Can You Do Multiple Inheritances In Java?
456. How Can You Access A Non-static Variable From The Static Context?
457. Can You Create An Immutable Object That Contains A Mutable Object?
458. How Can You Convert An Array Of Bytes To a String?
459. What Is The Difference Between StringBuffer And StringBuilder?
460. Out Of An Int And Integer, Which One Takes More Memory?
461. Can We Use String In The Switch Case Statement In Java?
462. Can We Use Multiple Main Methods In the Same Class?
463. When Creating An Abstract Class, Is It A Good Idea To Call Abstract
Methods Inside Its Constructor?
464. How Can You Do Constructor Chaining In Java?
465. Can a functional interface extend/inherit another interface?
466. What is the default method, and why is it required?
467. What are static methods in Interfaces?
468. What is the basic structure/syntax of a lambda expression?
469. What are the features of a lambda expression?
470. Why is Java a platform-independent language?
471. Why is Java not a pure object-oriented language?
472. What do you understand by an instance variable and a local variable?
473. What are the default values assigned to variables and instances in
java?
474. What do you mean by data encapsulation?
475. Can you tell the difference between equals() method and equality
operator (==) in Java?
476. How is an infinite loop declared in Java?
477. Can the main method be Overloaded?
478. Do final, finally and finalize keywords have the same function?
479. Is it possible that the ‘finally’ block will not be executed? If yes then
list the case.
480. Why is the main method static in Java?
481. Can the static methods be overridden?
482. What part of memory Stack or Heap is cleaned in the garbage
collection process?
483. Apart from the security aspect, what are the reasons behind making
strings immutable in Java?
484. What is a singleton class in Java? And How to implement a singleton
class?
485. How would you differentiate between a String, StringBuffer, and a
StringBuilder?
Ans:
486. What is a Comparator in java?
487. What makes a HashSet different from a TreeSet?
488. Why is the character array preferred over string for storing
confidential information?
489. What do we get in the JDK file?
490. What are the differences between JVM, JRE, and JDK in Java?
Ans: JVM (Java Virtual Machine):
The JVM is an abstract machine that provides a runtime environment for
executing Java bytecode.
It doesn’t physically exist; instead, it’s a specification.
Key points:
Executes Java bytecode.
Supports other languages compiled to Java bytecode.
Available for various hardware and software platforms.
Responsible for loading, verifying, and executing code.
JRE (Java Runtime Environment):
The JRE is the implementation of the JVM.
It includes:
Java class libraries (used by Java programs).
Other files required for runtime execution.
Key points:
Physically exists.
Provides the runtime environment for Java applications.
Used for executing Java programs (not development).
JDK (Java Development Kit):
The JDK is a software development environment for creating Java applications
and applets.
It includes:
JRE: Provides the runtime environment.
Development tools (compiler, archiver, documentation generator, etc.).
Key points:
Physically exists.
Used for both development and execution.
Contains a private JVM for development purposes.
In summary:
JVM: Abstract machine for executing bytecode.
JRE: Implementation of the JVM for runtime execution.
JDK: Development environment with JRE and development tools.
491. What are the differences between HashMap and HashTable in Java?
Ans:
Traversing Elements:
HashMap:
Traversed using Iterator.
Iterator is fail-fast (detects concurrent modifications).
Hashtable:
Traversed using Enumerator and Iterator.
Enumerator is not fail-fast.
Inheritance:
HashMap:
Inherits from AbstractMap class.
Hashtable:
Inherits from Dictionary class.
492. What are the differences between the constructor and method of a
class in Java?
Ans:
493. Java works as a “pass by value” or “pass by reference” phenomenon?
494. Which among String or String Buffer should be preferred when there
are a lot of updates required to be done in the data?
495. What happens if the static modifier is not included in the main
method signature in Java?
Ans:I f you remove the static modifier from the main method, the program
will still compile successfully.
However, at runtime, the Java Virtual Machine (JVM) expects the main
method to be static.
If the static modifier is missing, the JVM will not recognize it as the entry
point, and your program won’t execute as expected.
Why Is main Method Static?:
The main method must be static because:
It is called by the JVM before any objects are created.
Non-static methods require an instance of the class, which is not available
during JVM startup.
By making it static, the JVM can load the class into memory and invoke the
main method without creating an object.
496. What happens if there are multiple main methods inside one class in
Java?
Ans: program consist of two main methods but throws out an error that the
Main method is not found in class, please define the main method as public
static void main(String[] args)”. Only the main() method with a single string
array as a parameter is considered as an entry point of the program. JVM only
looks for main method with string array as an argument. In order for other
main methods to execute, you need to call them from inside public static void
main(String[ ] args)
497. How does an exception propagate in the code?
Ans: when an exception happens, Propagation is a process in which the
exception is being dropped from to the top to the bottom of the stack. If not
caught once, the exception again drops down to the previous method and so on
until it gets caught or until it reach the very bottom of the call stack. This is
called exception propagation and this happens in case of Unchecked Exceptions.
In the example below, exception occurs in m() method where it is not handled,
so it is propagated to previous n() method where it is not handled, again it is
propagated to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method,
p() method, n() method or m() method.
Note : By default, Unchecked Exceptions are forwarded in calling chain
(propagated).
Unlike Unchecked Exceptions, the propagation of exception does not happen in
case of Checked Exception and its mandatory to use throw keyword here. Only
unchecked exceptions are propagated. Checked exceptions throw compilation
error.
498. How do exceptions affect the program if it doesn’t handle them?
Ans: When an exception occurred, if you don’t handle it, the program
terminates abruptly and the code past the line that caused the exception will not
get executed
499. Is it mandatory for a catch block to be followed after a try block?
Ans: No, it is not mandatory to have a catch block immediately following a try
block in Java.
try-catch Block:
A try block is used to enclose code that might throw an exception.
If an exception occurs within the try block, control transfers to the nearest
matching catch block.
The catch block handles the exception by specifying the type of exception it can
catch.
Optional catch Block:
You can have a try block without a corresponding catch block.
In such cases, you typically include a finally block (if needed) to perform cleanup
tasks.
The finally block executes whether an exception occurs or not.
try {
// Code that might throw an exception
// ...
} finally {
// Cleanup code (executes regardless of exceptions)
// ...
}
The order of blocks can be:
try → catch → finally
try → finally
try → catch
If you handle exceptions elsewhere (e.g., in a higher-level method), you might
omit the catch block.
If you only need cleanup (e.g., closing resources), use a finally block without a
catch block.
500. Will the finallly block get executed when the return statement is
written at the end of the try block and catch block as shown below?
Ans: finally Block Execution:
The finally block is always executed, regardless of whether an exception occurs
or not.
It runs even if there is a return statement in the try or catch block.
Scenario 1: return in try Block:
If a return statement is reached in the try block:
Control transfers to the finally block.
The finally block executes.
The function eventually returns normally (not as an exception).
The value returned is determined by the finally block (if it has a return
statement).
Scenario 2: return in catch Block:
If an exception occurs and the code reaches a return statement in the catch block:
Control transfers to the finally block.
The finally block executes.
The function eventually returns normally (not as an exception).
Again, the value returned is determined by the finally block (if it has a return
statement).
Example:
public class FinallyExample {
public static void main(String[] args) {
[Link](getValue());
}
private static int getValue() {
try {
int a = 10 / 0; // Throws an exception
return 4;
} catch (Exception e) {
return 45;
} finally {
return 34; // This value will be returned
}
}
}
Output:
When you run the above example, it prints 34 because the finally block has the
final say.
Important Note:
If you return from the finally block, it overrides any previous return statements
from the try or catch block.
Be cautious when using return in the finally block, as it can suppress exceptions.
In summary, the finally block ensures cleanup and executes even after return
statements in other blocks.
501. Can you call a constructor of a class inside another constructor?
Ans: a constructor is called from another constructor in the same class this
process is known as constructor chaining.
It occurs through inheritance.
When we create an instance of a derived class, all the constructors of the
inherited class (base class) are first invoked, after that the constructor of the
calling class (derived class) is invoked.
We can achieve constructor chaining in two ways:
Within the same class: If the constructors belong to the same class, we use this
From the base class: If the constructor belongs to different classes (parent and
child classes), we use the super keyword to call the constructor from the base
class.
502. Why does the java array index start with 0?
Ans:
503. Why is the remove method faster in the linked list than in an array?
Ans: Whenever we remove an element, internally, the array is traversed
and the memory bits are shifted. Manipulating LinkedList takes less time
compared to ArrayList because, in a doubly-linked list, there is no concept
of shifting the memory bits
Linked List:
In a linked list, each element (node) contains a reference to the next element.
When removing an element from a linked list, you only need to update a few
pointers (references).
Specifically, if you have a reference to the node you want to remove, the removal
operation is O(1) (constant time).
No need to shift other elements or resize any internal data structure.
ArrayList (Array):
An ArrayList uses an internal array to store elements.
When removing an element from an ArrayList, several steps are involved:
Find the index of the element to remove (which may require linear search if the
index is not known).
Shift all subsequent elements one position to the left (to fill the gap left by the
removed element).
If the removal occurs at the end of the list, no shifting is needed.
However, if it’s in the middle or at the beginning, all subsequent elements must
be moved.
504. How does the size of ArrayList grow dynamically? And also state how
it is implemented internally.
Ans: ArrayList size increases dynamically because whenever the ArrayList
class requires to resize then it will create a new array of bigger size and copies
all the elements from the old array to the new array
Internal Implementation:
The backing data structure of an ArrayList is an array of Object classes.
The ArrayList class uses an internal array called elementData.
The initial capacity of an ArrayList is typically 10 elements.
If you create an empty ArrayList, it starts with this default capacity.
When you add the first element to the ArrayList, it expands the array to the
default capacity.
If you specify a custom initial capacity, that value is used instead.
505. What is the difference between ‘>>’ and ‘>>>’ operators in java?
Ans:
506. What are Composition and Aggregation? State the difference.
Ans:
Composition is a "belong-to" type of relationship in which one object is
logically related with other objects. It is also referred to as "has-a" relationship.
A classroom belongs to a school, or we can say a school has a classroom.
Composition is a strong type of "has-a" relationship because the containing
object is its owner. So, objects are tightly coupled, which means if we delete the
parent object, the child object will also get deleted with it.
Aggregation relationship is also a "has-a" relationship. The only difference
between Aggregation and Composition is that in Aggregation, objects are not
tightly coupled
A car comes with a wheel, and if we take off its wheels, the wheels will still exist.
But a car without wheels won't be as useful as a car with its wheels
507. How is the creation of a String using new() different from that of a
literal?
Ans: String Literal:
When you declare a String using a literal, such as:
String str = "GeeksForGeeks"
The compiler checks the String pool for an existing String with the same content
(“GeeksForGeeks”).
If an identical String already exists, the reference points to that existing object.
No new String object is created.
The intern() method is implicitly called on the literal.
String Object (Using new()):
When you create a String using the new operator, like this:
String str = new String("GeeksForGeeks");
A new String object is explicitly created in the heap memory.
Even if an identical String exists in the pool, a new object is constructed.
This approach is less efficient because it creates a new String every time it
is executed.
In summary:
Literal: Checks the pool and reuses existing String if available.
new(): Always creates a new String object in memory.
This approach is more efficient because it reuses existing String objects.
508. Is it possible to import the same class or package twice in Java and
what happens to it during runtime?
Ans: Yes, it is possible to import the same class or package multiple times in
Java. However, neither the compiler nor the JVM complains about it
Importing the Same Package:
You can import the same package multiple times in a Java class.
The compiler considers these additional import statements redundant.
Importing the Same Class:
Similarly, you can import the same class multiple times.
The JVM, however, loads the class only once, regardless of how many times you
import it.
This behavior ensures that there is no issue with importing the same class
repeatedly.
509. Will the finally block be executed if the code [Link](0) is written
at the end of the try block?
Ans: When [Link](0) is called in the try block, it immediately terminates
the program without allowing any further code execution. As a result, the finally
block is skipped. The finally block only executes if control leaves the try block
normally (i.e., without an exception or an explicit exit)
510. What do you understand by marker interfaces in Java?
Ans: An interface that does not contain methods, fields, and constants is
known as marker interface. In other words, an empty interface is known as
marker interface or tag interface. It delivers the run-time type information about
an object. It is the reason that the JVM and compiler have additional information
about an object. The Serializable and Cloneable interfaces are the example of
marker interface
Java marker interface are useful if we have information about the class and that
information never changes, in such cases, we use marker interface represent to
represent the same. Implementing an empty interface tells the compiler to do
some operations.
511. Why is it said that the length() method of the String class doesn’t
return accurate results?
Ans: the length() method gives the total number of characters present in
the string
Notes:
Yes, we can define multiple methods in a class with the same name but with
different types of parameters. Which method is to get invoked will depend
upon the parameters passed.
In the below example, we have defined three display methods with the same
name but with different parameters. Depending on the parameters, the
appropriate method will be called.