Java Basic Interview Questions for freshers
I have shared 50 important JAVA interview questions for freshers.
Questions marked with * are most repeated interview questions. JAVA
Interviewers mostly ask these questions to JAVA freshers to evaluate their
familiarity with JAVA language and OOP concepts.
*Q1. What do you understand by Java virtual machine
(JVM)?
JVM is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.
Q2. What do you understand by Java
Development Kit (JDK)?
JDK is an acronym for Java Development Kit. It is a software development
environment which is used to develop Java applications. It contains JRE +
development tools. JDK is an implementation of any one of the below given Java
Platforms released by Oracle Corporation:
- Standard Edition Java
Platform
- Enterprise Edition Java
Platform
- Micro Edition Java Platform
Q3. What do you understand by Java Runtime Environment (JRE)?
JRE stands for Java Runtime Environment. It is the implementation of JVM.
The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment. It
is the implementation of JVM. It physically exists. It contains a set of
libraries + other files that JVM uses at runtime.
*Q4. List the features of the Java Programming
language?
Features of the
Java Programming language are:
Simple: Java is easy to learn. The syntax of Java is
easy to understand.
Object-Oriented: Java is an object-oriented language which allows us
to maintain our code as the combination of different type of objects that
mainly focuses on both data and behaviour.
Platform Independent: Java is a platform independent programming
language. It is different from other programming languages like C and C++ which
needs a platform to be executed. Java comes with its platform on which its code
is executed. Java doesn't depend upon the operating system to be executed.
Architecture Neutral: Java is architectural neutral as it is not
dependent on the architecture. In C, the size of data types may vary according
to the architecture (32 bit or 64 bit) which doesn't exist in Java.
Portable: Java supports read-once-write-anywhere
approach. We can execute the Java program on every machine. Java program
(.java) is converted to bytecode (.class) which can be easily run on every
machine.
Secured: Java is secured because it doesn't use
explicit pointers. Java also provides the concept of Byte Code and Exception
handling which makes it more secured.
Robust: Java is a strong programming language as it
uses strong memory management. The concepts like Automatic garbage collection,
Exception handling, etc. make it more robust.
Multithreaded: We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web applications,
etc.
Distributed: Java is distributed because it facilitates
users to create distributed applications in Java. RMI and EJB are used for
creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.
Dynamic: Java is a dynamic language. It supports
dynamic loading of classes. It means classes are loaded on demand. It also
supports functions from its native languages, i.e., C and C++.
Q5. Why Java is called
'write once and run anywhere’?
Java compiler converts the
Java programs into the class file which contains byte code. Bytecode is the
intermediate language between source code and machine code. This bytecode is
not platform specific and can be executed on any platform or operating system.
*Q6. What is the constructor in Java? What are
different types of constructors used in Java?
The constructor can be defined as the special type of method that is
used to initialize the state of an object. It is invoked when the class is
instantiated, and the memory is allocated for the object. Every time, an object
is created using the new keyword, the default constructor of
the class is called. The name of the constructor must be similar to the class
name. The constructor must not have an explicit return type.
1. Default Constructor: default constructor is the one which does not
accept any value. The default constructor is mainly used to initialize the
instance variable with the default values. It can also be used for performing
some useful tasks on object creation. A default constructor is invoked
implicitly by the compiler if there is no constructor defined in the class.
2. Parameterized
Constructor: The
parameterized constructor is the one which can initialize the instance
variables with the given values. In other words, we can say that the
constructors which can accept the arguments are called parameterized
constructors.
*Q7. What is Copy constructor in Java?
There is no copy constructor in java. However, we can copy the values
from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in
java. They are:
- By constructor
- By assigning the values of
one object into another
- By clone () method of
Object class
In this example, we are going to copy the values of one object into another using java constructor.
package com.nomaan.test;
class Employee {
int empId;
String empName;
// constructor to
initialize employee id and employee name
Employee (int i, String
name)
{
empId = i;
empName =
name;
}
// Copy Constructor
Employee (Employee e)
{
empId =
e.empId;
empName =
e.empName;
}
void display()
{
System.out.println(empId
+ " " + empName);
}
public static void main
(String args[])
{
Employee e1
= new Employee (111, "Karan");
Employee e2
= new Employee(e1); // Copy Constructor
e1.display
();
e2.display ();
}
}
In Above example values of first Employee Object e1 are copied
in to e2.
*Q8. What are the various access specifiers in
Java?
In Java, access specifiers are the keywords which are used to define the
access scope of the method, class, or a variable. In Java, there are four
access specifiers given below.
1. Public: The classes, methods, or
variables which are defined as public, can be accessed by any class or method.
2. Protected: can be accessed by the class of the same package, or by the sub-class
of this class, or within the same class.
3. Default: is accessible within the package only. By default, all the classes,
methods, and variables are of default scope.
4. Private: The class, methods, or variables defined as private can be
accessed within the class only.
Q9. What is the Inheritance in JAVA?
Inheritance is a one of the four pillars of OOP by which one object
acquires all the properties and behaviour of another object of another class.
It is used for Code Reusability and Method Overriding. The idea behind
inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in
your current class also. Inheritance represents the IS-A relationship which is
also known as a parent-child relationship.
There are five types of inheritance in Java.
- Single-level inheritance
- Multi-level inheritance
- Multiple Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Multiple inheritance is not supported in Java through class.
*Q10. What is Aggregation in JAVA?
What is Has-a Relationship in JAVA?
Aggregation can be defined as the relationship between two classes where
the aggregate class contains a reference to the class it owns. Aggregation is
best described as a has-a relationship. For example, The
aggregate class Employee having various fields such as age, name, and salary
also contains an object of Address class having various fields such as
Address-Line 1, City, State, and pin-code. In other words, we can say that
Employee (class) has an object of Address class. Consider the following
example.
package com.nomaan.test;
public class Employee {
int id;
String name;
Address address;
public Employee(int id,
String name, Address address) {
this.id =
id;
this.name =
name;
this.address
= address;
}
void display() {
System.out.println(id
+ " " + name);
System.out.println(address.city
+ " " + address.state + " " + address.country);
}
public static void
main(String[] args) {
Address
address1 = new Address("Nashik", "Maharashtra",
"India");
Address
address2 = new Address("Mumbai", "Maharashtra",
"India");
Employee e1
= new Employee(111, "varun", address1);
Employee e2
= new Employee(112, "arun", address2);
e1.display()
e2.display()
}
}
public class Address {
String city, state,
country;
public Address(String city, String
state, String country) {
this.city =
city;
this.state
= state;
this.country
= country;
}
}
In above Program Employee Has-a Address. There is Has-a relationship between Employee class and Address class.
Q11. What is composition in JAVA?
Composition is nothing but a particular case of aggregation in
which a stronger relationship between two objects is shown.
More specifically when one class holds the reference of some other class
is known as composition. When an object of a class contains an object of some
other class, if the contained object cannot exist without the existence of
container object, then it is called composition.
Example: A class Class contains students (Student
Class Objects). A student cannot exist without a class. There exists
composition between class Class and Student class.
*Q12. What is the difference between aggregation
and composition?
Aggregation represents the weak relationship between objects whereas
composition represents the strong relationship between objects.
Aggregation implies a relationship where the contained class can exist
independently of the Container class.
Composition implies a relationship where the contained class cannot
exist independent of the Container class.
For example, the bike has an indicator (aggregation), but the bike has
an engine (composition).
Q13. Explain this keyword in java?
The this keyword is a reference variable that refers to
the current object. There are the various uses of this keyword
in Java. It can be used to refer to current class properties such as instance
methods, variable, constructors, etc. It can also be passed as an argument into
the methods or constructors. It can also be returned from the method as the
current class instance.
Q14. What is super in java?
The super keyword in Java is a reference variable that
is used to refer to the immediate parent class object. Whenever you create the
instance of the subclass, an instance of the parent class is created implicitly
which is referred by super reference variable.
There are the following uses of super keyword.
- super can be used to refer to
the immediate parent class instance variable.
- super can be used to invoke
the immediate parent class method.
- super() can be used to invoke
immediate parent class constructor.
*Q15. What are the differences between this and super
keyword?
Following are the differences between this and super keyword.
- The super keyword
always points to the parent class contexts whereas this keyword
always points to the current class context.
- The super keyword
is primarily used for initializing the base class variables within the
derived class constructor whereas this keyword primarily
used to differentiate between local and instance variables when passed in
the class constructor.
- The super and
this must be the first statement inside constructor
otherwise the compiler will throw an error.
*Q16. What is the purpose of static methods and
variables?
Static methods or variables are defined to be shared among all the
objects of the class. The static is the part of the class and not of the
object. The static variables are stored in the class area, and we do not need
to create the object to access such variables. Therefore, static is used in the
case, where we need to define variables or methods which are common to all the
objects of the class.
For example, In the Student class the name of the college is the common
attribute to all the students. Therefore, the college name will be defined
as static.
Q17. What is the static method?
- A static method belongs to the class rather than the object.
- There is no need for object creation to call the static
methods.
- A static method can access and change the value of the static
variable.
- The static method can not use non-static data member or call the
non-static method directly.
- this and super are non static hence they cannot be used in static context
*Q18. What is the static block?
Static block is used to initialize the static data member. It is
executed before the main method, at the time of class loading.
class Test{
static{
System.out.println("This is an example of static block..");
}
public static void main(String args[])
{
System.out.println("Hello
from main method..");
}
}
*Q.19 What is Data Abstraction in JAVA?
Data abstraction is the process of hiding certain details and
showing only essential information to the user. Abstraction is one of the four
pillars of OOP.
Abstraction can be achieved with either abstract classes or interfaces
in JAVA.
*Q20. What do you mean by Interface in JAVA?
An interface is a collection of abstract methods. A class implements an
interface in order to inherit the abstract methods of the interface.
- Interface
cannot be instantiated
- An
interface does not contain any constructors.
- All of
the methods in an interface are abstract.
- All
the variables in interface are public, static and final
*Q21. What do you mean by Abstract Class?
Abstract
classes cannot be instantiated and are either partially implemented or not at
all implemented. This class contains one or more abstract methods which are
simply method declarations without a body.
If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.
*Q22. Difference between Abstract Class and Interface.
1. To create an
abstract class abstract keyword is used in JAVA and we can
also use abstract with methods without body. To create
Interface We use interface keyword in JAVA but interface keyword
can not be used with methods. In fact methods in interface are are by
default abstract.
2.
Abstract classes
can be extended by child classes and child class should override all abstract
methods present in abstract class.
3.
Child classes
use extends keyword to extend an abstract class on the other
hand in order to use an interface child classes must implement the interface
using implements keyword and it should provide implementation
for all the methods declared in the interface.
4. Abstract classes
can have methods with implementation whereas interface provides only abstract
methods and can’t have any method implementations. Java version 8
onwards, we can create default and static methods in interface that contains
the method implementations.
5.
Abstract classes
can have constructors but interfaces can’t have constructors.
6. Abstract class
have all the features of a normal java class except that we can’t instantiate
it. We can use abstract keyword to make a class abstract but
interfaces are a completely different type and can have only public static
final constants and method declarations.
7.
Abstract classes methods
can have access modifiers as public, private, protected, static but interface
methods are implicitly public and abstract, we can’t use any other access
modifiers with interface methods.
8.
A child class can
extend only one abstract class since multiple inheritance is not supported in
JAVA but it can implement multiple interfaces.
9.
Abstract classes
can extend other class and implement interfaces but interface can only extend
other interfaces.
10.Abstract class can have main() method but interface doesn't have
main method implementation.
*Q23. Explain Polymorphism in JAVA?
Polymorphism in JAVA allows us to perform the same action in many
different ways. It refers to the ability of a class to provide
different implementations of a method.
For Example.
Method Overloading and Method Overriding
*Q24. Method Overloading Vs Method Overriding.
Method Overloading:
1.
Method overloading
is the example of compile time polymorphism.
2.
Method overloading is
performed within class.
3. In
method overloading, methods must have the same name and different
signatures. Method can't be
overloaded just by changing return type of the method.
4.
Argument list
should be different while doing
method overloading.
5.
Return type can be
same or different in Method
Overloading.
6.
Private and final
methods can be overloaded.
Method Overriding:
1.
Method overriding
is the example of run time polymorphism.
2.
Method overriding
occurs in two classes that have IS-A (inheritance) relationship.
3.
In method overriding, methods must have the
same name and same signature.
4.
Argument list should be same in method
overriding.
5.
Return type must
be same or covariant in method
overriding.
6. Private and final methods can’t be overridden.
*Q25. Explain Encapsulation in JAVA?
In OOP Encapsulation refers to integrating data variables and
methods into a single unit called Class. In encapsulation, variables of one
class are hidden from other classes and can only be accessed by the methods of
the class in which they are found.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our code.
*Q26. Explain Garbage Collection in JAVA.
In terms of JAVA, garbage refers to unreferenced or unused objects.
Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
In C language we were using free() function in C++ delete()
function is used. But, in java it is performed automatically. So, java provides
better memory management.
Garbage Collection makes java memory
efficient because garbage collector removes the unreferenced objects from
heap memory. It is automatically done by the garbage collector so we
don't need to make extra efforts.
1.Final:
- final is a keyword.
- It is
used to apply restrictions on classes, methods and variables.
- If a
class is declared as final then It can’t be inherited.
- If a
method is declared as final then It can’t be overridden.
- final
variable must be initialized when it is being declared.
- Value
of final variable once declared, can’t be changed or re-initialized.
2.Finally:
- finally is a block.
- It is
used to place important code in this block.
- It
gets executed irrespective of whether the exception is handled or not.
3.Finalize:
- finalize() is a method.
- It is
used to perform clean up processing right before the object is collected
by garbage collector.
- Clean-up activity means closing the resources associated with that object like
Database Connection, Network Connection.
*Q29. What is Exception in JAVA? What are checked and unchecked Exceptions?
An exception is a
problem that arises during the execution of a program. In other words it
is an event, which occurs during the execution of a program, that disrupts
the normal flow of the program.
Checked exceptions in Java are predictable, erroneous situation that can occur in a JAVA program which are checked at compile time by the compiler. For example, if a developer tries to access a file, then he may or may not find the file at provided path, this situation forces developer to deal with the checked FileNotFoundException. Compiler complains at compile time and forces the developer to handle them using try-catch or throws keyword.
Unchecked exceptions are not verified or checked by the compiler at compile-time hence they are called unchecked exception. An unchecked exception is the one which occurs at the time of execution.
Some common unchecked exceptions
in Java
ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException
and IllegalArgumentException.
*Q30. Differentiate between Error
and Exception.
Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or handled. It indicates a serious problem. It occurs at run time. they belong to an unchecked type.
For Example: OutOfMemoryError, LinkageError etc. are the subclasses of the Error class.
Exceptions are the problems which
can occur at runtime and compile time. It mainly occurs in the code written by the
developers. It can be recovered by using the try-catch block and
throws keyword. There are two types of exceptions i.e. checked and unchecked.
For Example: FileNotFoundException,ArithmeticException,NullPointerException, ArrayIndexOutOfBoundsException and IllegalArgumentException.
Q31. Can we write only try block without catch
and finally blocks?
No, It shows compilation error. The try block must be followed by either catch or finally block. You can remove either catch block or finally block but not both.
try{
}catch(Exception e)
{
}
finally{
}
2.
try{
}catch(Exception e)
{
3.
try{
}
finally{
}
*Q32. When do we get unreachable catch block error?
When there are multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e sub classes of Exception must come first and super classes must come later. If you keep super classes first and sub classes later, compiler will show unreachable catch block error.
{
public static void main(String[]
args)
{
try
{
int i =
Integer.parseInt("test"); //This statement will throw
NumberFormatException
}
catch(Exception ex)
{
System.out.println("This block handles all types of exception");
}
catch(NumberFormatException
ex)
{
/*Here We
will get compile time error as this block becomes unreachable
since exception is already caught by above catch block*/
}
}
}
*Q33.What is the difference between ClassNotFoundException and NoClassDefFoundError in Java?
ClassNotFoundException is a checked exception which is thrown when an application tries to load a class at run time using Class.forName() or loadClass() or findSystemClass() methods and the class with specified name are not found in the classpath. For example, this exception occurs when you try to connect to MySQL or Oracle databases and you have not updated the classpath with required JAR files. In most of time, this exception occurs when you try to run an application without updating the classpath with required JAR files.
For example, below program will throw ClassNotFoundException if the mentioned class “com.microsoft.sqlserver.jdbc.SQLServerDriver” is not found in the classpath.
public class ConnectionDemo
{
public static void main(String[]
args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch
(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
NoClassDefFoundError is an error which is thrown when Java Runtime System tries to load the definition of a class and class definition is no longer available. The required class definition was present at compile time but it is missing at run time.
Two .class files will
be generated. One is TestClass1.class and another one is TestClass2.class.
If you remove the TestClass1.class file and run the TestClass2.class file,
Java will throw NoClassDefFoundError.
class TestClass1
{
}
public class TestClass2
{
public static void main(String[]
args)
{
TestClass1 test = new
TestClass1();
}
}
at TestClass2.main(TestClass2.java:10)
Caused by: java.lang.ClassNotFoundException: TestClass1
at
java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at
java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
- The exceptions which occur at run time are called as run time
exceptions. These exceptions are unknown to compiler.
- All sub classes of java.lang.RunTimeException and java.lang.Error are
run time exceptions.
- These exceptions are unchecked type of exceptions. For example, NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOfBoundException, StackOverflowError etc.
Q35. What is the use of throws keyword in Java?
If a method is capable of throwing an exception
that it could not handle, then it should specify that exception using throws keyword.
It helps the callers of that method in handling that exception.
The syntax for using throws keyword:
{
}
where, list_of_exceptions is the list of exceptions that method may throw. Exceptions are separated by commas.
throw is a keyword in java which is used to throw an exception manually. Using throw keyword, wecan throw an exception from any method or block. But, that exception must be of type java.lang.Throwable class or it’s sub classes. Below example shows how to throw an exception using throw keyword.
public
static void main(String[] args) {
try
{
m1();
}
catch (Exception e) {
e.printStackTrace();
}
}
static
void m1() throws Exception {
Exception
e = new Exception();
throw
e; // throwing an exception explicitly using 'throw'
}
}
throws is also a keyword in java which is used in the method signature to
indicate that this method may throw mentioned exceptions. The caller to such
methods must handle the mentioned exceptions either using try-catch blocks or
using throws keyword.
Please refer to above program it catches exception thrown by m1() method.
Throwable is a super class for all types of errors and exceptions in java. This class is a member of java.lang package. Only instances of this class or it’s sub classes are thrown by the java virtual machine or by the throw statement. The only argument of catch block must be of this type or it’s sub classes. If you want to create your own customized exceptions, then your class must extend this class.
package com.nomaan.test;
class MyTestException extends Throwable {
//
Customized Exception class
}
class ThrowAndThrowsExample {
static
void m1() throws MyTestException {
MyTestException e = new MyTestException();
throw
e;
}
public
static void main(String[] args) {
try {
m1();
}
catch (MyTestException e) {
e.printStackTrace();
}
}
}
Output of above program:
com.nomaan.test.MyTestException
at
com.nomaan.test.ThrowAndThrowsExample.m1(test.java:9)
at com.nomaan.test.ThrowAndThrowsExample.main(test.java:16)
*Q37. Can we override a parent class
method which is throwing an unchecked exception with checked exception in
the child class?
No. If a parent class method is throwing an unchecked exception, then it can be overridden in the child class with same exception or any other unchecked exceptions but can not be overridden with checked exceptions.
Please refer following code snippet
package com.nomaan.test;
class TestException {
static
void m1() throws NullPointerException {
}
}
class MyTest extends TestException{
static
void m1() throws ArrayIndexOutOfBoundsException {
}
public static void main(String[] args) {
try
{
m1();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
In above code snippet when I have overridden m1() method which originally throws NullPointerException(unchecked exception) in Parent class with ArrayIndexOutOfBoundsException (unchecked exception) in child class it compiles fine without any error.
But when I replace ArrayIndexOutOfBoundsException
(unchecked exception) in child class with FileNotFoundException
(checked exception) then this time compiler complains and gives a
compile time error.
Please try following example and run it yourself.
class TestException {
static
void m1() throws NullPointerException {
}
}
class MyTest extends TestException{
static
void m1() throws FileNotFoundException {
}
public
static void main(String[] args) {
try
{
m1();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
*Q38. Explain the term Wrapper Classes in JAVA.
These are classes that allow primitive types to be
accessed as objects. Example: Integer, Character, Double, Boolean etc.
The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.
Q39. Explain Class class in JAVA.
The Class class is used to obtain information about an object's design and java.lang.Class class instance represent classes, interfaces in a running Java application.
*Q40. Explain Serialization and Deserialization in JAVA.
Serialization is the process of converting an object into a
stream of bytes to store the object or transmit it to memory, a database, or a
file. Its main purpose is to save the state of an object in order to be able to
recreate it when needed. The reverse process is called deserialization.
It is mainly used in Hibernate, RMI, JPA, EJB and
JMS technologies.
Deserialization is the reverse operation of serialization where byte-stream is
converted into an object. The serialization and deserialization process
is platform-independent, it means you can serialize an object on
one platform and deserialize it on a different platform.
For serializing the object, we call the writeObject() method
of ObjectOutputStream class, and for deserialization we call
the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface
for serializing the object.
Please execute following sample program which demonstrate Serialization
process.
package com.nomaan.test;
import java.io.Serializable;
public class Employee implements Serializable {
int empId;
String empName;
public Employee(int id,
String name) {
this.empId
= id;
this.empName
= name;
}
}
import java.io.*;
public class SerializationDemo {
public static void
main(String args[]) {
try {
//
Creating the object
Employee
e1 = new Employee(211, "Nomaan");
//
Creating stream and writing the object
FileOutputStream
fout = new FileOutputStream("File.txt");
ObjectOutputStream
out = new ObjectOutputStream(fout);
out.writeObject(e1);
out.flush();
//
closing the stream
out.close();
System.out.println("Object
written successfully in File.txt");
} catch
(Exception e) {
System.out.println(e);
}
}
}
Lets Demonstrate Deserialization process now.
import java.io.*;
public class DeserializationDemo {
public static void
main(String args[]) {
try {
//
Creating stream to read the object
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("File.txt"));
Employee
e = (Employee) in.readObject();
//
printing the data of the serialized object
System.out.println(e.empId
+ " " + e.empName);
//
closing the stream
in.close();
} catch
(Exception e) {
System.out.println(e);
}
}
}
Please write and execute above program to better understand both
Serialization and Deserialization.
*Q41. What is transient variable?
A transient variable is a variable that may not be serialized during
Serialization and which is initialized by its default value during
de-serialization.
In short, If you don't want to serialize any data member of a class, you
can mark it as transient.
class Employee implements Serializable{
transient int EmpId;
String empName;
public Employee(int id, String name) {
this.EmpId = id;
this.empName = name;
}
}
As a result of above program empId will not be
serialized as it was declared as transient, so when you deserialize
the object after serialization, you will not get the value of id. It will
return default value always. In such case, it will return 0 because
the data type of id is an integer.
Q42. Explain Multithreading in JAVA.
Multithreading is a process of
executing multiple threads simultaneously. Multithreading is used to obtain the
multitasking. It consumes less memory and gives the fast and efficient
performance. Its main advantages are:
Multithreading programming has the following advantages:
- Multithreading allows the faster
execution of tasks, as threads execute independently.
- Multithreading provides better
utilization of cache memory as threads share the common memory resources.
- Multithreading reduces the number of the
required server as one server can execute multiple threads at a time.
*Q43. Explain thread lifecycle.
A thread can have one of the
following states during its lifetime:
1. New: In this state, a Thread class object is created using a new
operator, but the thread is not alive. Thread doesn't start until we call
the start() method.
2. Runnable: In this state, the thread is ready to run after calling the start()
method. However, the thread is not yet selected by the thread
scheduler.
3. Running: In this state, the thread scheduler picks the
thread from the ready state, and the thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive,
or it is waiting for the other thread to finish.
5. Dead/Terminated: A thread is in terminated or dead state when
the run() method exits.
*Q44. What do you understand Synchronization in JAVA?
Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.
*Q45. What is the purpose of wait() method in Java?
The wait() method is
provided by the Object class in Java. This method is used for
inter-thread communication in Java. The java.lang.Object.wait() is
used to pause the current thread, and wait until another thread does not call
the notify() or notifyAll() method. Its syntax is given below.
public final void
wait()
*Q46. What are
different ways of thread creation in JAVA?
The Thread can be created by using
two ways.
1. By extending the Thread class
2. By implementing the Runnable interface
However, the primary differences
between both the ways are given below:
- By extending the Thread class,
we cannot extend any other class, as Java does not allow multiple
inheritances while implementing the Runnable interface; we can
also extend other base class(if required).
- By extending the Thread class,
each of thread creates the unique object and associates with it while
implementing the Runnable interface; multiple threads share
the same object
- Thread class provides various inbuilt methods
such as getPriority(), isAlive() and many more while
the Runnable interface provides a single method,
i.e., run().
*Q47. What does join() method?
The join() method waits
for a thread to die. In other words, it causes the currently running threads to
stop executing until the thread it joins with completes its task. Join method
is overloaded in Thread class in the following ways.
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
public class MyThread extends Thread {
//overriding the run method
public
void run() {
for
(int i = 0; i < 2; i++) {
try
{
Thread.sleep(300);
System.out.println("The
current thread name is: " + Thread.currentThread().getName());
}
catch (Exception e) {
System.out.println("The
exception has been caught: " + e);
}
System.out.println(i);
}
}
}
public class ThreadJoinExample {
public static void main(String argvs[]) {
MyThread
t1 = new MyThread();
MyThread
t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start(); // thread t1 starts
try
{
System.out.println("The
current thread name is: " +
Thread.currentThread().getName());
//
starting t2 after t1 has ended or died.
t1.join();
// invoking the join() method
}
catch
(Exception e) {
System.out.println("The
exception has been caught " + e);
}
t2.start(); // thread t2 starts
try
{
System.out.println("The
current thread name is: " +
Thread.currentThread().getName());
//starting
thread t3 after t2 has ended or died.
t2.join();
}
catch
(Exception e) {
System.out.println("The
exception has been caught " + e);
}
t3.start();//
thread t3 starts
}
}
*Q48. What is Daemon Thread in Java?
Daemon thread in
Java is a service provider thread
that provides services to the user thread. When all the user threads dies, JVM
terminates this thread automatically.
This is a low-priority thread that runs in the background to
perform tasks such as garbage collection.
There are many java daemon threads
running automatically e.g. gc, finalizer etc.
It provides services to user
threads for background supporting tasks. It has no role in life than to serve
user threads. Its life depends on
user threads.
The java.lang.Thread class
provides two methods for java daemon thread.
public void setDaemon(boolean status)
public boolean isDaemon()
Please execute following program to
understand these methods better.
package com.nomaan.test;
public class DaemonThreadDemo extends
Thread {
public void run() {
if
(Thread.currentThread().isDaemon()) {// checking if current thread is daemon
thread
System.out.println(Thread.currentThread().getName() + " is a Daemon
Thread..");
}
else {
System.out.println(Thread.currentThread().getName() + " is a User
Thread..");
}
}
public static void main(String[] args) {
DaemonThreadDemo t1 = new
DaemonThreadDemo();
DaemonThreadDemo t2 = new
DaemonThreadDemo();
DaemonThreadDemo t3 = new
DaemonThreadDemo();
t1.setName("T1");
t2.setName("T2");
t3.setName("T3");
t1.setDaemon(true);// t1 is
set as daemon thread
t1.start();
t2.start();
t3.start();
}
}
Please note we can only create a daemon thread before starting the thread.
If we try to create a daemon thread after starting it, we will get IllegalThreadStateException
Q49. What is the difference
between notify() and notifyAll()?
The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.
*Q50. Describe the purpose and working of
sleep() method.
The sleep() method
in java is used to block a thread for a particular time, which means it pause
the execution of a thread for a specific time. There are two methods of doing
so.
When we call
the sleep() method, it pauses the execution of the current thread for
the given time and gives priority to another thread(if available). Once the waiting time gets complete then previous thread
changes its state from waiting to runnable and comes in running state.
There are 2 method signatures as
follows:
public static void sleep
(long milliseconds) throws InterruptedException
public static void sleep
(long milliseconds, int nanos) throws InterruptedException
===========================================================================
Please Note these
are questions for freshers (0-2 Years) who are pursuing their careers in JAVA
Development. There are many more complex questions in JAVA that usually asked
to senior JAVA developers who have already gain some experience (3-10 Years)
in JAVA. I will be sharing more interview questions for experienced JAVA
developers in future.
Stay tuned and keep
growing!!
Comments
Post a Comment