Java Interview Questions
Java Interview Questions
Java Interview Questions
Interview Question
Ans: Java is one the most famous and most used language in the real world,
there are many features in Java that makes it better than any other language
some of them are mentioned below..
©Topperworld
Q 3. What is JVM?
©Topperworld
Q 4. What is JIT?
Ans:
©Topperworld
4) The JIT compiler is enabled throughout, while it gets activated when a
method is invoked. For a compiled method, the JVM directly calls the
compiled code, instead of interpreting it.
5) As JVM calls the compiled code that increases the performance and
speed of the execution.
Ans :
©Topperworld
Q 6.Difference between JVM, JRE, and JDK.
Ans: JVM: JVM also known as Java Virtual Machine is a part of JRE. JVM is a
type of interpreter responsible for converting bytecode into machine-
readable code. JVM itself is platform dependent but it interprets the
bytecode which is the platform-independent reason why Java is platform-
independent.
JRE: JRE stands for Java Runtime Environment, it is an installation package
that provides an environment to run the Java program or application on any
machine.
JDK: JDK stands for Java Development Kit which provides the environment to
develop and execute Java programs. JDK is a package that includes two
things Development Tools to provide an environment to develop your Java
programs and, JRE to execute Java programs or applications.
Q 7.What is a classloader?
class file classloader is responsible for dynamically loading the java classes
and interfaces to JVM(Java Virtual Machine).
Because of classloaders Java run time system does not need to know about
files and file systems.
Ans :
©Topperworld
Basis C++ Java
©Topperworld
Basis C++ Java
Ans : A Java String Pool is a place in heap memory where all the strings
defined in the program are stored. A separate place in a stack is there where
the variable storing the string is stored. Whenever we create a new string
object, JVM checks for the presence of the object in the String pool, If String
is available in the pool, the same object reference is shared with the variable,
else a new object is created.
©Topperworld
Example:
String str1="Hello";
// "Hello" will be stored in String Pool
// str1 will be stored in stack memory
Ans: We can declare the main method without using static and without
getting any errors. But, the main method will not be treated as the entry
point to the application or the program.
Ans : Unlike any other programming language like C, C++, etc. In Java, we
declared the main function as a public static void main (String args[]). The
meanings of the terms are mentioned below:
1) public: the public is the access modifier responsible for mentioning
who can access the element or the method and what is the limit. It is
responsible for making the main function globally available. It is made
public so that JVM can invoke it from outside the class as it is not present
in the current class.
2) static: static is a keyword used so that we can use the element without
initiating the class so to avoid the unnecessary allocation of the
memory.
3) void: void is a keyword and is used to specify that a method doesn’t
return anything. As the main function doesn’t return anything we use
void.
4) main: main represents that the function declared is the main function.
It helps JVM to identify that the declared function is the main function.
5) String args[]: It stores Java command-line arguments and is an array
of type java.lang.String class.
©Topperworld
Q 12. What are the advantages of Packages in Java?
©Topperworld
Q 14. When a byte datatype is used?
Ans :
©Topperworld
Instance Variable Local Variable
Ans : In Java When we haven’t initialized the instance variables then the
compiler initializes them with default values. The default values for
instances and variables depend on their data types. Some common types of
default data types are:
➢ The default value for numeric types (byte, short, int, long, float, and
double) is 0.
➢ The default value for the boolean type is false.
➢ The default value for object types (classes, interfaces, and arrays) is null.
©Topperworld
Example:
import java.io.*;
class TW {
static byte b;
static int i;
static long l;
static short s;
static boolean bool;
static char c;
static String str;
static Object object;
static float f;
static double d; static int[] Arr;
public static void main(String[] args) {
System.out.println("byte value" + b);
System.out.println("short value" + s);
System.out.println("int value" + i);
System.out.println("long value" + l);
System.out.println("boolean value" + bool);
System.out.println("char value" + c);
System.out.println("float value" + f);
System.out.println("double value" + d);
System.out.println("string value" + str);
System.out.println("object value" + object);
System.out.println("Array value" + Arr);
}
}
©Topperworld
Output:
byte value0
short value0
int value0
long value0
boolean valuefalse
char value
float value0.0
double value0.0
string valuenull
object valuenull
Array valuenull
Ans : The wrapper class is an object class that encapsulates the primitive
data types, and we need them for the following reasons:
1. Wrapper classes are final and immutable
2. Provides methods like valueOf(), parseInt(), etc.
3. It provides the feature of autoboxing and unboxing.
©Topperworld
Q 19. What is a Class Variable?
Ans :
In Java, a class variable (also known as a static variable) is a variable that is
declared within a class but outside of any method, constructor, or block.
Class variables are declared with the static keyword, and they are shared by
all instances (objects) of the class as well as by the class itself. No matter
how many objects are derived from a class, each class variable would only
exist once.
Example:
Output:
©Topperworld
Q 20. What is the default value stored in Local Variables?
Ans : There is no default value stored with local variables. Also, primitive
variables and objects don’t have any default values.
Ans:
➢ Instance Variable :
A class variable without a static modifier known as an instance variable is
typically shared by all instances of the class.
These variables can have distinct values among several objects.
The contents of an instance variable are completely independent of one
object instance from another because they are related to a specific object
instance of the class.
©Topperworld
Example:
Output:
Name John
➢ Class Variable:
Class Variable variable can be declared anywhere at the class level using the
keyword static.
These variables can only have one value when applied to various objects.
These variables can be shared by all class members since they are not
connected to any specific object of the class.
©Topperworld
Example:
// Java Program to demonstrate Class Variable
import java.io.*;
class TW {
// class variable
private static final double PI = 3.14159;
private double radius;
public TW(double radius) { this.radius = radius; }
public double getArea() { return PI * radius * radius; }
public static void main(String[] args)
{
TW obj = new TW(5.0);
System.out.println("Area of circle: "
+ obj.getArea());
}
}
Output:
Ans : The static keyword is used to share the same variable or method of a
given class. Static variables are the variables that once declared then a
single copy of the variable is created and shared among all objects at the
class level.
©Topperworld
Q 23. What are the super most classes for all the streams?
Ans : All the stream classes can be divided into two types of classes that are
ByteStream classes and CharacterStream Classes.
The ByteStream classes are further divided into InputStream classes and
OutputStream classes. CharacterStream classes are also divided into Reader
classes and Writer classes.
The SuperMost classes for all the InputStream classes is java.io.InputStream
and for all the output stream classes is java.io.OutPutStream.
Similarly, for all the reader classes, the super-most class is java.io.Reader,
and for all the writer classes, it is java.io.Writer.
Ans : When we are working with the files or stream then to increase the
Input/Output performance of the program we need to use the
BufferedInputStream and BufferedOutputStream classes.
These both classes provide the capability of buffering which means that the
data will be stored in a buffer before writing to a file or reading it from a
stream.
It also reduces the number of times our OS needs to interact with the
network or the disk.
Buffering allows programs to write a big amount of data instead of writing it
in small chunks. This also reduces the overhead of accessing the network or
the disk.
©Topperworld
While working filter() it doesn’t actually perform filtering but instead
creates a new stream that, when traversed, contains the elements of initial
streams that match the given predicate.
Ans : The covariant return type specifies that the return type may vary in the
same direction as the subclass.
It is possible to have different return types for an overriding method in the
child class, but the child’s return type should be a subtype of the parent’s
return type and because of that overriding method becomes variant with
respect to the return type.
We use covariant return type because of the following reasons:
➢ Avoids confusing type casts present in the class hierarchy and makes the
code readable, usable, and maintainable.
➢ Gives liberty to have more specific return types when overriding
methods.
➢ Help in preventing run-time ClassCastExceptions on returns.
Ans :
Sleep() Wait()
The sleep() method belongs to the Wait() method belongs to the object
thread class. class.
Sleep does not release the lock that wait() release the lock which allows
©Topperworld
Sleep() Wait()
Mainly used to delay a thread for Mainly used to pause a thread until
some specific time duration. notified by another thread.
Ans :
String StringBuffer
©Topperworld
String StringBuffer
operations could be
performed on them.)
Ans :
StringBuffer StringBuilder
©Topperworld
Q 31. On which memory arrays are created in Java?
Ans : Arrays in Java are created in heap memory. When an array is created
with the help of a new keyword, memory is allocated in the heap to store the
elements of the array.
In Java, the heap memory is managed by the Java Virtual Machine(JVM) and it
is also shared between all threads of the Java Program.
The memory which is no longer in use by the program, JVM uses a garbage
collector to reclaim the memory.
Arrays in Java are created dynamically which means the size of the array is
determined during the runtime of the program.
The size of the array is specified during the declaration of the array and it
cannot be changed once the array is created.
Ans : In Java there are multiple ways to copy an Array based on the
requirements.
⚫ clone() method in Java: This method in Java is used to create a shallow
copy of the given array which means that the new array will share the
same memory as the original array.
int[] Arr = { 1, 2, 3, 5, 0};
int[] tempArr = Arr.clone();
⚫ arraycopy() method: To create a deep copy of the array we can use this
method which creates a new array with the same values as the original
array.
int[] Arr = {1, 2, 7, 9, 8};
int[] tempArr = new int[Arr.length];
System.arraycopy(Arr, 0, tempArr, 0, Arr.length);
⚫ copyOf() method: This method is used to create a new array with a
specific length and copies the contents of the original array to the new
array.
int[] Arr = {1, 2, 4, 8};
©Topperworld
int[] tempArr = Arrays.copyOf(Arr, Arr.length);
⚫ copyOfRange() method: This method is very similar to the copyOf()
method in Java, but this method also allows us to specify the range of
the elements to copy from the original array.
int[] Arr = {1, 2, 4, 8};
int[] temArr = Arrays.copyOfRange(Arr, 0, Arr.length);
Volatile keywords in Java can only be applied to individual variables but not
to arrays or collections.
The value of the Variable is always read from and written to the main
memory when it is defined as volatile rather than being cached in a thread’
s local memory.
This makes it easier to make sure that all threads that access the variable
can see changes made to it.
©Topperworld
Disadvantages of Arrays are:
©Topperworld
Object-Oriented Programming Object-Based Programming
Language Language
It supports all the built-in objects It doesn’t support all the built-in
objects
Ans :
©Topperworld
Static(Class) method Instance method
Static methods can be called using The instance method can be called
the class name only without creating on a specific instance of a class
an instance of a class. using the object reference.
This method can access only static This method can access both static
members of the class and non-static methods of the class.
Ans : The object is a real-life entity that has certain properties and methods
associated with it. The object is also defined as the instance of a class. An
object can be declared using a new keyword.
©Topperworld
Q 41. What are the advantages and disadvantages of object cloning?
Ans : There are many advantages and disadvantages of using object cloning
as mentioned below:
Advantages:
➢ In Java, the ‘=’ assignment operator cannot be used for cloning as it
simply creates a copy of reference variables. To overcome such
discrepancy the clone() method of Object class can be used over the
assignment operator.
➢ The clone() method is a protected method of class Object which means
that only the Employee class can clone Employee objects. This means no
class other than Employee can clone Employee objects since it does not
know the Employee class’ attributes.
➢ Code size decreases as repetition decreases.
Disadvantages:
➢ As the Object.clone() method is protected, so need to provide our own
clone() and indirectly call Object.clone() from it.
➢ If we don’t have any methods then we need to provide a Cloneable
interface as we need to provide JVM information so that we can perform
a clone() on our object.
Ans : There are a few advantages of passing this into a method instead of the
current class object itself these are:
⚫ this is the final variable because of which this cannot be assigned to any
new value whereas the current class object might not be final and can be
changed.
⚫ this can be used in the synchronized block.
©Topperworld
Q 43. What do you understand by copy constructor in Java?
Ans : Java constructors are used for initializing objects. During creation,
constructors are called to set attributes for objects apart from this few basic
differences between them are:
1) Constructors are only called when the object is created but other
methods can be called multiple times during the life of an object.
2) Constructors do return anything whereas other methods can return
anything.
3) Constructors are used to setting up the initial state but methods are
used to perform specific actions.
©Topperworld
Q 44. Give some features of the Interface.
Ans :
Errors Exceptions
Errors can occur at compile time as All exceptions occur at runtime but
©Topperworld
Errors Exceptions
well as run time. Compile Time: checked exceptions are known to the
Syntax Error, Run Time: Logical compiler while unchecked are not.
Error.
Ans : Runtime Exceptions are exceptions that occur during the execution of a
code, as opposed to compile-time exceptions that occur during compilation.
Runtime exceptions are unchecked exceptions, as they aren’t accounted
for by the JVM.
Examples of runtime exceptions in Java include:
⚫ NullPointerException: This occurs when an application attempts to use a
null object reference.
⚫ ArrayIndexOutOfBoundsException: This occurs when an application
attempts to access an array index that is out of bounds.
⚫ ArithmeticException: This occurs when an application attempts to divide
by zero.
©Topperworld
⚫ IllegalArgumentException: This occurs when a method is passed on an
illegal or inappropriate argument.
Unlike checked exceptions, runtime exceptions do not require a declaration
in the throws clause or capture in a try-catch block. However, handling
runtime exceptions is advisable in order to provide meaningful error
messages and prevent a system crash. Because runtime exceptions provide
more specific information about the problem than checked exceptions, they
enable developers to detect and correct programming errors more easily and
quickly.
Ans :
Checked Exception:
Checked Exceptions are the exceptions that are checked during compile time
of a program.
In a program, if some code within a method throws a checked exception,
then the method must either handle the exception or must specify the
exception using the throws keyword.
Checked exceptions are of two types:
) Fully checked exceptions: all its child classes are also checked, like
IOException, and InterruptedException.
) Partially checked exceptions: some of its child classes are unchecked,
like an Exception.
Unchecked Exception:
Unchecked are the exceptions that are not checked at compile time of a
program.
Exceptions under Error and RuntimeException classes are unchecked
exceptions, everything else under throwable is checked.
©Topperworld
Q 48. What will happen if you put System.exit(0) on the try or catch
block? Will finally block execute?
©Topperworld
➢ Scalability: Multithreading on multiple CPU machines increases
parallelism.
➢ Better Communication: Thread synchronization functions improves inter-
process communication.
➢ Utilization of multiprocessor architecture
➢ Minimized system resource use
ABOUT US
➢ Our Vision
❖ Our vision is to create a world where every college student can easily
access high-quality educational content, connect with peers, and achieve
their academic goals.
❖ We believe that education should be accessible, affordable, and
engaging, and that's exactly what we strive to offer through our platform.
©Topperworld
diverse array of online resources tailored to your specific college
curriculum.
❖ Whether you're studying science, arts, engineering, or any other
discipline, we've got you covered.
❖ Our platform hosts a vast library of e-books, quizzes, and interactive
study tools to ensure you have the best resources at your fingertips.
❖ Education is not just about textbooks and lectures; it's also about forming
connections and growing together.
❖ TopperWorld encourages you to engage with your fellow students, ask
questions, and share your knowledge.
❖ We believe that collaborative learning is the key to academic success.
©Topperworld
“Unlock Your
Potential”
With- Topper World
Explore More
topperworld.in
Follow Us On
E-mail
[email protected]