1.top500oops Java Interview Que
1.top500oops Java Interview Que
:- 220350320112
INTERVIEW_QUESTION
TOP 500+ QUESTIONS
→{DATE-26/08/2022
→DAY-FRIDAY
Java is a collection of objects. It was developed by Sun Microsystems. There are a lot of
applications, websites, and games that are developed using Java.
Q #2) What are the features of JAVA?
• OOP concepts
o Object-oriented
o Inheritance
o Encapsulation
o Polymorphism
o Abstraction
Answer: Java uses Just In Time compiler to enable high performance. It is used to convert
the instructions into bytecodes.
Q #6) What is meant by the Local variable and the Instance variable?
Answer:
Local variables are defined in the method and scope of the variables that exist inside the
method itself.
Instance variable is defined inside the class and outside the method and the scope of the
variables exists throughout the class.
Q #7) What is a Class?
Answer: All Java codes are defined in a Class. It has variables and methods.
Methods are the place where the exact business logic has to be done. It contains a set of
statements (or) instructions to satisfy the particular requirement.
Example:
Answer: An instance of a class is called an object. The object has state and behavior.
Whenever the JVM reads the “new()” keyword then it will create an instance of that class.
Example:
The above code creates the object for the Addition class.
• Inheritance
• Encapsulation
• Polymorphism
• Abstraction
• Interface
Answer: Inheritance means one class can extend to another class. So that the codes can be
reused from one class to another class. The existing class is known as the Super class whereas
the derived class is known as a sub class.
Example:
Super class:
public class Manupulation(){
}
Sub class:
public class Addition extends Manipulation(){
}
Inheritance is only applicable to the public and protected members only. Private members
can’t be inherited.
Example:
get A(){
}
set A(int a){
if(a>0){// Here condition is applied
.........
}
}
For encapsulation, we need to make all the instance variables private and create setter and
getter for those variables. Which in turn will force others to call the setters rather than access
the data directly.
A single object can refer to the super-class or sub-class depending on the reference type
which is called polymorphism.
Example:
Using the Manipulation reference type we can call the Addition class “add()” method. This
ability is known as Polymorphism. Polymorphism is applicable for overriding and not for
overloading.
Answer: Method overriding happens if the sub-class method satisfies the below
conditions with the Super-class method:
The key benefit of overriding is that the Sub-class can provide some specific information
about that sub-class type than the super-class.
Example:
addition.add() method calls the add() method in the Sub-class and not the parent class. So it
overrides the Super-class method and is known as Method Overriding.
Answer: Method overloading happens for different classes or within the same class.
For method overloading, sub-class method should satisfy the below conditions with the
Super-class method (or) methods in the same class itself:
Example:
}
Public static void main(String args[]){
Addition addition = new Addition();
addition.add();
}
}
Here the add() method has different parameters in the Addition class is overloaded in the
same class as with the super-class.
Answer: Multiple inheritances cannot be achieved in java. To overcome this problem the
Interface concept is introduced.
An interface is a template which has only method declarations and not the method
implementation.
Example:
• All the methods in the interface are internally public abstract void.
• All the variables in the interface are internally public static final that is constants.
• Classes can implement the interface and not extends.
• The class which implements the interface should provide an implementation for all
the methods declared in the interface.
Answer: We can create the Abstract class by using the “Abstract” keyword before the class
name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that
are a concrete class.
Abstract method:
The method which has only the declaration and not the implementation is called the abstract
method and it has the keyword called “abstract”. Declarations ends with a semicolon.
Example:
Answer: The Difference between Array and Array List can be understood from the
table below:
Array Array List
Size should be given at the time of array Size may not be required. It changes the
declaration. size dynamically.
Answer:
String: String variables are stored in a “constant string pool”. Once the string reference
changes the old value that exists in the “constant string pool”, it cannot be erased.
Example:
String Buffer:
• Here string values are stored in a stack. If the values are changed then the new value
replaces the older value.
• The string buffer is synchronized which is thread-safe.
• Performance is slower than the String Builder.
Example:
Once the name value has been changed to “pen” then the “book” is erased in the stack.
String Builder:
This is the same as String Buffer except for the String Builder which is not threaded safely
that is not synchronized. So obviously the performance is fast.
Public:
Public members are visible in the same package as well as the outside package that is for
other packages.
Public members of Class A are visible to Class B (same package) as well as Class C
(different packages).
Private:
Private members are visible in the same class only and not for the other classes in the same
package as well as classes in the outside packages.
Private members in class A are visible only in that class. It is invisible for class B as well as
class C.
Answer:
Default: Methods and variables declared in a class without any access specifiers are called
default.
Default members in Class A are visible to the other classes which are inside the package and
invisible to the classes which are outside the package.
Protected:
.
Protected is the same as Default but if a class extends then it is visible even if it is outside the
package.
Class A members are visible to Class B because it is inside the package. For Class C it is
invisible but if Class C extends Class A then the members are visible to Class C even if it is
outside the package.
Answer: The difference between HashMap and HashTable can be seen below:
HashMap HashTable
Methods are not synchronized Key methods are synchronized
Not thread safety Thread safety
Iterator is used to iterate the values Enumerator is used to iterate the values
Allows one null key and multiple null values Doesn’t allow anything that is null
Performance is high than HashTable Performance is slow
Answer: The difference between HashSet and TreeSet can be seen below:
HashSet TreeSet
Inserted elements are in random order Maintains the elements in the sorted order
Can able to store null objects Couldn’t store null objects
Performance is fast Performance is slow
Answer: The differences between Abstract Class and Interface are as follows:
Abstract Class:
• Abstract classes have a default constructor and it is called whenever the concrete
subclass is instantiated.
• It contains Abstract methods as well as Non-Abstract methods.
• The class which extends the Abstract class shouldn’t require the implementation of all
the methods, only Abstract methods need to be implemented in the concrete sub-class.
• Abstract class contains instance variables.
Interface:
Answer: Collection is a framework that is designed to store the objects and manipulate the
design to store the objects.
• Searching
• Sorting
• Manipulation
• Insertion
• Deletion
A group of objects is known as collections. All the classes and interfaces for collecting are
available in Java util package.
Q #25) What are all the Classes and Interfaces that are available in the collections?
Answer: Given below are the Classes and Interfaces that are available in Collections:
Interfaces:
• Collection
• List
• Set
• Map
• Sorted Set
• Sorted Map
• Queue
Classes:
• Lists:
• Array List
• Vector
• Linked List
Sets:
• Hash set
• Linked Hash Set
• Tree Set
Maps:
• Hash Map
• Hash Table
• TreeMap
• Linked Hashed Map
Queue:
• Priority Queue
Answer:
Ordered: It means the values that are stored in a collection is based on the values that are
added to the collection. So we can iterate the values from the collection in a specific order.
Sorted: Sorting mechanisms can be applied internally or externally so that the group of
objects sorted in a particular collection is based on the properties of the objects.
Answer: Values added to the list are based on the index position and it is ordered by index
position. Duplicates are allowed.
a) Array List:
Example:
From the output, Array List maintains the insertion order and it accepts the duplicates. But
it’s not sorted.
b) Vector:
Example:
Output:
[cherry,apple,banana,kiwi,apple]
Vector also maintains the insertion order and accepts the duplicates.
c) Linked List:
Example:
Output:
[ banana,cherry,apple,kiwi,banana]
Answer: Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method
is used to determine whether two objects are identical or not.
a) Hash Set:
Example:
Output:
Example:
Output:
It maintains the insertion order in which they have been added to the Set. Duplicates are not
allowed.
c) Tree Set:
Example:
Output:
TreeSet sorts the elements in ascending order. And duplicates are not allowed.
Answer: Map cares about the unique identifier. We can map a unique key to a specific value.
It is a key/value pair. We can search a value, based on the key. Like the set, the map also uses
the “equals ( )” method to determine whether two keys are the same or different.
a) Hash Map:
• Unordered and unsorted map.
• Hashmap is a good choice when we don’t care about the order.
• It allows one null key and multiple null values.
Example:
Output:
b) Hash Table:
Example:
Output:
Example:
Output:
d) TreeMap:
• Sorted Map.
• Like Tree set, we can construct a sort order with the constructor.
Example:
Output:
It is sorted in ascending order based on the key. Duplicate keys are not allowed.
Hence elements are ordered either naturally or according to the comparator. The elements
ordering represents their relative priority.
Answer: An Exception is a problem that can occur during the normal flow of execution. A
method can throw an exception when something wails at runtime. If that exception couldn’t
be handled, then the execution gets terminated before it completes the task.
If we handled the exception, then the normal flow gets continued. Exceptions are a subclass
of java.lang.Exception.
try{
//Risky codes are surrounded by this block
}catch(Exception e){
//Exceptions are caught in catch block
}
Answer: There are two types of Exceptions. They are explained below in detail.
a) Checked Exception:
These exceptions are checked by the compiler at the time of compilation. Classes that extend
Throwable class except Runtime exception and Error are called checked Exception.
Checked Exceptions must either declare the exception using throws keyword (or) surrounded
by appropriate try/catch.
b) Unchecked Exception:
These exceptions are not checked during the compile time by the compiler. The compiler
doesn’t force to handle these exceptions. It includes:
• Arithmetic Exception
• ArrayIndexOutOfBounds Exception
a) Using try/catch:
The risky code is surrounded by try block. If an exception occurs, then it is caught by the
catch block which is followed by the try block.
Example:
class Manipulation{
public static void main(String[] args){
add();
}
Public void add(){
try{
addition();
}catch(Exception e){
e.printStacktrace();
}
}
}
At the end of the method, we can declare the exception using throws keyword.
Example:
class Manipulation{
public static void main(String[] args){
add();
}
public void add() throws Exception{
addition();
}
}
• The normal flow of the execution won’t be terminated if an exception gets handled
• We can identify the problem by using catch declaration
a) try:
When a risky code is surrounded by a try block. An exception occurring in the try block is
caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any
one of the blocks is mandatory.
b) catch:
This is followed either by try block (or) catch block. This block gets executed regardless of
an exception. So generally clean up codes are provided here.
Answer: Exception is first thrown from the method which is at the top of the stack. If it
doesn’t catch, then it pops up the method and moves to the previous method and so on until
they are got.
Example:
From the above example, the stack looks like as shown below:
If an exception occurs in the addition() method is not caught, then it moves to the method
add(). Then it is moved to the main() method and then it will stop the flow of execution. It is
called Exception Propagation.
Answer:
Final variable: Once a variable is declared as final, then the value of the variable could not
be changed. It is like a constant.
Example:
Final class: If a class is declared as final, then the class couldn’t be subclassed. No class can
extend the final class.
Q #38) What is a Thread?
Answer: In Java, the flow of execution is called Thread. Every java program has at least one
thread called the main thread, the main thread is created by JVM. The user can define their
own threads by extending the Thread class (or) by implementing the Runnable interface.
Threads are executed concurrently.
Example:
a) Extend Thread class: Extending a Thread class and override the run method. The thread
is available in java.lang.thread.
Example:
The disadvantage of using a thread class is that we cannot extend any other classes because
we have already extended the thread class. We can overload the run () method in our class.
Example:
Answer: Join () method is used to join one thread with the end of the currently running
thread.
Example:
Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task, then
only the main thread starts the execution.
It is a non-static method. The Join () method has an overloaded version. So we can mention
the time duration in join () method also “.s”.
Q #41) What does the yield method of the Thread class do?
Answer: A yield () method moves the currently running thread to a runnable state and allows
the other threads for execution. So that equal priority threads have a chance to run. It is a
static method. It doesn’t release any lock.
Yield () method moves the thread back to the Runnable state only, and not the thread to sleep
(), wait () (or) block.
Example:
Answer: wait () method is used to make the thread to wait in the waiting pool. When the
wait () method is executed during a thread execution then immediately the thread gives up the
lock on the object and goes to the waiting pool. Wait () method tells the thread to wait for a
given amount of time.
Then the thread will wake up after notify () (or) notify all () method is called.
Wait() and the other above-mentioned methods do not give the lock on the object
immediately until the currently executing thread completes the synchronized code. It is
mostly used in synchronization.
Example:
Answer: The differences between notify() method and notifyAll() method are enlisted
below:
notify() notifyAll()
This method is used to send a signal to wake up This method sends the signal to wake up all
a single thread in the waiting pool. the threads in a waiting spool.
Q #44) How to stop a thread in java? Explain about sleep () method in a thread?
• Sleeping
• Waiting
• Blocked
Sleep: Sleep () method is used to sleep the currently executing thread for the given amount of
time. Once the thread is wake up it can move to the runnable state. So sleep () method is used
to delay the execution for some period.
It is a static method.
Example:
Answer: If we need our class to extend some other classes other than the thread then we can
go with the runnable interface because in java we can extend only one class.
If we are not going to extend any class then we can extend the thread class.
Answer: Multiple threads are executed simultaneously. Each thread starts its own stack
based on the flow (or) priority of the threads.
Example Program:
On the 1st line execution, JVM calls the main method and the main thread stack looks as
shown below.
Once the execution reaches, t.start () line then a new thread is created and the new stack for
the thread is also created. Now JVM switches to the new thread and the main thread are back
to the runnable state.
Now, the user thread executed the code inside the run() method.
Once the run() method has completed, then JVM switches back to the main thread and the
user thread has completed the task and the stack was disappeared.
JVM switches between each thread until both the threads are completed. This is called Multi-
threading.
• New
• Runnable
• Running
• Non-runnable (Blocked)
• Terminated
• New: In New state, a Thread instance has been created but start () method is not yet
invoked. Now the thread is not considered alive.
• Runnable: The Thread is in the runnable state after the invocation of the start ()
method, but before the run () method is invoked. But a thread can also return to the
runnable state from waiting/sleeping. In this state, the thread is considered alive.
• Running: The thread is in a running state after it calls the run () method. Now the
thread begins the execution.
• Non-Runnable(Blocked): The thread is alive but it is not eligible to run. It is not in
the runnable state but also, it will return to the runnable state after some time.
Example: wait, sleep, block.
• Terminated: Once the run method is completed then it is terminated. Now the thread
is not alive.
Answer: Synchronization makes only one thread to access a block of code at a time. If
multiple threads accesses the block of code, then there is a chance for inaccurate results at the
end. To avoid this issue, we can provide synchronization for the sensitive block of codes.
The synchronized keyword means that a thread needs a key in order to access the
synchronized code.
Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can
access a synchronized method only if the thread can get the key to the objects to lock.
For this, we use the “Synchronized” keyword.
Example:
Ans: Synchronization is not recommended to implement all the methods. Because if one
thread accesses the synchronized code then the next thread should have to wait. So it makes a
slow performance on the other end.
Answer: Converting a file into a byte stream is known as Serialization. The objects in the file
are converted to bytes for security purposes. For this, we need to implement a
java.io.Serializable interface. It has no method to define.
Variables that are marked as transient will not be a part of the serialization. So we can skip
the serialization for the variables in the file by using a transient keyword.
Answer: Transient variables are not part of the serialization process. During deserialization,
the values of the transient variables are set to the default value. It is not used with static
variables.
Example:
Q #53) Which methods are used during the Serialization and Deserialization process?
Answer: Volatile variable values are always read from the main memory and not from
thread’s cache memory. This is used mainly during synchronization. It is applicable only for
variables.
Example:
Answer: These are the differences between serialization and deserialization in java:
Serialization Deserialization
Deserialization is the opposite process of
Serialization is the process which is used
serialization where we can get the objects back
to convert the objects into byte stream
from the byte stream.
An object is serialized by writing it an An object is deserialized by reading it from an
ObjectOutputStream. ObjectInputStream.
Answer: Whenever an object is Serialized, the object is stamped with a version ID number
for the object class. This ID is called the SerialVersionUID. This is used during
deserialization to verify that the sender and receiver that are compatible with the
Serialization.
Conclusion
These are some of the core JAVA interview questions that cover both the basic and advanced
Java concepts for programming as well as developer interview, and these are ones which
have been answered by our JAVA experts.
I hope that this tutorial will give you a great insight into JAVA core coding concepts in detail.
The explanations given above will really enrich your knowledge and increase your
understanding of JAVA programming.
It stands for Java It stands for Java Runtime It stands for Java Virtual
Development Kit. Environment. Machine.
It is an abstract machine. It is a
It is the tool necessary to JRE refers to a runtime
specification that provides a run-
compile, document and environment in which Java
time environment in which Java
package Java programs. bytecode can be executed.
bytecode can be executed.
main() in Java is the entry point for any Java program. It is always written as public static
void main(String[] args).
• public: Public is an access modifier, which is used to specify who can access this method.
Public means that this Method will be accessible by any Class.
• static: It is a keyword in java which identifies it is class-based. main() is made static in Java so
that it can be accessed without creating the instance of a Class. In case, main is not made static
then the compiler will throw an error as main() is called by the JVM before any objects are
made and only static methods can be directly invoked via the class.
• void: It is the return type of the method. Void defines the method which will not return any
value.
• main: It is the name of the method which is searched by JVM as a starting point for an
application with a particular signature only. It is the method where the main execution occurs.
• String args[]: It is the parameter passed to the main method.
Java is not 100% Object-oriented because it makes use of eight primitive data types such as
boolean, byte, char, int, float, double, long, short which are not objects.
Wrapper classes convert the Java primitives into the reference types (objects). Every primitive
data type has a class dedicated to it. These are known as wrapper classes because they “wrap”
the primitive data type into an object of that class. Refer to the below image which displays
different primitive type, wrapper class and constructor argument.
In Java, constructor refers to a block of code which is used to initialize an object. It must have
the same name as that of the class. Also, it has no return type and it is automatically called
when an object is created.
1. Default Constructor: In Java, a default constructor is the one which does not take any inputs.
In other words, default constructors are the no argument constructors which will be created
by default in case you no other constructor is defined by the user. Its main purpose is to
initialize the instance variables with the default values. Also, it is majorly used for object
creation.
2. Parameterized Constructor: The parameterized constructor in Java, is the constructor which
is capable of initializing the instance variables with the provided values. In other words, the
constructors which take the arguments are called parameterized constructors.
Q63. What is singleton class in Java and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given time, in one
JVM. A class can be made singleton by making its constructor private.
Q64. What is the difference between Array list and vector in Java?
ArrayList Vector
Array List can only use Iterator for traversing Vector can use both Enumeration and Iterator for
an Array List. traversing.
Equals() method is defined in Object class in Java and used for checking equality of two
objects defined by business logic.
In Java, the super keyword is a reference variable that refers to an immediate parent class
object.
When you create a subclass instance, you’re also creating an instance of the parent class, which is
referenced to by the super reference variable.
HashSet TreeSet
It permits the null object. It does not allow the null object.
Q68. What are the differences between HashMap and HashTable in Java?
HashMap Hashtable
It permits one null key and multiple null values. It does not permit any null key or value.
is a new class introduced in JDK 1.2. It was present in earlier versions of java as well.
It is faster. It is slower.
It uses fail fast iterator. It uses an enumerator which is not fail fast.
Reflection is a runtime API for inspecting and changing the behavior of methods, classes, and
interfaces. Java Reflection is a powerful tool that can be really beneficial. Java Reflection
allows you to analyze classes, interfaces, fields, and methods during runtime without
knowing what they are called at compile time. Reflection can also be used to create new
objects, call methods, and get/set field values. External, user-defined classes can be used by
creating instances of extensibility objects with their fully-qualified names. Debuggers can
also use reflection to examine private members of classes.
The NonSerialized attribute can be used to prevent member variables from being serialized.
You should also make an object that potentially contains security-sensitive data
nonserializable if possible. Apply the NonSerialized attribute to certain fields that store
sensitive data if the object must be serialized. If you don’t exclude these fields from
serialisation, the data they store will be visible to any programmes with serialization
permission.
Yes, we can call a constructor of a class inside another constructor. This is also called as
constructor chaining. Constructor chaining can be done in 2 ways-
1. Within the same class: For constructors in the same class, the this() keyword can be used.
2. From the base class: The super() keyword is used to call the constructor from the base class.
The constructor chaining follows the process of inheritance. The constructor of the sub class
first calls the constructor of the super class. Due to this, the creation of sub class’s object
starts with the initialization of the data members of the super class. The constructor chaining
works similarly with any number of classes. Every constructor keeps calling the chain till the
top of the chain.
Q72. Contiguous memory locations are usually used for storing actual values in an
array but not in ArrayList. Explain.
An array generally contains elements of the primitive data types such as int, float, etc. In such
cases, the array directly stores these elements at contiguous memory locations. While an
ArrayList does not contain primitive data types. An arrayList contains the reference of the
objects at different memory locations instead of the object itself. That is why the objects are
not stored at contiguous memory locations.
Q73. How is the creation of a String using new() different from that of a literal?
When we create a string using new(), a new object is created. Whereas, if we create a string
using the string literal syntax, it may return an already existing object with the same name.
Q74. Why is synchronization necessary? Explain with the help of a relevant example.
Java allows multiple threads to execute. They may be accessing the same variable or object.
Synchronization helps to execute threads one after another.
It is important as it helps to execute all concurrent threads while being in sync. It prevents
memory consistency errors due to access to shared memory. An example of synchronization
code is-
2{
3a++;
4}
As we have synchronized this function, this thread can only use the object after the previous
thread has used it.
Double Brace Initialization is a Java term that refers to the combination of two independent
processes. There are two braces used in this. The first brace creates an anonymous inner
class. The second brace is an initialization block. When these both are used together, it is
known as Double Brace Initialization. The inner class has a reference to the enclosing outer
class, generally using the ‘this’ pointer. It is used to do both creation and initialization in a
single statement. It is generally used to initialize collections. It reduces the code and also
makes it more readable.
Q76. Why is it said that the length() method of String class doesn’t return accurate
results?
The length() method of String class doesn’t return accurate results because
it simply takes into account the number of characters within in the String. In other words,
code points outside of the BMP (Basic Multilingual Plane), that is, code points having a value
of U+10000 or above, will be ignored.
The reason for this is historical. One of Java’s original goals was to consider all text as
Unicode; yet, Unicode did not define code points outside of the BMP at the time. It was too
late to modify char by the time Unicode specified such code points.
Q77. What are the differences between Heap and Stack Memory in Java?
Stack memory is used only by one Heap memory is used by all the parts of
Memory
thread of execution. the application.
Stack memory can’t be accessed by Objects stored in the heap are globally
Access
other threads. accessible.
Packages in Java, are the collection of related classes and interfaces which are bundled
together. By using packages, developers can easily modularize the code and optimize its reuse.
Also, the code within the packages can be imported by other classes and reused. Below I have
listed down a few of its advantages:
Java doesn’t use pointers because they are unsafe and increases the complexity of the program.
Since, Java is known for its simplicity of code, adding the concept of pointers will be
contradicting. Moreover, since JVM is responsible for implicit memory allocation, thus in
order to avoid direct access to memory by the user, pointers are discouraged in Java.
JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the Java
bytecode into instructions that are sent directly to the processor. By default, the JIT compiler
is enabled in Java and is activated whenever a Java method is invoked. The JIT compiler then
compiles the bytecode of the invoked method into native machine code, compiling it “just in
time” to execute. Once the method has been compiled, the JVM summons the compiled code
of that method directly rather than interpreting it. This is why it is often responsible for the
performance optimization of Java applications at the run time.
In Java, access modifiers are special keywords which are used to restrict the access of a class,
constructor, data member and method in another class. Java supports four types of access
modifiers:
1. Default
2. Private
3. Protected
4. Public
Modifier Default Private Protected Public
A class in Java is a blueprint which includes all your data. A class contains fields (variables)
and methods to describe the behavior of an object. Let’s have a look at the syntax of a class.
1class Abc {
3methods}
An object is a real-world entity that has a state and behavior. An object has three characteristics:
1. State
2. Behavior
3. Identity
1. Inheritance: Inheritance is a process where one class acquires the properties of another.
2. Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code
together as a single unit.
3. Abstraction: Abstraction is the methodology of hiding the implementation details from the
user and only providing the functionality to the users.
4. Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple
forms.
Q86. What is the difference between a local variable and an instance variable?
In Java, a local variable is typically used inside a method, constructor, or a block and has only
local scope. Thus, this variable can be used only within the scope of a block. The best benefit
of having a local variable is that other methods in the class won’t be even aware of that variable.
Example
1if(x > 100)
2{
4}
Whereas, an instance variable in Java, is a variable which is bounded to its object itself. These
variables are declared within a class, but outside a method. Every object of that class will create
it’s own copy of the variable while using it. Thus, any changes made to the variable won’t
reflect in any other instances of that class and will be bound to that particular instance only.
1class Test{
4}
Methods Constructors
5. Method name may or may not be same 5. Constructor name must always be the same as the
as class name class name
In case you are facing any challenges with these Core Java interview questions, please
comment on your problems in the section below.
final is a special keyword in Java that is used as a non-access modifier. A final variable can be
used in different contexts such as:
• final variable
When the final keyword is used with a variable then its value can’t be changed once assigned.
In case the no value has been assigned to the final variable then using only the class constructor
a value can be assigned to it.
• final method
When a method is declared final then it can’t be overridden by the inheriting class.
• final class
When a class is declared as final in Java, it can’t be extended by any subclass class but it can
extend other class.
break continue
2. It causes the switch or loop statements to 2. It doesn’t terminate the loop but causes the loop
terminate the moment it is executed to jump to the next iteration
3. It terminates the innermost enclosing loop 3. A continue within a loop nested with a switch will
or switch immediately cause the next loop iteration to execute
Example break:
for (int i = 0; i < 5; i++)</div>
1
<div>
2<pre>{
3if (i == 3)
{
4
break;
5
}
6
System.out.println(i);
7
}
8
Example continue:
1
for (int i = 0; i < 5; i++)
2{
3if(i == 2)
4{
5continue;
6}
System.out.println(i);
7
}
8
An infinite loop is an instruction sequence in Java that loops endlessly when a functional exit
isn’t met. This type of loop can be the result of a programming error or may also be a
deliberate action based on the application behavior. An infinite loop will terminate
automatically once the application exits.
For example:
7}
8
In Java, super() and this(), both are special keywords that are used to call the constructor.
this() super()
2. Used to call the default constructor of the 2. Used to call the default constructor of the
same class parent/base class
3. Used to access methods of the current class 3. Used to access methods of the base class
4. Used for pointing the current class instance 4. Used for pointing the superclass instance
5. Must be the first line of a block 5. Must be the first line of a block
Java String pool refers to a collection of Strings which are stored in heap memory. In this,
whenever a new object is created, String pool first checks whether the object is already present
in the pool or not. If it is present, then the same reference is returned to the variable else new
object will be created in the String pool and the respective reference will be returned.
1. The static keyword must be used before the method 1. No need to use the static keyword before
name the method name
Double Brace Initialization is a Java term that refers to the combination of two independent
processes. There are two braces used in this. The first brace creates an anonymous inner
class. The second brace is an initialization block. When these both are used together, it is
known as Double Brace Initialisation. The inner class has a reference to the enclosing outer
class, genertally using the ‘this’ pointer. It is used to do both creation and initialization in a
single statement. It is generally used to initialize collections. It reduces the code and also
makes it more readable.
In Java, constructor chaining is the process of calling one constructor from another with respect
to the current object. Constructor chaining is possible only through legacy where a subclass
constructor is responsible for invoking the superclass’ constructor first. There could be any
number of classes in the constructor chain. Constructor chaining can be achieved in two ways:
If you think this article on Java Interview Questions is helpful, you can check out Edureka’s Java
Training in Chennai as well.
1. Bootstrap ClassLoader
2. Extension ClassLoader
3. System/Application ClassLoader
In Java, string objects are immutable in nature which simply means once the String object is
created its state cannot be modified. Whenever you try to update the value of that object instead
of updating the values of that particular object, Java creates a new string object. Java String
objects are immutable as String objects are generally cached in the String pool. Since String
literals are usually shared between multiple clients, action from one client might affect the rest.
It enhances security, caching, synchronization, and performance of the application.
Array ArrayList
Cannot contain values of different data types Can contain values of different data types.
Need to specify the index in order to add data No need to specify the index
Arrays can contain primitive data types as Arraylists can contain only objects, no primitive
well as objects data types are allowed
In Java, Map is an interface of Util package which maps unique keys to values. The Map
interface is not a subset of the main Collection interface and thus it behaves little different from
the other collection types. Below are a few of the characteristics of Map interface:
Q101. What is collection class in Java? List down its methods and interfaces.
In Java, the collection is a framework that acts as an architecture for storing and manipulating
a group of objects. Using Collections you can perform various tasks like searching, sorting,
insertion, manipulation, deletion, etc. Java collection framework includes the following:
• Interfaces
• Classes
• Methods
The below image shows the complete hierarchy of the Java Collection.
1 class Car {
void run()
2
{
3
System.out.println(“car is running”);
4
}
5
}
6 class Audi extends Car {
7 void run()
8 {
17
Abstraction refers to the quality of dealing with ideas rather than events. It basically deals with
hiding the details and showing the essential things to the user. Thus you can say that abstraction
in Java is the process of hiding the implementation details from the user and revealing only the
functionality to them. Abstraction can be achieved in two ways:
An interface in Java is a blueprint of a class or you can say it is a collection of abstract methods
and static constants. In an interface, each method is public and abstract but it does not contain
any constructor. Thus, interface basically is a group of related methods with empty bodies.
Example:
An abstract class can have instance variables An Interface cannot have instance variables
Inheritance in Java is the concept where the properties of one class can be inherited by the
other. It helps to reuse the code and establish a relationship between different classes.
Inheritance is performed between two types of classes:
A class which inherits the properties is known as Child Class whereas a class whose properties
are inherited is known as Parent class.
1. Single Inheritance: In single inheritance, one class inherits the properties of another i.e there
will be only one parent as well as one child class.
2. Multilevel Inheritance: When a class is derived from a class which is also derived
from another class, i.e. a class having more than one parent class but at different levels,
such type of inheritance is called Multilevel Inheritance.
3. Hierarchical Inheritance: When a class has more than one child classes (subclasses)
or in other words, more than one child classes have the same parent class, then such
kind of inheritance is known as hierarchical.
4. Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of
inheritance.
Method Overloading :
• In Method Overloading, Methods of the same class shares the same name but each method
must have a different number of parameters or parameters having different types and order.
• Method Overloading is to “add” or “extend” more to the method’s behavior.
• It is a compile-time polymorphism.
• The methods must have a different signature.
• It may or may not need inheritance in Method Overloading.
Let’s take a look at the example below to understand it better.
1
class Adder {
2
Static int add(int a, int b)
3
{
4
return a+b;
5 }
7 {
8 return a+b;
9 }
public static void main(String args[])
10
{
11
System.out.println(Adder.add(11,11));
12
System.out.println(Adder.add(12.3,12.6));
13
}}
14
Method Overriding:
• In Method Overriding, the subclass has the same method with the same name and exactly the
same number and type of parameters and same return type as a superclass.
• Method Overriding is to “Change” existing behavior of the method.
• It is a run time polymorphism.
• The methods must have the same signature.
• It always requires inheritance in Method Overriding.
1 class Car {
2 void run(){
System.out.println(“car is running”);
3
}
4
Class Audi extends Car{
5
void run()
6
{
7 System.out.prinltn("Audi is running safely with 100km");
8 }
15
You cannot override a private or static method in Java. If you create a similar method with the
same return type and same method arguments in child class then it will hide the superclass
method; this is known as method hiding. Similarly, you cannot override a private method in
subclass because it’s not accessible there. What you can do is create another private method
with the same name in the child class. Let’s take a look at the example below to understand it
better.
class Base {
1
private static void display() {
2
System.out.println("Static or class method from Base");
3 }
6 }
15{
20
21
22
The problem with multiple inheritance is that if multiple parent classes have the same method
name, then at runtime it becomes difficult for the compiler to decide which method to execute
from the child class.
Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred to as
Diamond Problem.
In case you are facing any challenges with these java interview questions, please comment on
your problems in the section below.
Encapsulation is a mechanism where you bind your data(variables) and code(methods) together
as a single unit. Here, the data is hidden from the outer world and can be accessed only via
current class methods. This helps in protecting the data from any unnecessary modification. We
can achieve encapsulation in Java by:
Association is a relationship where all object have their own lifecycle and there is no owner.
Let’s take the example of Teacher and Student. Multiple students can associate with a single
teacher and a single student can associate with multiple teachers but there is no ownership
between the objects and both have their own lifecycle. These relationships can be one to one,
one to many, many to one and many to many.
Q114. What do you mean by aggregation?
An aggregation is a specialized form of Association where all object has their own lifecycle
but there is ownership and child object can not belong to another parent object. Let’s take an
example of Department and teacher. A single teacher can not belong to multiple departments,
but if we delete the department teacher object will not destroy.
Composition is again a specialized form of Aggregation and we can call this as a “death”
relationship. It is a strong type of Aggregation. Child object does not have their lifecycle and
if parent object deletes all child object will also be deleted. Let’s take again an example of a
relationship between House and rooms. House can contain multiple rooms there is no
independent life of room and any room can not belongs to two different houses if we delete the
house room will automatically delete.
A Marker interface can be defined as the interface having no data member and member
functions. In simpler terms, an empty interface is called the Marker interface. The most
common examples of Marker interface in Java are Serializable, Cloneable etc. The marker
interface can be declared as follows.
2}
Object cloning in Java is the process of creating an exact copy of an object. It basically means
the ability to create an object with a similar state as the original object. To achieve this, Java
provides a method clone() to make use of this functionality. This method creates a new instance
of the class of the current object and then initializes all its fields with the exact same contents
of corresponding fields. To object clone(), the marker interface java.lang.Cloneable must be
implemented to avoid any runtime exceptions. One thing you must note is Object clone() is a
protected method, thus you need to override it.
Copy constructor is a member function that is used to initialize an object using another object
of the same class. Though there is no need for copy constructor in Java since all objects are
passed by reference. Moreover, Java does not even support automatic pass-by-value.
5 {
6 i=k;
7 }
In case you are facing any challenges with these java interview questions, please comment on
your problems in the section below. Apart from this Java Interview Questions Blog, if you want
to get trained from professionals on this technology, you can opt for a structured training from
edureka!
Java language was developed in such a way that it does not depend on any hardware or
software due to the fact that the compiler compiles the code and then converts it to platform-
independent byte code which can be run on multiple systems.
• The only condition to run that byte code is for the machine to have a runtime environment
(JRE) installed in it
Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and
hence it is not a pure object oriented language.
3. Difference between Heap and Stack Memory in java. And how java utilizes
this.
Stack memory is the portion of memory that was assigned to every individual program. And
it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java
program but it will be available for use by the java program when it is required, mostly
during the runtime of the program.
• When we write a java program then all the variables, methods, etc are stored in the stack
memory.
• And when we create any object in the java program then that object was created in the heap
memory. And it was referenced from the stack memory.
class Main {
public void printArray(int[] array){
for(int i : array)
System.out.println(i);
}
public static void main(String args[]) {
int[] array = new int[10];
printArray(array);
}
}
For this java program. The stack and heap memory occupied by java is -
Main and PrintArray is the method that will be available in the stack area and as well as the
variables declared that will also be in the stack area.
And the Object (Integer Array of size 10) we have created, will be available in the Heap area
because that space will be allocated to the program during runtime.
4. Can java be said to be the complete object-oriented programming
language?
It is not wrong if we claim that java is the complete object-oriented programming language.
Because Everything in Java is under the classes. And we can access that by creating the
objects.
But also if we say that java is not a completely object-oriented programming language
because it has the support of primitive data types like int, float, char, boolean, double, etc.
6. Pointers are used in C/ C++. Why does Java not make use of pointers?
Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on
code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also
cause potential errors. Moreover, security is also compromised if pointers are used because
the users can directly access memory with the help of pointers.
Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover,
the usage of pointers can make the procedure of garbage collection quite slow and erroneous.
Java makes use of references as these cannot be manipulated, unlike pointers.
Instance variables are those variables that are accessible by all the methods in the class.
They are declared outside the methods and inside the class. These variables describe the
properties of an object and remain bound to it at any cost.
All the objects of the class will have their copy of the variables for utilization. If any
modification is done on these variables, then only that instance will be impacted by it, and all
other class instances continue to remain unaffected.
Example:
class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}
Local variables are those variables present within a block, function, or constructor and can
be accessed only inside them. The utilization of the variable is restricted to the block scope.
Whenever a local variable is declared inside a method, the other class methods don’t have
any knowledge about the local variable.
Example:
• There are no default values assigned to the variables in java. We need to initialize the value
before using it. Otherwise, it will throw a compilation error of (Variable might not be
initialized).
• But for instance, if we create the object, then the default value will be initialized by the
default constructor depending on the data type.
• If it is a reference, then it will be assigned to null.
• If it is numeric, then it will assign to 0.
• If it is a boolean, then it will be assigned to false. Etc.
• JIT stands for Just-In-Time and it is used for improving the performance during run time. It
does the task of compiling parts of byte code having similar functionality at the same time
thereby reducing the amount of compilation time for the code to run.
• The compiler is nothing but a translator of source code to machine-executable code. But
what is special about the JIT compiler? Let us see how it works:
o First, the Java source code (.java) conversion to byte code (.class) occurs with the
help of the javac compiler.
o Then, the .class files are loaded at run time by JVM and with the help of an
interpreter, these are converted to machine understandable code.
o JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the
method calls in the .class files and compiles them to get more efficient and native
code. It also ensures that the prioritized method calls are optimized.
o Once the above step is done, the JVM executes the optimized code directly instead
of interpreting the code again. This increases the performance and speed of the
execution.
11. Can you tell the difference between equals() method and equality operator
(==) in Java?
equals() ==
This method is used for checking the This operator is used for comparing addresses (or
equality of contents between two objects as references), i.e checks if both the objects are pointing
per the specified business logic. to the same memory location.
Note:
• In the cases where the equals method is not overridden in a class, then the class uses the
default implementation of the equals method that is closest to the parent class.
• Object class is considered as the parent class of all the java classes. The implementation of
the equals method in the Object class uses the == operator to compare two objects. This
default implementation can be overridden as per the business logic.
12. How is an infinite loop declared in Java?
Infinite loops are those loops that run infinitely without any breaking conditions. Some
examples of consciously declaring infinite loop is:
for (;;)
{
// Business logic
// Any break logic
}
while(true){
// Business logic
// Any break logic
}
do{
// Business logic
// Any break logic
}while(true);
class Hospital {
int variable1, variable2;
double variable3;
public Hospital(int doctors, int nurses) {
variable1 = doctors;
variable2 = nurses;
}
public Hospital(int doctors) {
variable1 = doctors;
}
public Hospital(double salaries) {
variable3 = salaries
}
}
Three constructors are defined here but they differ on the basis of parameter type and their
numbers.
Copy Constructor is the constructor used when we want to initialize the value to the new
object from the old object of the same class.
class InterviewBit{
String department;
String service;
InterviewBit(InterviewBit ib){
this.departments = ib.departments;
this.services = ib.services;
}
}
Here we are initializing the new object value from the old object value in the constructor.
Although, this can also be achieved with the help of object cloning.
Yes, It is possible to overload the main method. We can create as many overloaded main
methods we want. However, JVM has a predefined calling method that JVM will only call
the main method with the definition of -
class Main {
public static void main(String args[]) {
System.out.println(" Main Method");
}
public static void main(int[] args){
System.out.println("Overloaded Integer array Main Method");
}
public static void main(char[] args){
System.out.println("Overloaded Character array Main Method");
}
public static int main(double[] args){
System.out.println("Overloaded Double array Main Method");
}
public static void main(float args){
System.out.println("Overloaded float Main Method");
}
}
In Java, method overloading is made possible by introducing different methods in the same
class consisting of the same name. Still, all the functions differ in the number or type of
parameters. It takes place inside a class and enhances program readability.
The only difference in the return type of the method does not promote method overloading.
The following example will furnish you with a clear picture of it.
class OverloadingHelp {
public int findarea (int l, int b) {
int var1;
var1 = l * b;
return var1;
}
public int findarea (int l, int b, int h) {
int var2;
var2 = l * b * h;
return var2;
}
}
Both the functions have the same name but differ in the number of arguments. The first
method calculates the area of the rectangle, whereas the second method calculates the area of
a cuboid.
Method overriding is the concept in which two methods having the same method signature
are present in two different classes in which an inheritance relationship is present. A
particular method implementation (already present in the base class) is possible for the
derived class by using method overriding.
Let’s give a look at this example:
class HumanBeing {
public int walk (int distance, int time) {
int speed = distance / time;
return speed;
}
}
class Athlete extends HumanBeing {
public int walk(int distance, int time) {
int speed = distance / time;
speed = speed * 2;
return speed;
}
}
Both class methods have the name walk and the same parameters, distance, and time. If the
derived class method is called, then the base class method walk gets overridden by that of the
derived class.
17. A single try block and multiple catch blocks can co-exist in a Java
Program. Explain.
Yes, multiple catch blocks can exist but specific approaches should come prior to the general
approach because only the first catch block satisfying the catch condition is executed. The
given code illustrates the same:
18. Explain the use of final keyword in variable, method and class.
In Java, the final keyword is used as defining something as constant /final and represents the
non-access modifier.
• final variable:
o When a variable is declared as final in Java, the value can’t be modified once it has
been assigned.
o If any value has not been assigned to that variable, then it can be assigned only by
the constructor of the class.
• final method:
o A method declared as final cannot be overridden by its children's classes.
o A constructor cannot be marked as final because whenever a class is inherited, the
constructors are not inherited. Hence, marking it final doesn't make sense. Java
throws compilation error saying - modifier final not allowed here
• final class:
o No classes can be inherited from the class declared as final. But that final class can
extend other classes for its usage.
19. Do final, finally and finalize keywords have the same function?
Final: If any restriction is required for classes, variables, or methods, the final keyword
comes in handy. Inheritance of a final class and overriding of a final method is restricted by
the use of the final keyword. The variable value becomes fixed after incorporating the final
keyword. Example:
Finally: It is the block present in a program where all the codes written inside it get executed
irrespective of handling of exceptions. Example:
try {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}
Finalize: Prior to the garbage collection of an object, the finalize method is called so that the
clean-up activity is implemented. Example:
public static void main(String[] args) {
String example = new String("InterviewBit");
example = null;
System.gc(); // Garbage collector called
}
public void finalize() {
// Finalize called
}
20. Is it possible that the ‘finally’ block will not be executed? If yes then list
the case.
Yes. It is possible that the ‘finally’ block will not be executed. The cases are-
21. Identify the output of the java program and state the reason.
1. public class InterviewBit
2. {
3. public static void main(String[] args) {
4. final int i;
5. i = 20;
6. int j = i+20;
7. i = j+30;
8. System.out.println(i + " " + j);
9. }
10. }
The above code will generate a compile-time error at Line 7 saying - [error: variable i
might already have been initialized]. It is because variable ‘i’ is the final variable. And
final variables are allowed to be initialized only once, and that was already done on line no 5.
• The super keyword is used to access hidden fields and overridden methods or attributes of
the parent class.
• Following are the cases when this keyword can be used:
o Accessing data members of parent class when the member names of the class and
its child subclasses are same.
o To call the default and parameterized constructor of the parent class inside the child
class.
o Accessing the parent class methods when the child classes have overridden them.
• The following example demonstrates all 3 cases when a super keyword is used.
Parent(){
System.out.println("Parent class default constructor.");
}
Parent(String x){
System.out.println("Parent class parameterised constructor.");
}
Child(){
System.out.println("Child class default Constructor");
super("Call Parent"); // to call parameterised constructor.
super(); // to call default parent constructor
void printNum(){
System.out.println(num);
System.out.println(super.num); //prints the value of num of
parent class
}
@Override
public void foo(){
System.out.println("Parent class foo!");
super.foo(); //Calls foo method of Parent class inside the
Overriden foo method of Child class.
}
}
Yes! There can be two or more static methods in a class with the same name but differing
input parameters.
The main method is always static because static members are those methods that belong to
the classes, not to an individual object. So if the main method will not be static then for every
object, It is available. And that is not acceptable by JVM. JVM calls the main method based
on the class name itself. Not by creating the object.
Because there must be only 1 main method in the java program as the execution starts from
the main method. So for this reason the main method is static.
• No! Declaration of static methods having the same signature can be done in the subclass but
run time polymorphism can not take place in such cases.
• Overriding or dynamic polymorphism occurs during the runtime, but the static methods are
loaded and looked up at the compile time statically. Hence, these methods cant be
overridden.
26. Difference between static methods, static variables, and static classes in
java.
• Static Methods and Static variables are those methods and variables that belong to the
class of the java program, not to the object of the class. This gets memory where the class is
loaded. And these can directly be called with the help of class names.
o For example - We have used mathematical functions in the java program like -
max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it
directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static
method. And Similarly static variables we have used like (length) for the array to get
the length. So that is the static method.
• Static classes - A class in the java program cannot be static except if it is the inner class. If it
is an inner static class, then it exactly works like other static members of the class.
The main objective of this process is to free up the memory space occupied by the
unnecessary and unreachable objects during the Java program execution by deleting those
unreachable objects.
• This ensures that the memory resource is used efficiently, but it provides no guarantee that
there would be sufficient memory for the program execution.
• Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of
ClassLoader is to load the required classes and interfaces to the JVM when required.
• Example- To get input from the console, we require the scanner class. And the Scanner class
is loaded by the ClassLoader.
Heap.
To copy the object's data, we have several methods like deep copy and shallow copy.
Example -
class Rectangle{
int length = 5;
int breadth = 3;
}
• Shallow copy - The shallow copy only creates a new reference and points to the same
object. Example - For Shallow copy, we can do this by -
Rectangle obj2 = obj1;
Now by doing this what will happen is the new reference is created with the name obj2 and
that will point to the same memory location.
• Deep Copy - In a deep copy, we create a new object and copy the old object value to the
new object. Example -
Both these objects will point to the memory location as stated below -
Now, if we change the values in shallow copy then they affect the other reference as well.
Let's see with the help of an example -
class Rectangle
{
int length = 5;
int breadth = 3;
}
public class Main
{
public static void main(String[] args) {
Rectangle obj1 = new Rectangle();
//Shallow Copy
Rectangle obj2 = obj1;
}
}
Output -
We can see that in the above code, if we change the values of object1, then the object2 values
also get changed. It is because of the reference.
Now, if we change the code to deep copy, then there will be no effect on object2 if it is of
type deep copy. Consider some snippets to be added in the above code.
class Rectangle
{
int length = 5;
int breadth = 3;
}
public class Main
{
public static void main(String[] args) {
Rectangle obj1 = new Rectangle();
//Shallow Copy
Rectangle obj2 = new Rectangle();
obj2.length = obj1.length;
obj2.breadth = obj1.breadth;
}
}
The above snippet will not affect the object2 values. It has its separate values. The output will
be
Now we see that we need to write the number of codes for this deep copy. So to reduce this,
In java, there is a method called clone().
The clone() will do this deep copy internally and return a new object. And to do this we need
to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();
31. Apart from the security aspect, what are the reasons behind making
strings immutable in Java?
• String Pool: Designers of Java were aware of the fact that String data type is going to be
majorly used by the programmers and developers. Thus, they wanted optimization from the
beginning. They came up with the notion of using the String pool (a storage area in Java
heap) to store the String literals. They intended to decrease the temporary String object with
the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the
mutable structures between two unknown parties is not possible. Thus, immutable Java
String helps in executing the concept of String Pool.
• Multithreading: The safety of threads regarding the String objects is an important aspect in
Java. No external synchronization is required if the String objects are immutable. Thus, a
cleaner code can be written for sharing the String objects across different threads. The
complex process of concurrency is facilitated by this method.
• Collections: In the case of Hashtables and HashMaps, keys are String objects. If the String
objects are not immutable, then it can get modified during the period when it resides in the
HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing
states pose a lot of risks. Therefore, it is quite safe to make the string immutable.
32. What is a singleton class in Java? And How to implement a singleton
class?
Singleton classes are those classes, whose objects are created only once. And with only that
object the class members can be accessed.
Consider the water jug in the office and if every employee wants that water then they will not
create a new water jug for drinking water. They will use the existing one with their own
reference as a glass. So programmatically it should be implemented as -
class WaterJug{
private int waterQuantity = 500;
private WaterJug(){}
private WaterJug object = null;
In the above class, the Constructor is private so we cannot create the object of the class. But
we can get the object by calling the method getInstance(). And the getInstance is static so it
can be called without creating the object. And it returns the object. Now with that object, we
can call getWater() to get the water.
We can get the single object using this getInstance(). And it is static, so it is a thread-safe
singleton class. Although there are many ways to create a thread-safe singleton class. So
thread-safe classes can also be:
• When singletons are written with double-checked locking, they can be thread-safe.
• We can use static singletons that are initialized during class loading. Like we did in the above
example.
• But the most straightforward way to create a thread-safe singleton is to use Java enums.
33. Which of the below generates a compile-time error? State the reason.
We get a compile-time error in line 3. The error we will get in Line 3 is - integer number
too large. It is because the array requires size as an integer. And Integer takes 4 Bytes in the
memory. And the number (2241423798) is beyond the capacity of the integer. The maximum
array size we can declare is - (2147483647).
Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a
compile-time error. The program will compile fine. But we get the runtime exception in line
2. The exception is - NegativeArraySizeException.
Here what will happen is - At the time when JVM will allocate the required memory during
runtime then it will find that the size is negative. And the array size can’t be negative. So the
JVM will throw the exception.
• Storage area: In string, the String pool serves as the storage area. For StringBuilder and
StringBuffer, heap memory is the storage area.
• Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are
mutable.
• Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in
performing operations. The speed of a StringBuffer is more than a String and less than a
StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in
String because a new memory is required for the new String with appended character.)
• Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used
whereas a String is not used. However, StringBuilder is suitable for an environment with a
single thread, and a StringBuffer is suitable for multiple threads.
Syntax:
// String
String first = "InterviewBit";
String second = new String("InterviewBit");
// StringBuffer
StringBuffer third = new StringBuffer("InterviewBit");
// StringBuilder
StringBuilder fourth = new StringBuilder("InterviewBit");
35. Using relevant properties highlight the differences between interfaces and
abstract classes.
• Availability of methods: Only abstract methods are available in interfaces, whereas non-
abstract methods can be present along with abstract methods in abstract classes.
• Variable types: Static and final variables can only be declared in the case of interfaces,
whereas abstract classes can also have non-static and non-final variables.
• Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do
not promote multiple inheritances.
• Data member accessibility: By default, the class data members of interfaces are of the
public- type. Conversely, the class members for an abstract class can be protected or private
also.
• Implementation: With the help of an abstract class, the implementation of an interface is
easily possible. However, the converse is not true;
Interface example:
36. Is this program giving a compile-time error? If Yes then state the reason
and number of errors it will give. If not then state the reason.
abstract final class InterviewBit{
2. public abstract void printMessage();
3. }
4. class ScalarAcademy extends InterviewBit{
5. public void printMessage(){
6. System.out.println("Welcome to Scalar Academy By InterviewBit");
7. }
8. }
9. class ScalarTopics extends ScalarAcademy{
10. public void printMessage(){
11. System.out.println("Welcome to Scalar Topics By Scalar
Academy");
12. }
13. }
public class Main{
public static void main(String[] args) {
InterviewBit ib = new ScalarTopics();
ib.printMessage();
}
}
The above program will give a compile-time error. The compiler will throw 2 errors in this.
It is because abstract classes are incomplete classes that need to be inherited for making their
concrete classes. And on the other hand, the final keywords in class are used for avoiding
inheritance. So these combinations are not allowed in java.
37. What is a Comparator in java?
Consider the example where we have an ArrayList of employees like( EId, Ename, Salary),
etc. Now if we want to sort this list of employees based on the names of employees. Then that
is not possible to sort using the Collections.sort() method. We need to provide something to
the sort() function depending on what values we have to perform sorting. Then in that case a
comparator is used.
Comparator is the interface in java that contains the compare method. And by overloading the
compare method, we can define that on what basis we need to compare the values.
The statement in the context is completely False. The static methods have no relevance with
the objects, and these methods are of the class level. In the case of a child class, a static
method with a method signature exactly like that of the parent class can exist without even
throwing any compilation error.
The phenomenon mentioned here is popularly known as method hiding, and overriding is
certainly not possible. Private method overriding is unimaginable because the visibility of the
private method is restricted to the parent class only. As a result, only hiding can be facilitated
and not overriding.
Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not
present, there are certain properties that distinguish a HashSet from a TreeSet.
• Implementation: For a HashSet, the hash table is utilized for storing the elements in an
unordered manner. However, TreeSet makes use of the red-black tree to store the elements
in a sorted manner.
• Complexity/ Performance: For adding, retrieving, and deleting elements, the time
amortized complexity is O(1) for a HashSet. The time complexity for performing the same
operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of
HashSet is faster in comparison to TreeSet.
• Methods: hashCode() and equals() are the methods utilized by HashSet for making
comparisons between the objects. Conversely, compareTo() and compare() methods are
utilized by TreeSet to facilitate object comparisons.
• Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the
case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null
objects.
40. Why is the character array preferred over string for storing confidential
information?
In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it
continues to stay in the string pool as long as it is not removed in the form of garbage. In
other words, a string resides in the heap section of the memory for an unregulated and
unspecified time interval after string value processing is executed.
As a result, vital information can be stolen for pursuing harmful activities by hackers if a
memory dump is illegally accessed by them. Such risks can be eliminated by using mutable
objects or structures like character arrays for storing any variable. After the work of the
character array variable is done, the variable can be configured to blank at the same instant.
Consequently, it helps in saving heap memory and also gives no chance to the hackers to
extract vital data.
• JDK- For making java programs, we need some tools that are provided by JDK (Java
Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime
Environment, etc.
• JRE - To execute the java program we need an environment. (Java Runtime Environment)
JRE contains a library of Java classes + JVM. What are JAVA Classes? It contains some
predefined methods that help Java programs to use that feature, build and execute. For
example - there is a system class in java that contains the print-stream method, and with the
help of this, we can print something on the console.
• JVM - (Java Virtual Machine) JVM is a part of JRE that executes the Java program at the
end. Actually, it is part of JRE, but it is software that converts bytecode into machine-
executable code to execute on hardware.
42. What are the differences between JVM, JRE and JDK in Java?
Java Runtime
Abbreviation Java Development Kit Java Virtual Machine
Environment
JRE = (JVM) +
JDK = (JRE) + JVM = Runtime environment to execute
Summary Libraries to execute
Development tools Java byte code.
the application
43. What are the differences between HashMap and HashTable in Java?
HashMap HashTable
Allows only one null key but any number of null in This does not allow null in both keys or
the values. values.
Supports order of insertion by making use of its Order of insertion is not guaranteed in
subclass LinkedHashMap. HashTable.
44. What is the importance of reflection in Java?
• The term reflection is used for describing the inspection capability of a code on other
code either of itself or of its system and modify it during runtime.
• Consider an example where we have an object of unknown type and we have a method
‘fooBar()’ which we need to call on the object. The static typing system of Java doesn't allow
this method invocation unless the type of the object is known beforehand. This can be
achieved using reflection which allows the code to scan the object and identify if it has any
method called “fooBar()” and only then call the method if needed.
• Implementing a thread using the method of Runnable interface is more preferred and
advantageous as Java does not have support for multiple inheritances of classes.
• start() method is used for creating a separate call stack for the thread execution. Once
the call stack is created, JVM calls the run() method for executing the thread in that call
stack.
46. What are the different types of Thread Priorities in Java? And what is the
default priority of a thread assigned by JVM?
In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default
priority for any thread is NORM_PRIORITY assigned by JVM.
47. What is the difference between the program and the process?
• A program can be defined as a line of code written in order to accomplish a particular task.
Whereas the process can be defined as the programs which are under execution.
• A program doesn't execute directly by the CPU. First, the resources are allocated to the
program and when it is ready for execution then it is a process.
48. What is the difference between the ‘throw’ and ‘throws’ keyword in java?
• The ‘throw’ keyword is used to manually throw the exception to the calling method.
• And the ‘throws’ keyword is used in the function definition to inform the calling method that
this method throws the exception. So if you are calling, then you have to handle the
exception.
Example -
class Main {
public static int testExceptionDivide(int a, int b) throws
ArithmeticException{
if(a == 0 || b == 0)
throw new ArithmeticException();
return a/b;
}
public static void main(String args[]) {
try{
testExceptionDivide(10, 0);
}
catch(ArithmeticException e){
//Handle the exception
}
}
}
Here in the above snippet, the method testExceptionDivide throws an exception. So if the
main method is calling it then it must have handled the exception. Otherwise, the main
method can also throw the exception to JVM.
And the method testExceptionDivide 'throws’ the exception based on the condition.
49. What are the differences between constructor and method of a class in
Java?
Constructor Method
If the constructor is not defined, then a default constructor is If a method is not defined, then the
provided by the java compiler. compiler does not provide it.
50. Identify the output of the below java program and Justify your answer.
class Main {
public static void main(String args[]) {
Scaler s = new Scaler(5);
}
}
class InterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
class Scaler extends InterviewBit{
Scaler(){
System.out.println(" Welcome to Scaler Academy ");
}
Scaler(int x){
this();
super();
System.out.println(" Welcome to Scaler Academy 2");
}
}
The above code will throw the compilation error. It is because the super() is used to call the
parent class constructor. But there is the condition that super() must be the first statement in
the block. Now in this case, if we replace this() with super() then also it will throw the
compilation error. Because this() also has to be the first statement in the block. So in
conclusion, we can say that we cannot use this() and super() keywords in the same block.
Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java.
However, when the object is passed in any method, the address of the value is passed due to
the nature of object handling in Java. When an object is passed, a copy of the reference is
created by Java and that is passed to the method. The objects point to the same memory
location. 2 cases might happen inside the method:
• Case 1: When the object is pointed to another location: In this case, the changes made to
that object do not get reflected the original object before it was passed to the method as the
reference points to another location.
For example:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver {
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in
the object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// Point the object to new reference
ibObj = new InterviewBitTest();
// Update the value
ibObj.num = 50;
}
}
Output:
20
• Case 2: When object references are not modified: In this case, since we have the copy of
reference the main object pointing to the same memory location, any changes in the
content of the object get reflected in the original object.
For example:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver{
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in
the object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// no changes are made to point the ibObj to new location
// Update the value of num
ibObj.num = 50;
}
}
Output:
50
‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the
derived class, then it forms a relationship between the classes. So that relationship is termed
an ‘IS-A’ Relationship.
Example - Consider a Television (Typical CRT TV). Now another Smart TV that is
inherited from television class. So we can say that the Smart iv is also a TV. Because CRT
TV things can also be done in the Smart TV.
So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ].
53. Which among String or String Buffer should be preferred when there are
lot of updates required to be done in the data?
StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation /
modification of String creates a new String thereby overloading the string pool with
unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use
StringBuffer as it will reduce the overhead of the creation of multiple String objects in the
string pool.
• In order to achieve this, the attribute can be declared along with the usage of transient
keyword as shown below:
• In the above example, all the fields except someInfo can be serialized.
55. What happens if the static modifier is not included in the main method
signature in Java?
There wouldn't be any compilation error. But then the program is run, since the JVM cant
map the main method signature, the code throws “NoSuchMethodError” error at the runtime.
56. Consider the below program, identify the output, and also state the reason
for that.
public class Main{
public static void main(String[] args) {
System.out.println(" Hello. Main Method. ");
}
public static void main(int[] args) {
System.out.println(" Hello. Main Method2. ");
}
}
The output of the above program will be Hello. Main Method. This is because JVM will
always call the main method based on the definition it already has. Doesn't matter how many
main methods we overload it will only execute one main method based on its declaration in
JVM.
In java multithreading, the main() threads are always non-daemon threads. And there is no
way we can change the nature of the non-daemon thread to the daemon thread.
58. What happens if there are multiple main methods inside one class in Java?
The program can't compile as the compiler says that the method has been already defined
inside the class.
59. What do you understand by Object Cloning and how do you achieve it in
Java?
• It is the process of creating an exact copy of any object. In order to support this, a java class
has to implement the Cloneable interface of java.lang package and override the clone()
method provided by the Object class the syntax of which is:
• In case the Cloneable interface is not implemented and just the method is overridden, it
results in CloneNotSupportedException in Java.
When an exception occurs, first it searches to locate the matching catch block. In case, the
matching catch block is located, then that block would be executed. Else, the exception
propagates through the method call stack and goes into the caller method where the process
of matching the catch block is performed. This propagation happens until the matching catch
block is found. If the match is not found, then the program gets terminated in the main
method.
61. How do exceptions affect the program if it doesn't handle them?
Exceptions are runtime errors. Suppose we are making an android application with java. And
it all works fine but there is an exceptional case when the application tries to get the file from
storage and the file doesn’t exist (This is the case of exception in java). And if this case is not
handled properly then the application will crash. This will be a bad experience for users. This
is the type of error that cannot be controlled by the programmer. But programmers can take
some steps to avoid this so that the application won’t crash. The proper action can be taken at
this step.
No, it is not necessary for a catch block to be present after a try block. - A try block should be
followed either by a catch block or by a finally block. If the exceptions likelihood is more,
then they should be declared using the throws clause of the method.
63. Will the finally block get executed when the return statement is written at
the end of try block and catch block as shown below?
public int someMethod(int i){
try{
//some statement
return 1;
}catch(Exception e){
//some statement
return 999;
}finally{
//finally block statements
}
}
finally block will be executed irrespective of the exception or not. The only case where
finally block is not executed is when it encounters ‘System.exit()’ method anywhere in
try/catch block.
64. Can you call a constructor of a class inside the another constructor?
Yes, the concept can be termed as constructor chaining and can be achieved using this().
65. Contiguous memory locations are usually used for storing actual values in
an array but not in ArrayList. Explain.
In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is
not possible. The data members/objects present in the ArrayList have references to the
objects which are located at various sites in the memory. Thus, storing of actual objects or
non-primitive data types (like Integer, Double, etc.) takes place in various memory locations.
However, the same does not apply to the arrays. Object or primitive type values can be stored
in arrays in contiguous memory locations, hence every element does not require any
reference to the next element.
It is because the 0 index array avoids the extra arithmetic operation to calculate the memory
address.
Example - Consider the array and assume each element takes 4-byte memory space. Then the
address will be like this -
Now if we want to access index 4. Then internally java calculates the address using the
formula-
[Base Address + (index * no_of_bytes)]. So according to this. The starting address of the
index 4 will be - [100 + (4*4)] = 116. And exactly that's what the address is calculated.
Now consider the same with 1 index Array -
Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th
index. Which is wrong. Then we need to apply formula - [Base Address + ((index-1) *
no_of_bytes)].
And for calculating this, an extra arithmetic operation has to be performed. And consider the
case where millions of addresses need to be calculated, this causes complexity. So to avoid
this, ) the index array is supported by java.
67. Why is the remove method faster in the linked list than in an array?
In the linked list, we only need to adjust the references when we want to delete the element
from either end or the front of the linked list. But in the array, indexes are used. So to manage
proper indexing, we need to adjust the values from the array So this adjustment of value is
costlier than the adjustment of references.
Example - To Delete from the front of the linked list, internally the references adjustments
happened like this.
The only thing that will change is that the head pointer will point to the head’s next node.
And delete the previous node. That is the constant time operation.
68. How many overloaded add() and addAll() methods are available in the
List interface? Describe the need and uses.
There are a total of 4 overloaded methods for add() and addAll() methods available in List
Interface. The below table states the description of all.
Return
Method Description
Type
add(Element e): This method is used for adding the element at the end of the List. The
boolean Datatype of the element is of any type it has been initially assigned with. It returns the
boolean indicating successfully inserted or not.
add(int index, Element e): This method is the overloaded version of add() method. In
void this, along with the element, the index is also passed to the method for the specific index
the value needs to be inserted.
addAll(Collection <extends ? Element > c): This method helps to add all elements at the
boolean end of collections from the list received in the parameter. It contains an iterator that
helps to iterate the list and add the elements to the collection.
addAll(int index, Collection <extends ? Element > c): This is the overloaded method for
boolean addAll() method. In this along with the list, we can pass the specified index from which
the list elements need to be added.
69. How does the size of ArrayList grow dynamically? And also state how it is
implemented internally.
ArrayList is implemented in such a way that it can grow dynamically. We don't need to
specify the size of ArrayList. For adding the values in it, the methodology it uses is -
1. Consider initially that there are 2 elements in the ArrayList. [2, 3].
2. If we need to add the element into this. Then internally what will happen is-
• ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And
add the old elements into the new. Old - [2, 3], New - [2, 3, null, null].
• Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra
space will be available for the value to be inserted.
3. This process continues and the time taken to perform all of these is considered as the
amortized constant time.
This is how the ArrayList grows dynamically. And when we delete any entry from the
ArrayList then the following steps are performed -
1. It searches for the element index in the array. Searching takes some time. Typically it’s
O(n) because it needs to search for the element in the entire array.
2. After searching the element, it needs to shift the element from the right side to fill the
index.
So this is how the elements are deleted from the ArrayList internally. Similarly, the search
operations are also implemented internally as defined in removing elements from the list
(searching for elements to delete).
• Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In
cases where multiple functionalities are required, for example - to read and write
information into the file, the pattern of composition is preferred. The writer, as well as
reader functionalities, can be made use of by considering them as the private members.
• Composition assists in attaining high flexibility and prevents breaking of encapsulation.
• Unit testing is possible with composition and not inheritance. When a developer wants to
test a class composing a different class, then Mock Object can be created for signifying the
composed class to facilitate testing. This technique is not possible with the help of
inheritance as the derived class cannot be tested without the help of the superclass in
inheritance.
• The loosely coupled nature of composition is preferable over the tightly coupled nature of
inheritance.
Let’s take an example:
package comparison;
public class Top {
public int start() {
return 0;
}
}
class Bottom extends Top {
public int stop() {
return 0;
}
}
In the above example, inheritance is followed. Now, some modifications are done to the Top
class like this:
If the new implementation of the Top class is followed, a compile-time error is bound to
occur in the Bottom class. Incompatible return type is there for the Top.stop() function.
Changes have to be made to either the Top or the Bottom class to ensure compatibility.
However, the composition technique can be utilized to solve the given problem:
class Bottom {
Top par = new Top();
public int stop() {
par.start();
par.stop();
return 0;
}
}
71. What is the difference between ‘>>’ and ‘>>>’ operators in java?
These 2 are the bitwise right shift operators. Although both operators look similar. But there
is a minimal difference between these two right shift operators.
• ‘>>’ Bitwise Right Shift Operator- This operator shifts each bit to its right position. And this
maintains the signed bit.
• ‘>>>’ Bitwise Right Shift Operator with trailing zero- This operator also shifts each bit to its
right. But this doesn’t maintain the signed bit. This operator makes the Most significant bit
to 0.
Composition, and Aggregation help to build (Has - A - Relationship) between classes and
objects. But both are not the same in the end. Let’s understand with the help of an
example.
• Consider the University as a class that has some departments in it. So the university will be
the container object. And departments in it will contain objects. Now in this case, if the
container object destroys then the contained objects will also get destroyed
automatically. So here we can say that there is a strong association between the objects. So
this Strong Association is called Composition.
• Now consider one more example. Suppose we have a class department and there are
several professors' objects there in the department. Now if the department class is
destroyed then the professor's object will become free to bind with other objects. Because
container objects (Department) only hold the references of contained objects (Professor’s).
So here is the weak association between the objects. And this weak association is called
Aggregation.
73. How is the creation of a String using new() different from that of a literal?
When a String is formed as a literal with the assistance of an assignment operator, it makes its
way into the String constant pool so that String Interning can take place. This same object in
the heap will be referenced by a different String if the content is the same for both of them.
The checking() function will return true as the same content is referenced by both the
variables.
Conversely, when a String formation takes place with the help of a new() operator, interning
does not take place. The object gets created in the heap memory even if the same content
object is present.
The checking() function will return false as the same content is not referenced by both the
variables.
74. How is the ‘new’ operator different from the ‘newInstance()’ operator in
java?
Both ‘new’ and ‘newInstance()’ operators are used to creating objects. The difference is-
that when we already know the class name for which we have to create the object then we use
a new operator. But suppose we don’t know the class name for which we need to create the
object, Or we get the class name from the command line argument, or the database, or the
file. Then in that case we use the ‘newInstance()’ operator.
The ‘newInstance()’ keyword throws an exception that we need to handle. It is because there
are chances that the class definition doesn’t exist, and we get the class name from runtime. So
it will throw an exception.
Yes, it is possible for the program to go out of memory in spite of the presence of a garbage
collector. Garbage collection assists in recognizing and eliminating those objects which are
not required in the program anymore, in order to free up the resources used by them.
In a program, if an object is unreachable, then the execution of garbage collection takes place
with respect to that object. If the amount of memory required for creating a new object is not
sufficient, then memory is released for those objects which are no longer in the scope with
the help of a garbage collector. The memory limit is exceeded for the program when the
memory released is not enough for creating new objects.
Moreover, exhaustion of the heap memory takes place if objects are created in such a manner
that they remain in the scope and consume memory. The developer should make sure to
dereference the object after its work is accomplished. Although the garbage collector
endeavors its level best to reclaim memory as much as possible, memory limits can still be
exceeded.
Synchronization assists in resolving the issue and the resource is shared by a single thread at
a time. Let’s take an example to understand it more clearly. For example, you have a URL
and you have to find out the number of requests made to it. Two simultaneous requests can
make the count erratic.
No synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if
another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus,
inconsistency in count values takes place because the expected final value is 12 but the actual
final value we get will be 11.
Now, the function increase() is made synchronized so that simultaneous accessing cannot
take place.
With synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public synchronized int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread
Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count
values takes place.
• Ability to provide ... is a feature called varargs (variable arguments) which was introduced
as part of Java 5.
• The function having ... in the above example indicates that it can receive multiple
arguments of the datatype String.
• For example, the fooBarMethod can be called in multiple ways and we can still have one
method to process the data as shown below:
fooBarMethod("foo", "bar");
fooBarMethod("foo", "bar", "boo");
fooBarMethod(new String[]{"foo", "var", "boo"});
public void myMethod(String... variables){
for(String variable : variables){
// business logic
}
}
78. What will be the output of the below java program and define the steps of
Execution of the java program with the help of the below code?
class InterviewBit{
int i;
static int j;
{
System.out.println(" Instance Block 1. Value of i = "+i);
}
static{
System.out.println(" Static Block 1. Value of j = "+j);
method_2();
}
{
i = 5;
}
static{
j = 10;
}
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
public static void main(String[] args){
InterviewBit ib = new InterviewBit();
}
public void method_1(){
System.out.println(" Instance method. ");
}
static{
System.out.println(" Static Block 2. Value of j = "+j);
}
{
System.out.println(" Instance Block 2. Value of i = "+i);
method_1();
}
public static void method_2(){
System.out.println(" Static method. ");
}
}
In above steps from 4 to 6, will be executed for every object creation. If we create multiple
objects then for every object these steps will be performed.
Now from the above code, the execution will happen like this -
• static int j.
• static block.
• main method.
• static method_2.
During identification, the JVM will assign the default value in the static int j variable. Then it
is currently in the state of reading and indirectly writing. Because the original value is not
assigned.
2. In the next step, it will execute the static block and assign the value in static variables.
• First static block it will print and because execution from top to bottom and original value in
j is not assigned. So it will print the default value of 0.
• After executing static block 1. It will execute the static method_1 because it is called from
the static block 1.
• Then it will assign the original value of 5 in the j variable. And executes the remaining static
block.
3. Now it will execute the main method. In which it will create an object for the class
InterviewBit. And then the execution of instances will happen.
• int i.
• Instance block 1.
• Instance method_1.
Like a static variable, the instance variable also has been initialized with the default value 0
and will be in the state of reading and writing indirectly.
5. It will execute the instance methods and assign the original value to the instance variable.
• Prints the Instance block 1. And the current value of i is not assigned till now, so it will print
0.
• Assign the original value to i. Then print instance block 2. And after that instance method will
be called and printed because it is being called in the instance block.
6. And at the last step, the constructor will be invoked and the lines will be executed in the
constructor.
So if we justify the statement, then we can say that if we want to print anything on the
console then we need to call the println() method that was present in PrintStream class. And
we can call this using the output object that is present in the System class.
• New – When the instance of the thread is created and the start() method has not been
invoked, the thread is considered to be alive and hence in the NEW state.
• Runnable – Once the start() method is invoked, before the run() method is called by JVM,
the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered
from the Waiting or Sleeping state of the thread.
• Running – When the run() method has been invoked and the thread starts its execution, the
thread is said to be in a RUNNING state.
• Non-Runnable (Blocked/Waiting) – When the thread is not able to run despite the fact of its
aliveness, the thread is said to be in a NON-RUNNABLE state. Ideally, after some time of its
aliveness, the thread should go to a runnable state.
o A thread is said to be in a Blocked state if it wants to enter synchronized code but it
is unable to as another thread is operating in that synchronized block on the same
object. The first thread has to wait until the other thread exits the synchronized
block.
o A thread is said to be in a Waiting state if it is waiting for the signal to execute from
another thread, i.e it waits for work until the signal is received.
• Terminated – Once the run() method execution is completed, the thread is said to enter the
TERMINATED step and is considered to not be alive.
The following flowchart clearly explains the lifecycle of the thread in Java.
81. What could be the tradeoff between the usage of an unordered array
versus the usage of an ordered array?
• The main advantage of having an ordered array is the reduced search time complexity of
O(log n) whereas the time complexity in an unordered array is O(n).
• The main drawback of the ordered array is its increased insertion time which is O(n) due to
the fact that its element has to reordered to maintain the order of array during every
insertion whereas the time complexity in the unordered array is only O(1).
• Considering the above 2 key points and depending on what kind of scenario a developer
requires, the appropriate data structure can be used for implementation.
82. Is it possible to import the same class or package twice in Java and what
happens to it during runtime?
It is possible to import a class or package more than once, however, it is redundant because
the JVM internally loads the package or class only once.
83. In case a package has sub packages, will it suffice to import only the main
package? e.g. Does importing of com.myMainPackage.* also import
com.myMainPackage.mySubPackage.*?
This is a big NO. We need to understand that the importing of the sub-packages of a package
needs to be done explicitly. Importing the parent package only results in the import of the
classes within it and not the contents of its child/sub-packages.
84. Will the finally block be executed if the code System.exit(0) is written at
the end of try block?
NO. The control of the program post System.exit(0) is immediately gone and the program
gets terminated which is why the finally block never gets executed.
Marker interfaces, also known as tagging interfaces are those interfaces that have no methods
and constants defined in them. They are there for helping the compiler and JVM to get run
time-related information regarding the objects.
This is a convenient means of initializing any collections in Java. Consider the below
example.
import java.util.HashSet;
import java.util.Set;
doSomething(stringSets);
}
In the above example, we see that the stringSets were initialized by using double braces.
• The first brace does the task of creating an anonymous inner class that has the capability of
accessing the parent class’s behavior. In our example, we are creating the subclass of
HashSet so that it can use the add() method of HashSet.
• The second braces do the task of initializing the instances.
Care should be taken while initializing through this method as the method involves the
creation of anonymous inner classes which can cause problems during the garbage collection
or serialization processes and may also result in memory leaks.
87. Why is it said that the length() method of String class doesn't return
accurate results?
• The length method returns the number of Unicode units of the String. Let's understand what
Unicode units are and what is the confusion below.
• We know that Java uses UTF-16 for String representation. With this Unicode, we need to
understand the below two Unicode related terms:
o Code Point: This represents an integer denoting a character in the code space.
o Code Unit: This is a bit sequence used for encoding the code points. In order to do
this, one or more units might be required for representing a code point.
• Under the UTF-16 scheme, the code points were divided logically into 17 planes and the first
plane was called the Basic Multilingual Plane (BMP). The BMP has classic characters -
U+0000 to U+FFFF. The rest of the characters- U+10000 to U+10FFFF were termed as the
supplementary characters as they were contained in the remaining planes.
o The code points from the first plane are encoded using one 16-bit code unit
o The code points from the remaining planes are encoded using two code units.
Now if a string contained supplementary characters, the length function would count that as 2
units and the result of the length() function would not be as per what is expected.
In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE
character is considered to be TWO - Notice the inaccuracy here? As per the java
documentation, it is expected, but as per the real logic, it is inaccurate.
“bit” would have been the result printed if the letters were used in double-quotes (or the
string literals). But the question has the character literals (single quotes) being used which is
why concatenation wouldn't occur. The corresponding ASCII values of each character would
be added and the result of that sum would be printed.
The ASCII values of ‘b’, ‘i’, ‘t’ are:
• ‘b’ = 98
• ‘i’ = 105
• ‘t’ = 116
First Approach: Set the object references to null once the object creation purpose is served.
Second Approach: Point the reference variable to another object. Doing this, the object
which the reference variable was referencing before becomes eligible for GC.
In the above program, a total of 7 objects will be eligible for garbage collection. Let’s
visually understand what's happening in the code.
In the above figure on line 3, we can see that on each array index we are declaring a new
array so the reference will be of that new array on all the 3 indexes. So the old array will be
pointed to by none. So these three are eligible for garbage collection. And on line 4, we are
creating a new array object on the older reference. So that will point to a new array and older
multidimensional objects will become eligible for garbage collection.
91. What is the best way to inject dependency? Also, state the reason.
There is no boundation for using a particular dependency injection. But the recommended
approach is -
Setters are mostly recommended for optional dependencies injection, and constructor
arguments are recommended for mandatory ones. This is because constructor injection
enables the injection of values into immutable fields and enables reading them more easily.
92. How we can set the spring bean scope. And what supported scopes does it
have?
A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute in
an XML configuration file. Spring Bean supports the following five scopes:
• Singleton
• Prototype
• Request
• Session
• Global-session
Java Design patterns are categorized into the following different types. And those are also
further categorized as
Structural patterns:
• Adapter
• Bridge
• Filter
• Composite
• Decorator
• Facade
• Flyweight
• Proxy
Behavioral patterns:
• Interpreter
• Template method/ pattern
• Chain of responsibility
• Command pattern
• Iterator pattern
• Strategy pattern
• Visitor pattern
J2EE patterns:
• MVC Pattern
• Data Access Object pattern
• Front controller pattern
• Intercepting filter pattern
• Transfer object pattern
Creational patterns:
• Factory method/Template
• Abstract Factory
• Builder
• Prototype
• Singleton
The Java Garbage Collector (GC) typically removes unused objects when they are no longer
required, but when they are still referenced, the unused objects cannot be removed. So this
causes the memory leak problem. Example - Consider a linked list like the structure below -
In the above image, there are unused objects that are not referenced. But then also Garbage
collection will not free it. Because it is referencing some existing referenced object. So this
can be the situation of memory leak.
A thread that has a lock won't be released even after it calls sleep(). Despite the thread
sleeping for a specified period of time, the lock will not be released.
return word.charAt(word.length()- 1) +
getReverseWord(word.substring(0, word.length() - 1));
}
}
In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the
length of Fibonacci to be printed, we are using the helper function to print that.
98. Write a Java program to check if the two strings are anagrams.
The main idea is to validate the length of strings and then if found equal, convert the string to
char array and then sort the arrays and check if both are equal.
import java.util.Arrays;
import java.util.Scanner;
public class InterviewBit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//Input from two strings
System.out.print("First String: ");
String string1 = s.nextLine();
System.out.print("Second String: ");
String string2 = s.nextLine();
// check for the length
if(string1.length() == string2.length()) {
// convert strings to char array
char[] characterArray1 = string1.toCharArray();
char[] characterArray2 = string2.toCharArray();
// sort the arrays
Arrays.sort(characterArray1);
Arrays.sort(characterArray2);
// check for equality, if found equal then anagram, else not an
anagram
boolean isAnagram = Arrays.equals(characterArray1, characterArray2);
System.out.println("Anagram: "+ isAnagram);
}
}
99. Write a Java Program to find the factorial of a given number.
public class FindFactorial {
public static void main(String[] args) {
int num = 10;
long factorialResult = 1l;
for(int i = 1; i <= num; ++i)
{
factorialResult *= i;
}
System.out.println("Factorial: "+factorialResult);
}
}
Idea is to find the sum of n natural numbers using the formula and then finding the sum of
numbers in the given array. Subtracting these two sums results in the number that is the
actual missing number. This results in O(n) time complexity and O(1) space complexity.
int[] array={4,3,8,7,5,2,6};
int missingNumber = findMissingNum(array);
System.out.println("Missing Number is "+ missingNumber);
}
We have created the exception class named with CustomException and called the base
exception constructor with the error message that we want to print. And to avoid handling
exceptions in the main method, we have used the throws keyword in the method declaration.
103. Write a Java program to reverse a string.
class InterviewBit{
public static void main(String[] args){
//Input String
String str = "Welcome to InterviewBit";
//Pointers.
int i = 0, j = str.length()-1;
In the above code, we are storing the last character from the string to the first and the first
value to the last in the output character array. And doing the same thing in the loop for the
remaining 2nd to n-1 characters. This is how the string will be reversed.
System.out.println("\n");
//Rotation
//Transpose
for(int i = 0; i < no; i++){
for(int j = i; j < no; j++){
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
In the above code, for rotating the matrix to 90 degrees we are first transposing the matrix so
the row becomes the column. And after that, we are reversing each row in the matrix. So this
is how the matrix got rotated.
105. Write a java program to check if any number given as input is the sum of
2 prime numbers.
Example :
Input - 18
Output -
18 = 13 + 5
18 = 11 + 7
public class InterviewBit
{
// Method to Check Prime Number
private static int check_prime(int num){
int flag = 0;
for(int i = 2; i<=num/2; i++){
if(num%i == 0){
flag = 1;
return 1;
}
}
if(flag == 0)
return 0;
return 1;
}
// Method to get print the prime sum
private static void find(int num){
for(int i = 2; i <= num/2; i++){
if(check_prime(i) == 0){
if(check_prime(num-i) == 0)
System.out.println(num + " = "+ (num-i) + " "+ i);
}
}
}
public static void main(String[] args) {
find(18);
}
}
In the above code, for any number n, we find all the 2 pairs of numbers that are added
together resulting in n. And each checking number if it is prime. If it is prime then we are
printing that.
106. Write a Java program for solving the Tower of Hanoi Problem.
public class InterviewBit
{
//Recursive Method for Solving the Tower of hanoi.
private static void TOH(char source, char auxiliary, char destination,
int numOfDisk){
if (numOfDisk > 0){
TOH(source, destination, auxiliary, numOfDisk-1);
System.out.println("Move 1 disk from "+source+" to
"+destination+" using "+auxiliary+".");
TOH(auxiliary, source, destination, numOfDisk-1);
}
}
public static void main(String[] args) {
TOH('A','B','C', 3);
}
}
In the above code we are first moving the n-1 disk from Tower A to Tower B, then moving
that nth disk from Tower A to Tower C, and finally, the remaining n-1 disk from Tower B to
Tower C. And we are doing this recursively for the n-1 disk.
107. Implement Binary Search in Java using recursion.
public class Main
{
//Recursive method for binary search
private static boolean binarySearch(int[] arr, int low, int high, int
key){
//Calculating Mid.
int mid = (low + high)/2;
//Base Case.
if(low > high)
return false;
In the above code, we are finding the middle element each time and checking if the element is
in the middle or not. If it is not, then we check on which side from the middle it exists. And
Recursively searching on the particular subarray. So this way we are reducing the search
space by 2 every time. So the search time is very low.
Conclusion
108. Conclusion
Java is one of the simple high-level languages that provides powerful tools and impressive
standards required for application development. It was also one of the first languages to
provide amazing threading support for tackling concurrency-based problems. The easy-to-use
syntax and the built-in features of Java combined with the stability it provides to applications
are the main reasons for this language to have ever-growing usage in the software
community.
• How to Become a Java Developer?
• How much does a Java Developer earn in India?
• Java Projects
• Java Programming Questions for interview
• Java 8 Interview Questions
• Java String Interview Questions
• Spring Interview Questions
• Hibernate Interview Questions
• Java Collections Interview Questions
• Array Interview Questions
• Design Patterns Interview Questions
• Multithreading Interview Questions
• Java Tutorial
• Java MCQ
• Advance Java MCQ
• Difference Between C++ and Java
• Difference Between C and Java
• Difference Between Java and Javascript
• Kotlin Vs Java
• Java Vs Python
• Features of Java 9
• Java 8 Features
• Java Frameworks
• Java Developer Skills
• Java IDE
• Java 11 Features
→Java MCQ:-
REFERENCE:- INTERVIEW_BIT:-
1.What is the component used for compiling, debugging, and executing java programs?
JDK
JVM
JRE
JIT
2. What component does the task of bytecode to machine code conversion?
JDK
JVM
JRE
JIT
4. When an object has its own lifecycle and its child object cant belong to another parent object,
what is it called?
Association
Aggregation
Composition
Encapsulation
int-float method
float-int method
Compilation Error
Compilation Error
7. Which of the following happens when the garbage collection process kicks off during the
execution of the thread?
Both the process takes place simultaneously and does not interfere its execution.
false false
true true
true false
false true
12
15
42
25
-1
The life cycle of the thread in java is controlled by Java virtual machine. The java thread states are as
follows:
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
NEW is a newly created thread that has not yet started the execution. RUNNABLE is either running
or ready for execution but it's waiting for resource allocation. BLOCKED is waiting to acquire a
monitor lock to enter or re-enter a synchronized block/method.The thread is in running state if the
thread scheduler has selected it.A thread is in terminated or dead state when its run() method exits.
2. What do you know about Interface in Java?
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt ()
method. We can define a boolean variable which is used for stopping/killing threads say 'exit'
using a boolean flag. Whenever we want to stop a thread, the 'exit' variable will be set to true.
Volatile keyword is used to modify the value of a variable by different threads and used to
make classes thread safe. It means that multiple threads can use a method and instance of the
classes at the same time without any problem.
OutOfMemoryError is a runtime error which occurs when the Java Virtual Machine is unable
to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector
cannot free up the space required for a new object.
Memory allocation in java refers to the process where the computer programs and services are
allocated dedicated to virtual memory spaces. The memory in the JVM divided into 5 different parts:
• Class Area.
• Heap.
• Stack.
• Program Counter Register.
• Native Method Stack.
Java is built upon a virtual machine which is very secure and highly portable in nature. It is
grouped with a comprehensive library to provide support for the abstraction of the existing
platform.
public static void main(String[] args) Java main method is the entry point of any java
program. Its syntax is always public static void main(String[] args) . You can only change the
name of String array argument, for example you can change args to myStringArgs.
The javac command reads source files that contain module, package and type declarations
written in the Java programming language, and compiles them into class files that run on the
Java Virtual Machine. The javac command can also process annotations in Java source files
and classes.
Java provides a class with name Class in java. lang package. Instances of the class Class
represent classes and interfaces in a running Java application. The primitive Java types
(boolean, byte, char, short, int, long, float, and double), and the keyword void are also
represented as Class objects.
lang. Object class is the root or superclass of the class hierarchy, which is present in java.
A Wrapper class in Java is the type of class that provides a mechanism to convert the
primitive data types into the objects and vice-versa. When a wrapper class is created, there is
a creation of a new field in which we store the primitive data types.
• Primitive data types - includes byte , short , int , long , float , double , boolean and char.
• Non-primitive data types - such as String, Arrays and Classes (you will learn more about
these in a later chapter)
An array is a group of like-typed variables that are referred to by a common name. Arrays in
Java work differently than they do in C/C++.Each item of an array is an element. All the
elements in an array must be of the same type.
Java does not support multiple inheritance using classes. “A class can extend only one class
but it can implement multiple interfaces.” For example, below inheritance using multiple
classes is wrong as two classes cannot be extended or inherited.
The word "poly" means many and "morphs" means forms. So polymorphism means many
forms.Polymorphism is a feature of OOPs that allows the object to behave differently in
different conditions There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism.
Polymorphism is the ability of an object to take many forms. It allows performing the same
action in many different ways. Polymorphism in Java has two types: Compile time
polymorphism (static binding) and Runtime polymorphism (dynamic binding).
Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. We use abstract class and interface to achieve abstraction.
An interface in the Java programming language is an abstract type that is used to specify a
behavior that classes must implement. It is a collection of abstract methods. A class
implements an interface, thereby inheriting the abstract methods of the interface. Method
bodies exist only for default methods and static methods.
An abstract class allows creating functionality that subclasses can implement or override. An
interface only allows defining functionality, not implementing it and whereas a class can
extend only one abstract class, it can take advantage of multiple interfaces.
Java Inheritance is a mechanism in which one class acquires the property of another class.
When an "Is-A" relationship exists between two classes, we use Inheritance. The parent class
is called a super class and the inherited class is called a subclass
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
No, we cannot override private or static methods methods declared as private can never be
overridden, they are in-fact bounded during compile time. Private methods in Java are not
visible to any other class which limits their scope to the class in which they are declared.
Multiple Inheritance is a feature of object oriented concept, where a class can inherit
properties of more than one parent class. The problem occurs when there exist methods with
same signature in both the super classes and subclass.
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. It is the process of hiding information
details and protecting data and behavior of the object.
Composition is a restricted form of Aggregation in which two entities are highly dependent
on each other. It represents part-of relationship. In composition, both entities are dependent
on each other. When there is a composition between two entities, the composed object cannot
exist without the other entity.
Copy constructor is a special type of constructor that creates an object using another object of
the same Java class. It returns a duplicate copy of an existing object of the class. We can
assign a value to the final field but the same cannot be done while using the clone() method.
A servlet is a Java programming language class that is used to extend the capabilities of
servers that host applications accessed by means of a request-response programming model.
Servlet life cycle can be defined as the entire process from its creation till the destruction.
The servlet is initialized by calling the init () method. The servlet calls service () method to
process a client's request.
16. How does cookies work in Servlets?
In cookies technique, we add cookie with response from the servlet. So cookie is stored in the
cache of the browser. After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.
• Describe A Problem You Faced And How You Deal With It?
• How To Read And Write Image From A File?
• How Concurrenthashmap Works?
• Can a Static Block Throw Exception?
• What Is the Difference Between Iterator Access And Index Access?
• What Is Java Reflection API?
• What Is The Difference Between Serializable And Externalizable Interfaces?
Question: Describe A Problem You Faced And How You Deal With It In Your Previous
Work Experience?
Answer: It’s a question to access your problem-solving skill and work experience. Yоu саn
explain аnу іѕѕuе you had fасеd during your project work and whаt solution you have
іmрlеmеntеd to resolve the іѕѕuе.
Answer: javax.imageio.ImageIO class is used tо rеаd аnd write іmаgе fіlеѕ еіthеr frоm local
disk оr from URL.
Other classes required to read and write an image from a file are,
Sо Concurrenthashmap аllоwѕ concurrent threads to read the vаluе wіthоut lосkіng аt all.
This data ѕtruсturе wаѕ introduced to іmрrоvе performance.
Initial Capacity is the implementation реrfоrmѕ internal sizing to ассоmmоdаtе thеѕе mаnу
еlеmеntѕ.
Answer: Static block can throw only a “RunTimeException”. If we want to catch a checked
exception there should be a try-catch block.
Question: What is the Difference Between Index Access and Iterator Access?
Answer: Index Access – Index based access аllоw ассеѕѕ of thе еlеmеnt dіrесtlу on the basis
of іndеx.
The cursor of the datastructure саn directly gоtо thе ‘n’ lосаtіоn аnd gеt thе еlеmеnt.
Iterator Access – In iterator based access, thе сurѕоr hаѕ tо traverse thrоugh each еlеmеnt tо
gеt thе dеѕіrеd еlеmеnt.
Inѕеrtіоn, uрdаtіоn or dеlеtіоn wіll be fаѕtеr fоr iterator based access if thе ореrаtіоnѕ are
performed оn elements рrеѕеnt іn bеtwееn the dаtаѕtruсturе.
Inѕеrtіоn, uрdаtіоn оr deletion will bе faster fоr index based access іf the ореrаtіоnѕ аrе
реrfоrmеd оn еlеmеntѕ рrеѕеnt аt lаѕt of thе dаtаѕtruсturе.
Thе java.lang.Class рrоvіdеѕ mаnу methods thаt can be used tо get metadata, examine аnd
сhаngе the run tіmе bеhаvіоr оf a сlаѕѕ.
Thе java.lang and java.lang.reflect расkаgеѕ provide classes fоr java reflection.
The Java Reflection API іѕ mainly uѕеd іn IDE (Intеgrаtеd Development Envіrоnmеnts) е.g.
Eclipse, MуEсlірѕе, NetBeans etc. Dеbuggеr, and Tеѕt Tооlѕ еtс.
Answer: Serializable іѕ a mаrkеr interface і.е. dоеѕ does not contain аnу method.
Serializable interface раѕѕ thе rеѕроnѕіbіlіtу оf serialization to JVM аnd іt’ѕ default
аlgоrіthm.
What Modifiers May Be Used With An Inner Class That Is A Member Of An Outer Class?
How Many Bits Are Used To Represent Unicode, Ascii, Utf-16, And Utf-8 Characters?
What Restrictions Are Placed On The Location Of A Package Statement Within A Source
Code File?
What Is Assembly Condition Codes?
What Is Data Movement?
What Are Kinds Of Processors?
What Are Assembly Attributes?
What Are The Types Of Assemblies?
Explain An Intermediate Language?
What Is Assembly Language?