0% found this document useful (0 votes)
41 views16 pages

Java Interview Questions!!

This document discusses basics of Java including definitions of JDK, JRE and JVM. It also covers topics like why Java is platform independent, why it is not 100% object oriented, features of Java, local and global variables, static and non-static blocks, class and object loading, this and super keywords, constructors, method overloading vs overriding, upcasting and downcasting, variable and method shadowing, and difference between abstract class and interface. Questions related to the main method in Java are also provided along with answers.

Uploaded by

Prasad Deshmukh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
41 views16 pages

Java Interview Questions!!

This document discusses basics of Java including definitions of JDK, JRE and JVM. It also covers topics like why Java is platform independent, why it is not 100% object oriented, features of Java, local and global variables, static and non-static blocks, class and object loading, this and super keywords, constructors, method overloading vs overriding, upcasting and downcasting, variable and method shadowing, and difference between abstract class and interface. Questions related to the main method in Java are also provided along with answers.

Uploaded by

Prasad Deshmukh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

Rohit Gurunath Thakur

Email: trohit3459@gmail.com

Basics of java
1. Explain JDK, JRE and JVM?
[JDK=JRE+DE TOOLS] [JRE=JVM+INBUILT LIB] [JVM=JIT+ INTERPETRE]
JDK is a software development kit whereas JRE is a software bundle that allows Java program
to run, whereas JVM is an environment for executing bytecode. The full form of JDK is Java
Development Kit, while the full form of JRE is Java Runtime Environment, while the full form of
JVM is Java Virtual Machine

2. Why Java is platform independent?


Java is platform-independent because it does not depend on any type of platform. Hence, Java is
platform-independent language.
In Java, programs are compiled into byte code and that byte code is platform-independent.

3. Why java is not 100% Object oriented?


The object-oriented languages access data through message passing
There are 2 reasons
1st because of permeative data types
2nd because of static keyword java contains static variables and methods which can be accessed
directly without using objects.

4. Explain the Features of java?


 Simple: - the program can easily readable and recognizable by humans.
 Platform Independent: - we written program on one platform but we can run program on
any platform because of JVM
 WORA(Portable)
 Robust:- checks error twice compile time and run time so, code is virus free
Java is robust as it is capable of handling run-time errors, supports automatic garbage
collection and exception handling, and avoids explicit pointer concept.

Source -code compilerbyte-codeJVM-interpreter


 High Performance:- Java provides high performance with the use of “JIT – Just In Time
compiler”, in which the compiler compiles the code on-demand basis, that is, it compiles
only that method which is being called. This saves time and makes it more efficient.
Bytecodes generated by the Java compiler are highly optimized, so Java Virtual Machine can
execute them much faster.
 Object-Oriented programming language
 Secure:- java programs run inside JRE by JVM. Java supports access modifiers to check
memory access
 Multi-threaded :- one program can perform may tasks.
 Dynamic :- it allocates memory for program and automatically deletes after execution.

5. What is local variable and global variable?


local variable: - A local variable is created when the function is executed, and once the execution is
finished, the variable is destroyed.
global variable: - A global variable exists in the program for the entire time the program is executed.
It can be accessed throughout the program by all the functions present in the program.

6. What is static block and non-static block?


Static Block: -The static block executes at class loading time because it can contain only static
data that binds with class. So, there is no dependency on object creation.
Non-Static Block: -the non-static block (Instance block) executes when the object is created.
Because it can have non-static members that bind with the object.

7. What is class loading operation and object loading operation?


Java Classes aren’t loaded into memory all at once, but when required by an application. At
this point, the Java ClassLoader is called by the JRE and these ClassLoaders load classes into
memory dynamically.
8. What is this and super keyword?
super keyword is used to access methods of the parent class while this is used to access methods
of the current class. this is a reserved keyword in java i.e, we can't use it as an identifier. this is used
to refer current-class's instance as well as static members.
9. What are constructors in java?
A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created.
10. What is class and Objects?
class:
a class describes the contents of the objects that belong to it: it describes an aggregate of data
fields (called instance variables), and defines the operations (called methods).
object:
an object is an element (or instance) of a class; objects have the behaviors of their class. The
object is the actual component of programs, while the class specifies how instances are
created and how they behave.

Questions related to main method In Java


11. Why main method is a static method?
The main() method is static so that JVM can invoke it without instantiating the class. Because
we don’t have to create memory before loading
12. Can we overload the main method?
Yes but jvm call main main method first
13. Can we override the main method?
No because it is static
14. Can we write static public void main(String[] args)?
Yes.
15. Why does main method have String array as an argument?
String args[]: The main() method also accepts some data from the user. It accepts a group of strings,
which is called a string array. It is used to hold the command line arguments in the form of string
values. Here, agrs[] is the array name, and it is of String type.
16. Can we make main method as final? Yes
17. Can we have a class without main method?
NO, we can execute a java program without a main method by using a static block. In java 1.6 But
after java 7 jvm checks main method first
18. Can we execute the class without the main method? No
19. Can we create a method inside main method? No, you can't declare a method inside another
method
20. Can we make main method as private?
No. It compiles successfully without any errors but at the runtime, it says that the main method is not
public.
21. Can we call main method explicitly?
we can call the main() method whenever and wherever we need to.
22. Can we return any value from main method? No
Object Oriented Programming
23. What are the main features of OOPs in java?
 1) Encapsulation.2) Inheritance.3) Polymorphism.
 Static Polymorphism (compile time polymorphism/ Method overloading):
 Dynamic Polymorphism (run time polymorphism/ Method Overriding)

24. What is Polymorphism?


The word polymorphism means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form.

25. What is Inheritance in java?


Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object

26. What is Encapsulation in java?


the idea of bundling data and methods that work on that data within one unit, like a class in
Java. This concept is also often used to hide the internal representation, or state of an object from the
outside. This is called information hiding

27. What is Abstraction and how many ways it can be achieved?


In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.

28. What is this and super calling statement?


This is reserved keyword and used to ascess members of current class
super keyword is used to access methods of the parent class while this is used to access methods
of the current class
29. What is constructor chaining statement?
Constructor chaining is the process of calling one constructor from another constructor with
respect to current object.
 Within same class: It can be done using this() keyword for constructors in same class
 From base class: by using super() keyword to call constructor from the base class.

30.Explain the difference between method overloading & method overriding?

No. Method Overloading Method Overriding


1) Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already provided
by its super class.
2) Method overloading is performed within Method overriding occurs in two classes that have IS-
class. A (inheritance) relationship.
3) In case of method overloading, parameter In case of method overriding, parameter must be
must be different. same.
4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.

31. What is constructor overloading?


The constructor overloading can be defined as the concept of having more than one constructor with
different parameters so that every constructor can perform a different task.
32. Is it possible to override constructor? No
33. What is diamond problem in inheritance?
The base class having more then one parent class
CLP OLP Accessing the members
34. What is Compile time polymorphism and how it is different from run time polymorphism?
CTP- It is also known as Static binding, Early binding and overloading as well.
RTP- It is also known as Dynamic binding, Late binding and overriding as well.
35. What do you understand by upcasting and downcasting?
Upcasting (Generalization or Widening) is casting to a parent type in simple words casting individual
type to one common type is called upcasting while downcasting (specialization or narrowing) is
casting to a child type or casting common type to individual type.
36. What is variable shadowing and method shadowing?
If the instance variable and local variable have same name whenever you print it in the method. The
value of the local variable will be printed.
37. Difference between abstract class & interface?

Abstract class Interface


1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

38. Can we write main method inside an interface in Java? Yes


39. How we can achieve multiple inheritance by using interface concept?
interface AnimalEat {
void eat();
}
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
}
public void travel() {
System.out.println("Animal is travelling");
}
}
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
}
}
40. What are the access modifiers ?

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

Access Modifiers Private Default Protected Public


Same Package Same Class Yes Yes Yes Yes
Without No Yes Yes Yes
Inheritance
With Inheritance No Yes Yes Yes
Different Without No No No Yes
Package Inheritance
With Inheritance No No Yes Yes

41. What is marker interface? It is an empty interface (no field or methods).


Inbuilt Classes
42. What is Object class and its methods?
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class provides many methods. They are as follows:

Method Description
public final Class getClass() returns the Class class object of this object. The Class class
can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws
causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes notify()
or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread notifies
(invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.

43. What is array and String?


S.NO. Array String
01. An array is a data structure that stores A string is basically treated as an object which
a collection of elements of the same represents a sequence of characters. An array
data type.
02. Array can hold any of the data types. But, the String can hold only a char data type.
03. The elements of the array are stored in A string class contains a pointer to some part
a contiguous memory location. of the heap memory where the actual contents
of the string are stored in memory.
04. Java array not ended with a null But by default String is ended with null (‘\0’)
character, the end element of the array character in Java.
is the last element of the array.
05. Arrays are mutable. Strings are immutable.
06. The length of the array is fixed. The size of the string is not fixed.

44. When we will get ArrayIndexOutOfBoundsException and NegativeArraySizeException?


NegativeArraySizeException - This error is thrown when anyone wants create an array with a
negative size.

NegativeArraySizeException is a class in Java which extends RuntimeException.

3. ArrayIndexOutOfBoundsException - This type of error is generated when an array has been


accessed with an illegal index. In other words when an array is accessed by a negative index or more
than the size of the array. In Java it's a separate class and this class extends the
IndexOutOfBoundException class.

45. What is difference between " equals() " and " == " in java?
Ans. equals() – it is a method present in Object class which is used to compare the address of two
objects. It can be overridden and can be used o compare the state of the object.
(==) Equality Operator – It is an operator used to compare address of 2 object.
46. What is String and explain atleast 6 inbuilt methods of String?
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an
immutable object which means it is constant and can cannot be changed once it has been created.

1. char charAt(int index): It returns the character at the specified index. Specified index value
should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if
index<0||>= length of String.
2. boolean equals(Object obj): Compares the string with the specified string and returns true if
both matches else false.
3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t
consider the case while comparing strings. It does a case insensitive comparison.
4. int compareTo(String string): This method compares the two strings based on the Unicode
value of each character in the strings.
5. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the
case during comparison.
6. boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the
specified offset index) is having the specified prefix or not.
7. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes
then it returns true else false.
8. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
9. int hashCode(): It returns the hash code of the string.
10. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the
string.

47. Why String is immutable?


The String is immutable in Java because of the security, synchronization and concurrency,
caching, and class loading. The reason of making string final is to destroy the immutability and
to not allow others to extend it.The String objects are cached in the String pool, and it makes
the String immutable.
48. String class can be inherited by any other class?
It is not possible to directly inherit String class as it is final. Also wrapper classes java.
49. Why String class is final? What is String vs String buffer vs String builder?
The string is made final to not allow others to extend it and destroy its immutability

1. String is immutable whereas StringBuffer and StringBuilder are mutable classes.


2. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That’s why
StringBuilder is faster than StringBuffer.
3. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.

String Buffer: - It is a final class extending object class and implementing CharSequence,
Serializable and Appendable interfaces.
String Buffer is a ‘mutable’ class, we can modify the values present inside the created object.
String Buffer is synchronized and it is thread safe.
String Builder: - It is a final class extending object class and implementing CharSequence,
Serializable and Appendable interfaces.
StringBuilder is unsynchronized and it is thread unsafe.
Exception & Exception Handling
51. Difference between Error and Exception?

Basis of Exception Error


Comparison
Recoverable/ Exception can be recovered by using the try-catch An error cannot be recovered.
Irrecoverable block.
Type It can be classified into two categories i.e. checked All errors in Java are unchecked.
and unchecked.
Occurrence It occurs at compile time or run time. It occurs at run time.
Package It belongs to java.lang.Exception package. It belongs to java.lang.Error
package.
Known or Only checked exceptions are known to the compiler.
Errors will not be known to the
unknown compiler.
Causes It is mainly caused by the application itself. It is mostly caused by the
environment in which the
application is running.
Example Checked Exceptions: SQLException, IOException Java.lang.StackOverFlow,
Unchecked java.lang.OutOfMemoryError
Exceptions: ArrayIndexOutOfBoundException,
NullPointerException, ArithmaticException

52. Explain Java Exception Hierarchy?


53. What is checked exception and unchecked exception and its examples?
CHECKED EXCEPTION: - These are the exceptions that are checked at compile time. If some
code within a method throws a checked exception, then the method must either handle the
exception or it must specify the exception using the throws keyword.
// Java Program to Illustrate Checked Exceptions
// Where FileNotFoundException occured
// Importing I/O classes
import java.io.*;
class Chk_Ex {
// Main driver method
public static void main(String[] args){
// Reading file from path in local directory
FileReader file = new FileReader("C:\\test\\a.txt");
// Creating object as one of ways of taking input
BufferedReader fileInput = new BufferedReader(file);
// Printing first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
// Closing file connections
// using close() method
fileInput.close();
}
}

UNCHECKED EXCEPTION: - These are the exceptions that are not checked at compile time. In
Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything
else under throwable is checked.

// Java Program to Illustrate Un-checked Exceptions


// Main class
class Unchk_Ex {
// Main driver method
public static void main(String args[]) {
// Here we are dividing by 0
// which will not be caught at compile time
// as there is no mistake but caught at runtime
// because it is mathematically incorrect
int x = 0;
int y = 10;
int z = y / x;
}
}

54. What is difference between throw and throws keyword in java?


Sr. Basis of throw throws
no. Differences
1. Definition Java throw keyword is used throw an Java throws keyword is used in the method
exception explicitly in the code, signature to declare an exception which might
inside the function or the block of be thrown by the function while the execution
code. of the code.
2. Type of Using throw keyword, we can only Using throws keyword, we can declare both
exception propagate unchecked exception i.e., checked and unchecked exceptions. However,
the checked exception cannot be the throws keyword can be used to propagate
propagated using throw only. checked exceptions only.
3. Syntax The throw keyword is followed by an The throws keyword is followed by class
instance of Exception to be thrown. names of Exceptions to be thrown.
4. Declaration throw is used within the method. throws is used with the method signature.
5. Internal We are allowed to throw only one We can declare multiple exceptions using
implementation exception at a time i.e. we cannot throws keyword that can be thrown by the
throw multiple exceptions. method. For example, main() throws
IOException, SQLException.

55. How to write custom exceptions in java and why we need custom exception?
//class representing custom exception
class MyCustomException extends Exception {
}
//class that uses custom exception MyCustomException
public class Custom_Ex2{
// main method
public static void main(String args[]) {
try {
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex) {
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
System.out.println("rest of the code...");
}
}

56. Without having catch block, is it possible to have only try block and finally block?
Yes, It is possible to have a try block without a catch block by using a final block.
As we know, a final block will always execute even there is an exception occurred in a try block, except
System.exit() it will execute always.
public class TryBlockWithoutCatch {
public static void main(String[] args) {
try {
System.out.println("Try Block");
} finally {
System.out.println("Finally Block");
}
}
}

57. Why we need finally block?


To execute clean up code like closing connections, closing files, or freeing up threads, as it executes
regardless of an exception.
58. What is the purpose of printStackTrace()?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method
of Java’s throwable class which prints the throwable along with other details like the line number and
class name where the exception occurred.

printStackTrace() is very useful in diagnosing exceptions. For example, if one out of five methods in
your code cause an exception, printStackTrace() will pinpoint the exact line in which the method
raised the exception.

59. Is it possible to keep any statements in between try , catch and finally block?
No, we cannot write any statements in between try, catch and finally blocks and these blocks form
one unit.
try{
// Statements to be monitored for exceptions
}
// We can't keep any statements here
catch(Exception ex){
// Catching the exceptions here
}
// We can't keep any statements here
finally{
// finally block is optional and can only exist if try or try-catch
block is there.
// This block is always executed whether exception is occurred in the
try block or not
// and occurred exception is caught in the catch block or not.
// finally block is not executed only for System.exit() and if any
Error occurred.
}

60. Is it possible to only include a try block without the catch and finally block?
No.
Exception in thread "main" java.lang.Error: Unresolved compilation
problem:
Syntax error, insert "Finally" to complete BlockStatements

Collection and Map


61. What is the advantages of Collection over Array?
Collection = homogeneous + heterogeneous data i.e different datatypes can be stored. Size can be
altered.
Array = same data types and fixed in size. size can not be altered
62. What is Collection and its hierarchy?
63. What is List and Explain its implementation classes?
List is sub interface of collection interface.it has many implementation classes such as
1] ArrayList 2] LinkList 3] Vector

64. Difference between Arraylist & LinkedList vs Vector?

65. What is doubly-linked list concept?


Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous
as well as the next node in the sequence. Therefore, in a doubly linked list, a node consists of three
parts: node data, pointer to the next node in sequence (next pointer) , pointer to the previous node
(previous pointer).
66. Why we go with Set and what is the difference between List & Set?
LIST SET
duplicate values are allowed duplicate values are not allowed
maintains insertion order does not maintain insertion order
it has index does not has index
n no. of null objects are allowed only one null object is allowed
random access is allowed random access is not allowed
it has 4 methods to access foreach(), it has 2 methos to access foreach(),
get(),iterator(),ListIterator() iterator()

67. Difference between Hashset & LinkedHashset?


HASH SET LINKED HASH SET TREE SET
Insertion order is not Insertion order is By default sort in ASC order for DESC
maintained maintained descendingSet()
Hertogenious objects Hertogenious objects Hertogenious objects not allowed
allowed allowed
Only one null value Only one null value single null value also not allowed
allowed allowed

68. Explain Treeset?


TreeSet contains only homogeneous objects. In TreeSet null values are not allowed. By default sort
data in ascending order. For descending descendingSet().

69. What is Queue and explain its implementation classes?


70. What is Iterator and why we use?
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.
To use an Iterator, you must import it from the java.util package. And goes in Forward Direction 
iterator has two methods
next()---> printing next obj in list
hasNext()----> checking whether it has next obj or not
71. Difference between Iterator & ListIterator?

Iterator ListIterator
Iterator goes in Listiterator moves I both direction
Forward Direction  Both Directions
iterator has two methods ListIterator has four methods
next()--> printing next obj in list next()---> printing next obj in list
hasNext()--> checking whether it has hasNext()----> checking whether it has next obj or not
next obj or not previous()--->printing Previous obj in list
hasPrevious()--->checking whether it has previous obj or
not

72. What is Map and explain its implementation classes?


In map Data structure the objects are stored in form of (Key+Values).
Implementing classes 1] HashMap 2] LinkedHashMap 3] TreeHashMap

73. Difference between Hashmap vs LinkedHashmap?


HASH MAP LINKED HASH MAP TREE HASH MAP
Insertion order is not Insertion order is By default sort in ASC order based on
maintained maintained Key.
Hertogenious key allowed Hertogenious key Hertogenious key not allowed
allowed
Only one null key Only one null key single null key also not allowed
allowed allowed
74. What is Treemap?
In TreeMap by default sorting is done ASC order based on Key. Hertogenious key not allowed. Key
cannot be Null.

75. If we use duplicate key with some value in map what will happen?
If you try to insert the duplicate key, it will replace the element of the corresponding key.

76. Why hashMap does not comes under collection?


Answer:: Collection has a method add(Object o). Map can not have such method because it need key-
value pair. There are other reasons also such as Map supports keySet, valueSet etc. Collection classes
does not have such views. Due to such big differences, Collection interface was not used in Map
interface, and it was built in separate hierarchy.

Advanced Questions
77. What is multi-threading?
Ans. Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a
lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking. However, we use multithreading than multiprocessing because threads
use a shared memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

78. What is difference between Thread and runnable?


Ans. Thread
• Thread is a class. It is used to create a thread.
• It has multiple methods including start() and run()
• Each thread creates a unique object and gets associated with it.

Runnable
• Runnable is a functional interface which is used to create a thread.
• It has only abstract method run()
• Multiple threads share the same objects.

79. What is Synchronization?


Ans - Synchronization in java is the capability to control the access of multiple threads to any shared
resource. Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

80. What is difference between sleep() and wait()?


Ans. Wait() – The thread releases ownership of this monitor and waits until another thread notifies
threads waiting on this object's monitor to wake up either through a call to the notify() method or the
notifyAll() method. The thread then waits until it can re-obtain ownership of the monitor and resumes
execution.
Sleep() - This method causes the currently executing thread to sleep (temporarily cease execution) for
the specified number of milliseconds. The thread does not lose ownership of any monitors. It sends
the current thread into the “Not Runnable” state for a specified amount of time.

81. Difference between final and finally and finalize ?


Sr. Key final finally finalize
no.

1. Definition final is the keyword and finally is the block in finalize is the method in
access modifier which Java Exception Java which is used to
is used to apply Handling to execute the perform clean up
restrictions on a class, important code whether processing just before
method or variable. the exception occurs or object is garbage
not. collected.
2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and variables. catch block in exception
handling.
3. Functionality (1) Once declared, final (1) finally block runs the
finalize method performs
variable becomes important code even if
the cleaning activities
constant and cannot be exception occurs or not.
with respect to the object
modified. (2) finally block cleans
before its destruction.
(2) final method cannot up all the resources used
be overridden by sub in try block
class.
(3) final class cannot be
inherited.
4. Execution Final method is Finally block is finalize method is
executed only when we executed as soon as the executed just before the
call it. try-catch block is object is destroyed
executed.

It's execution is not


dependant on the
exception.

82. Define System.out.println() ?


Where System is the class name, it is declared as final. The out is an instance of the System class and
is of type PrintStream. Its access specifiers are public and final. It is an instance of
java.io.PrintStream. When we call the member, a PrintStream class object creates internally .
So, we can call the print() method, as shown below:
System.out.print();

83. What is Destructor?


It is a special method that automatically gets called when an object is no longer used. When an object
completes its life-cycle the garbage collector deletes that object and deallocates or releases the
memory occupied by the object.
It is also known as finalizers that are non-deterministic. In Java, the allocation and deallocation of
objects handled by the garbage collector. The invocation of finalizers is not guaranteed because it
invokes implicitly.

84. What is dynamic method dispatch?


Dynamic method dispatch is the mechanism in which a call to an overridden method is resolved at
run time instead of compile time. This is an important concept because of how Java implements run-
time polymorphism.

85. What is copy constructor?


A copy constructor in a Java class is a constructor that creates an object using another object of
the same Java class.
Need: -Sometimes, we face a problem where we required to create an exact copy of an existing object
of the class. There is also a condition, if we have made any changes in the copy it should not reflect in
the original one and vice-versa. For such cases, Java provides the concept of a copy constructor.

86. What is file handling?


Ans. File Handing in java comes under IO operations. Java IO package java.io classes are specially
provided for file handling in java.
Some of the common file handling operations are:
• Create file
• Delete file
• Read file
• Write file
• Change file permissions

You might also like