Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Java Interview Questions Guide
Description: This collection of Java Interview Questions covers essential topics to help you ace technical interviews. From core concepts like OOP principles, data types, and control structures to advanced topics such as multithreading, collections, and JVM architecture, these questions provide a thorough review. Prepare effectively with clear explanations and practical examples, ensuring you're ready for coding interviews and technical assessments.
Description: This collection of Java Interview Questions covers essential topics to help you ace technical interviews. From core concepts like OOP principles, data types, and control structures to advanced topics such as multithreading, collections, and JVM architecture, these questions provide a thorough review. Prepare effectively with clear explanations and practical examples, ensuring you're ready for coding interviews and technical assessments.
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
240 CORE JAVA INTERVIEW
QUESTIONS AND ANSWERS
Table of Contents
1) what are static blocks and static initalizers in Java ?
...
9
3) What is method overriding in java ?
...
9
5) Difference between method overloading and method overriding in java ?
...
10
7)
Why java is platform independent?
...
10
9)
What is difference between c++ and Java ?
...
10
11)
What is bytecode in java ?
...
11
13)
What is a class ?
...
11
15)What is method in java ?
...
11
17) Why main() method is public, static and void in java ?
...
12
19)What is constructor in java ?
...
12
21)
What is ASCII Code?
...
13
23)
Difference between Character Constant and String Constant in java ?
...
13
25)
Difference between ‘>>’ and ‘>>>’ operators in java?
...
13
26)
Explain Java Coding Standards for classes or Java coding conventions for
classes?
...
13
1
28)
Explain Java Coding standards for Methods?
...
13
30)
Explain Java Coding Standards for Constants?
...
14
32)
What is ‘IS-A ‘ relationship in java?
...
14
34)
Difference between ‘IS-A’ and ‘HAS-A’ relationship in java?
...
14
36) What does null mean in java?
...
15
38) What all access modifiers are allowed for top class ?
...
15
40)
Can we have more than one package statement in source file ?
...
15
42)
What are identifiers in java?
...
15
44) What is the difference between access specifiers and access modifiers in java? 16
45)
What access modifiers can be used for class ?
...
16
47)
Explain what access modifiers can be used for variables?
...
17
49)
Explain about abstract classes in java?
...
18
51)
What are abstract methods in java?
...
18
52)
What is an exception in java?
...
18
54)
What is Exception handling in java?
...
18
56)
What are advantages of Exception handling in java?
...
18
58)
List out five keywords related to Exception handling ?
...
19
60)
Can we have try block without catch block?
...
19
62)
Explain importance of finally block in java?
...
19
64)
Can we have any code between try and finally blocks?
...
19
66)
What are checked Exceptions?
...
20
68)
Explain differences between checked and Unchecked exceptions in java?
...
20
70)
Explain throw keyword in java?
...
21
72)
Explain importance of throws keyword in java?
...
21
74)
Explain a situation where finally block will not be executed?
...
21
76)
What are user defined exceptions?
...
21
78) Can we nested try statements in java?
...
22
80)
Explain when ClassNotFoundException will be raised ?
...
22
Java Interview questions on threads
...
22
84)
What is thread in java?
...
22
86)
What is multitasking ?
...
22
88)
What are the benefits of multithreaded programming?
...
23
90)
List Java API that supports threads?
...
23
92) In how many ways we can create threads in java?
...
23
94)
Explain creating threads by extending Thread class ?
...
24
96)
Explain the importance of thread scheduler in java?
...
24
98)
Can we restart a dead thread in java?
...
24
100)
Can we restart a thread already started in java?
...
24
102)
Can we overload run() method in java?
...
24
106)
In how many ways we can do synchronization in java?
...
25
108) When do we use synchronized methods in java?
...
25
110) When a thread is executing a synchronized method , then is it possible for the
same thread to access other synchronized methods of an object ?
...
25
112) When do we use synchronized blocks and advantages of using synchronized
blocks?
...
26
114) Can we synchronize static methods in java?
...
26
116) What are thread priorities and importance of thread priorities in java?
...
26
118) How to change the priority of thread or how to set priority of thread?
...
26
120)
What all methods are used to prevent thread execution ?
...
26
122) Is it possible for yielded thread to get chance for its execution again ?
...
27
124) Explain purpose of sleep() method in java?
...
28
126)
Can sleep() method causes another thread to sleep?
...
28
128) Explain about interthread communication and how it takes place in java?
...
28
130) Explain why wait() , notify() and notifyAll() methods are in Object class rather
than in thread class?
...
28
132) when wait(), notify(), notifyAll() methods are called does it releases the lock
or holds the acquired lock?
...
28
134) What are thread groups?
...
29
136) What are daemon threads in java?
...
29
138) Can we make main() thread as daemon?
...
29
139) What are nested classes in java?
...
29
141) Why to use nested classes in java?
...
29
What is the purpose of nested class in java?
...
30
143) How to instantiate static nested classes in java?
...
30
145) Explain about features of local inner class?
...
30
147) Explain restrictions for using anonymous inner classes?
...
30
5
149) Explain about member inner classes?
...
31
151) How to do encapsulation in Java?
...
31
153) Will the compiler creates a default constructor if I have a parameterized
constructor in the class?
...
31
155) Can we override constructors in java?
...
31
157) How do we access static members in java?
...
31
159) Difference between object and reference?
...
32
161) How many times finalize method will be invoked ? who invokes finalize()
method in java?
...
32
163) Explain wrapper classes in java?
...
32
165) Explain about transient variables in java?
...
32
167) What is type conversion in java?
...
32
169) Explain about narrowing conversion in java?
...
33
171) Explain naming conventions for packages ?
...
33
173) What is jar ?
...
33
175) Explain the scope or life time of class variables or static variables?
...
33
177) Explain about static imports in java?
...
34
6
179) Define interface in java?
...
34
181) Explain features of interfaces in java?
...
34
183) Explain restrictions on using enum?
...
34
185) Explain about Varargs in java?
...
35
187) Can we use Switch statement with Strings?
...
35
Oops concepts interview questions
...
35
190) Explain about object oriented programming and its features?
...
35
192) Differences between traditional programming language and object oriented
programming language?
...
35
194) Explain what is encapsulation?
...
36
196) Explain importance of inheritance in java?
...
36
Collection Framework interview questions
...
36
199) What is collection ?
...
37
201) Explain about Collection interface in java ?
...
37
203) Explain List interface ?
...
38
205) List implementations of List Interface ?
...
38
7
207) Difference between Array and ArrayList ?
...
39
209) Difference between arraylist and vector ?
...
39
211) Define Iterator and methods in Iterator?
...
40
212) Explain ListIterator and methods in ListIterator?
...
41
214) Implementations of Set interface ?
...
41
216) Explain Tree Set and its features?
...
42
218) What is Linked HashSet and its features?
...
42
220) What is linked hashmap and its features?
...
42
222) What is Hashtable and explain features of Hashtable?
...
42
224) Difference between arraylist and linkedlist?
...
43
226) What is concurrent hashmap and its features ?
...
synchronizedHashMap?
...
43
229) Explain about fail fast iterators in java?
...
44
Core java Serialization interview questions
...
44
232) What is the main purpose of serialization in java?
...
44
234) Explain about serializable interface in java?
...
44
8
236) What is serial version UID and its importance in java?
...
45
238) Can we serialize static variables in java?
...
45
240) If we don’t want some of the fields not to serialize How to do that?
...
we declare static blocks when we
want to intialize static fields in our class
...
Static blocks are executed even before the constructors are executed
...
Based on the
number of parameters we pass appropriate this() method is called
...
When to use overriding in java
If we want same method with different behaviour in superclass and subclass then we go for overriding
...
4) What is super keyword in java ?
Variables and methods of super class can be overridden in subclass
...
Subclass cannot access the variables and methods of
superclass because the overridden variables or methods hides the methods and variables of super class
...
Super is
used to access superclass variables, methods, constructors
...
2)
Second one is to call super class variables,methods
...
5) Difference between method overloading and method overriding in java ?
Method Overloading
1)
Method Overloading occurs with in the same
class
2) Since it involves with only one class inheritance
is not involved
...
3) In overriding return type must be same
...
5) Dynamic polymorphism can be acheived using
method overriding
...
9
6) Difference between abstract class and interface ?
1)
Interface
Interface contains only abstract methods
2)
Access Specifiers for methods in interface
must be public
3)
Variables defined must be public , static ,
final
4)
Multiple Inheritance in java is implemented
using interface
5)
To implement an interface we use
implements keyword
Abstract Class
1)
Abstract class can contain abstract methods,
concrete methods or both
2)
Except private we can have any access
specifier for methods in abstract class
...
5)To implement an interface we use implements
keyword
7)
Why java is platform independent?
The most unique feature of java is platform independent
...
This cannot be run across all platforms
...
class file
...
Byte codes are interpreted only by JVM’s
...
Byte
code generated in windows environment can also be executed in linux environment
...
8)
What is method overloading in java ?
A class having two or more methods with same name but with different arguments then we say that those
methods are overloaded
...
Method overloading is used when we want the methods to perform similar tasks but with different inputs
or values
...
Compiler decides which method to call at compile time
...
Note : Return type is not part of method signature
...
9)
1)
2)
3)
4)
5)
6)
7)
What is difference between c++ and Java ?
Java
C++
Java is platform independent
C++ is platform dependent
...
There is no operator overloading in java
C ++ has operator overloading
...
JIT compiler compiles byte code in to executable code
...
JIT cannot convert complete java program in to executable code it converts as and
when it is needed during execution
...
class file
...
class file contains set of
instructions called byte code
...
JVM can understand this byte codes
...
Either this() or super() exists it must be the first statement in the
constructor
...
A class is kind of blueprint or
template for objects
...
A class tells what type of objects we are creating
...
We can create any
number of department objects
...
When JVM starts running it first looks for the class
when we compile
...
Class starts with class keyword
...
File name must end with
...
public class FirstClass
{public static void main(String[] args)
{System
...
println(“My First class”);
}
}
If we see the above class when we compile JVM loads the FirstClass and generates a
...
class)
...
14) What is an object ?
An Object is instance of class
...
Each object belongs to some class
...
State is determined by value of attributes and behavior is called
method
...
To instantiate the class we declare with the class type
...
out
...
15)What is method in java ?
It contains the executable body that can be applied to the specific object of the class
...
Syntax : type methodName(Argument List){
}
ex : public float add(int a, int b, int c)
methods can have multiple arguments
...
16) What is encapsulation ?
The process of wrapping or putting up of data in to a single unit class and
keeps data safe from misuse is called encapsulation
...
Java supports
encapsulation through access control
...
For example take a car class , In car we have many parts which is not required for driver to know what all
it consists inside
...
So we can expose
what all are required and hide the rest by using encapsulation
...
When main method is declared
public it means it can be used outside class
...
Sometimes it may be required to call a method without the
help of object
...
JVM calls the main() method without creating
object by declaring keyword static
...
main() method does’nt return
any value, so main() is declared as void
...
public static void main(String[] args) {}
String args[] are array of string objects we need to pass from command line arguments
...
19)What is constructor in java ?
A constructor is a special method used to initialize objects in java
...
As and when an object
is created it is initialized automatically with the help of constructor in java
...
Ex : String str = “Hello World”;
System
...
println(str
...
length() will return 11 characters including space
...
For example :
String days[]={” Sun”,”Mon”,”wed”,”thu”,”fri”,”sat”};
Will return 6 since the number of values in days array is 6
...
ASCII character range is 0 to 255
...
ASCII character set supports only English
...
22)
What is Unicode ?
Unicode is a character set developed by Unicode Consortium
...
Unicode characters were represented by 16 bits and its character range is 065,535
...
If we want to
use telugu we can use telugu characters for identifiers
...
23)
Difference between Character Constant and String Constant in java ?
Character constant is enclosed in single quotes
...
Character
constants are single digit or character
...
Ex :’2’, ‘A’
Ex : “Hello World”
24) What are constants and how to create constants in java?
Constants are fixed values whose values cannot be changed during the execution of program
...
Ex : final int number =10;
final String str=”java-interview –questions”
25) Difference between ‘>>’ and ‘>>>’ operators in java?
>> is a right shift operator shifts all of the bits in a value to the right to a specified number of times
...
>>> is an unsigned shift operator used to shift right
...
Core java Interview questions on Coding Standards
26)
Explain Java Coding Standards for classes or Java coding conventions for classes?
Sun has created Java Coding standards or Java Coding Conventions
...
Classnames should start with uppercase letter
...
If Class name is of
multiple words then the first letter of inner word must be capital letter
...
2)
Method names are usually verbs
3)
If method contains multiple words, every inner word should start with uppercase letter
...
2)
Variable names should be nouns
3)
Short meaningful names are recommended
...
Ex : string,value,empName,empSalary
30) Explain Java Coding Standards for Constants?
Constants in java are created using static and final keywords
...
2)
If constant name is combination of two words it should be separated by underscore
...
Ex:MAX_VALUE, MIN_VALUE, MAX_PRIORITY, MIN_PRIORITY
31)
Difference between overriding and overloading in java?
Overriding
In overriding method names must be same
Argument List must be same
Overloading
In overloading method names must be same
Argument list must be different atleast order of
arguments
...
type
...
5 covariant types are allowed
We cant increase the level of checked exceptions
...
No restrictions for unchecked exceptions
A method can only be overridden in subclass
A method can be overloaded in same class or
subclass
Private,static and final variables cannot be
Private , static and final variables can be
overridden
...
In overriding which method is called is decided at
In overloading which method to call is decided at
runtime based on the type of object referenced at compile time based on reference type
...
32)
What is ‘IS-A ‘ relationship in java?
‘is a’ relationship is also known as inheritance
...
The advantage or inheritance or is a relationship is reusability of code instead of
duplicating the code
...
33) What is ‘HAS A’’ relationship in java?
‘Has a ‘ relationship is also known as “composition or Aggregation”
...
The main advantage of
‘Has-A‘ relationship in java code reusability
...
For IS-A relationship we uses extends keyword
For Has a relationship we use new keyword
Ex : Car is a vehicle
...
We cannot say Car is an
engine
The main advantage of inheritance is reusability of The main advantage of has a relationship is
code
reusability of code
...
Syntax :
Instanceof returns true if reference expression is subtype of destination type
...
Example : public classInstanceOfExample {public static voidmain(String[] args) {Integer a =
newInteger(5);if (a instanceof java
...
Integer) {
System
...
println(true);
} else {
System
...
println(false);
}
14
}
}
Since a is integer object it returns true
...
If it is not
a subtype then compile time error will be shown as Incompatible types
36) What does null mean in java?
When a reference variable doesn’t point to any value it is assigned null
...
We can
have multiple classes in File but only one class can be made public
...
“The public type must be defined in its own file”
...
public and default
...
If a class is declared default it is visible only in same package
...
Illegal Modifier for the class only public,abstract and final are permitted
...
Package can be declared using the following statement :
Syntax : package
Coding Convention : package name should be declared in small letters
...
The main use of package is
1)
To resolve naming conflicts
2)
For visibility control : We can define classes and interfaces that are not accessible outside the
class
...
In any java program there can be atmost
only 1 package statement
...
41) Can we define package statement after import statement in java?
We can’t define package statement after import statement in java
...
We can have comments before the package statement
...
Identifiers can be class name, method name or variable name
...
2) Identifiers can’t start with numbers
...
5) First letter can be alphabet ,or underscore and dollar sign
...
6) We should’nt use reserve words for identifiers in java
...
By preventing access control we can misuse of
class, methods and members
...
There are three types
of access modifiers in java
...
If no access modifier is specified then it has a default
access
...
But there is no such divison of access specifiers and access modifiers in java
...
Access Modifiers : public, private, protected, default
Non Access Modifiers : abstract, final, stricfp
...
public: A class with public modifier can be visible
1) In the same class
2) In the same package subclass
3) In the same package nonsubclass
4) In the different package subclass
5) In the different package non subclass
...
46) Explain what access modifiers can be used for methods?
We can use all access modifiers public, private,protected and default for methods
...
default : When a method is declared as default, we can access that method in
1) In the same class
2) In the same package subclass
3) In the same package non subclass
We cannot access default access method in
1) Different package subclass
2) Different package non subclass
...
private : When a method is declared as private it can be accessed only in that class
...
47) Explain what access modifiers can be used for variables?
We can use all access modifiers public, private,protected and default for variables
...
default : When a variables is declared as default, we can access that method in
1) In the same class
2) In the same package subclass
3) In the same package non subclass
We cannot access default access variables in
4) Different package subclass
5) Different package non subclass
...
private : When a variables is declared as private it can be accessed only in that class
...
48)
What is final access modifier in java?
final access modifier can be used for class, method and variables
...
The main disadvantage of final
access modifier is we cannot implement oops concepts in java
...
final class : A final class cannot be extended or subclassed
...
But we can still access the methods of this class by composition
...
But there are situations where
we may not want to use this feature
...
To
allow a method from being overridden we use final access modifier for methods
...
We cannot modify the value
of final variable
...
The error is as
follows
“final variable cannot be assigned
...
We want to leave the implementation to a class that extends it
...
To make a class abstract we use key word abstract
...
If we don’t declare class as abstract which contains abstract
methods we get compile time error
...
“The type
...
At that moment we make vehicle class abstract
...
Any class which extends vehicle will provide
its method implementation
...
The important features of abstract classes are :
1) Abstract classes cannot be instantiated
...
3) Any class which extends abstract class must override all methods of abstract class
...
17
Though we cannot instantiate abstract classes we can create object references
...
50)
Can we create constructor in abstract class ?
We can create constructor in abstract class , it does’nt give any compilation error
...
51) What are abstract methods in java?
An abstract method is the method which does’nt have any body
...
Signature : public abstract void
Ex : public abstract void getDetails();
It is the responsibility of subclass to provide implementation to abstract method defined in abstract class
...
Exceptions are created when an abnormal situations are arised in our
program
...
All Exception classes are defined
in java
...
In otherwords we can say Exception as run time error
...
2) Invalid conversion of number to string and string to number
...
When an
exception is raised in program it leads to termination of program when it is not handled properly
...
This can be done with help of Exception handling
...
When errors are caused by our program we call that as
Exception, but some times exceptions are caused due to some environment issues such as running out of
memory
...
Exceptions which cannot be recovered are called
as errors in java
...
56) What are advantages of Exception handling in java?
1) Separating normal code from exception handling code to avoid abnormal termination of program
...
It is recommended to handle exceptions with
specific Exception instead of handling with Exception root class
...
This propogation continues till it finds an
appropriate exception handler ,if it finds handler it would be handled otherwise program terminates
abruptly
...
2) Declaring a method with throws clause
...
In java try and catch forms a unit
...
Catch block cannot catch an exception thrown by another try
block
...
Syntax :
try
{
}
Catch(Exception e)
{
}
60)
Can we have try block without catch block?
Each try block requires atleast one catch block or finally block
...
We can skip either of catch or finally block but not both
...
In such case we can specify two or more
catch clauses, each catch handling different type of exception
...
Try with multiple catch blocks is highly recommended in java
...
62) Explain importance of finally block in java?
Finally block is used for cleaning up of resources such as closing connections, sockets etc
...
If there is
exception thrown in try block finally block executes immediately after catch block
...
63) Can we have any code between try and catch blocks?
We shouldn’t declare any code between try and catch block
...
try{
//code
}
System
...
println(“one line of code”); // illegal
catch(Exception e){
//
}
64)
Can we have any code between try and finally blocks?
We shouldn’t declare any code between try and finally block
...
If there is no catch block it should immediately start after try block
...
out
...
This type of handling reduces
the code duplication
...
We cannot assign any value to catch parameter
...
66) What are checked Exceptions?
1) All the subclasses of Throwable class except error,Runtime Exception and its subclasses are checked
exceptions
...
We do get compilation error
...
These are unchecked exceptions
because compiler does not checks if a method handles or throws exceptions
...
If an exception occurs in the program,program terminates
...
Example : 1) Arithmetic Exception
3) ArrayIndexOutOfBoundsException
4) ClassCastException
5) IndexOutOfBoundException
6) NullPointerException
7) NumberFormatException
8) StringIndexOutOfBounds
9) UnsupportedOperationException
68)
Explain differences between checked and Unchecked exceptions in java?
Unchecked Exception
1) All the subclasses of RuntimeException are
called unchecked exception
...
4) ArrayIndexOutOfBoundsException,
ClassCastException, IndexOutOfBoundException
Checked Exception
All subclasses of Throwable class except
RuntimeException are called as checked exceptions
Checked Exceptions need to be handled at compile
time
...
1) Name of Exception
2) Description about the Exception
3) Location of Exception
...
If there is
exception handling code then exception handles and continues the program
...
Default Exception handler displays description of exception,prints the stacktrace and location of exception
and terminates the program
...
20
70)
Explain throw keyword in java?
Generally JVM throws the exception and we handle the exceptions by using try catch block
...
In such case we use
throw keyword to throw exception explicitly
...
After the throw statement execution stops and subsequent statements are not executed
...
If not then the next catch
statement till it finds the appropriate handler
...
In general we use throw keyword for throwing userdefined or customized exception
...
If we try to write
any statement after throw we do get compile time error saying unreachable code
...
The main purpose of throws keyword is to delegate responsibility of exception handling to the caller
methods, in the case of checked exception
...
We can use throws keyword only for throwable types otherwise compile time error saying incompatible
types
...
Syntax : Class Test{
Public static void main(String args[]) throws IE
{
}
}
Note : The method should throw only checked exceptions and subclasses of checked exceptions
...
73) Explain the importance of finally over return statement?
finally block is more important than return statement when both are present in a program
...
74)
Explain a situation where finally block will not be executed?
Finally block will not be executed whenever jvm shutdowns
...
exit(0) in try statement
finally block if present will not be executed
...
This raises compile time error if we try to handle checked exceptions when there is
no possibility of causing exception
...
We can create user defined
exceptions as checked or unchecked exceptions
...
Userdefined exceptions can extend RuntimeException to create userdefined unchecked exceptions
...
e we need to extend
Runtime Exception class but not Excpetion class
...
If we want to rethrow checked exception
from a catch block we need to declare that exception
...
We can declare try statements inside the block of another try
statement
...
All exceptions are derived from this throwable class
...
The three methods defined in throwable class
are :
1) void printStackTrace() :
This prints the exception information in the following format :
Name of the exception, description followed by stack trace
...
3) toString():
It prints the name and description of Exception
...
An example for this exception is when class name is misspelled
and when we try to load the class by string name hence class cannot be found which raises
ClassNotFoundException
...
The class may exist at compile time but unable to find at runtime
...
Java Interview questions on threads
83) What is process ?
A process is a program in execution
...
Process are heavy weight and requires their own address
space
...
84) What is thread in java?
Thread is separate path of execution in program
...
3) creating thread is simple when compared to process because creating thread requires less resources
when compared to process
4) Threads exists in process
...
85)
Difference between process and thread?
Process
Thread
1) Program in execution
...
One or
more threads is called as process
...
3) Processes require separate address space
...
4) Interprocess communication is expensive
...
5) Context switching from one process to another Context switching between threads is low cost
...
86) What is multitasking ?
Multitasking means performing more than one activity at a time on the computer
...
87) What are different types of multitasking?
There are two different types of multitasking :
22
1) Process based multitasking
2) Thread based multitasking
Process based multitasking : It allows to run two or more programs concurrently
...
Example : Running Ms word and Ms powerpoint at a time
...
Example : Formatting the text and printing word document at same time
...
88) What are the benefits of multithreaded programming?
Multithreading enables to use idle time of cpu to another thread which results in faster execution of
program
...
89)
1)
2)
3)
4)
Explain thread in java?
Thread is independent path of execution with in a program
...
At run time threads share code and data i
...
Every thread in java is an object of java
...
Thread class
...
lang
...
By extending Thread class and overriding
run() we can create thread in java
...
lang
...
By implementing runnable interface and overriding
run() we can create thread in java
...
lang
...
In object class we have three
methods wait(), notify(), notifyAll() that supports threads
...
util
...
Ex : Executor interface, Future task class etc
...
Main thread is important because :
1) All the child threads spawn from main thread
...
When JVM calls main method() it starts a new thread
...
92) In how many ways we can create threads in java?
We can create threads in java by any of the two ways :
1) By extending Thread class
2) By Implementing Runnable interface
...
By implementing runnable interface and implementing
run() method we can create new thread
...
Example :
public class MyClass implements Runnable {
@Override
public void run() {
// T
}
}
94) Explain creating threads by extending Thread class ?
We can create a thread by extending Thread class
...
Example :
public class MyClass extends Thread {
@Override
public void run() {
23
// Starting point of Execution
}
}
95) Which is the best approach for creating thread ?
The best way for creating threads is to implement runnable interface
...
When we create thread by implementing runnable interface we can implement Runnable interface
...
96) Explain the importance of thread scheduler in java?
Thread scheduler is part of JVM use to determine which thread to run at this moment when there are
multiple threads
...
Thread scheduler first allocates the processor time to the higher priority threads
...
97) Explain the life cycle of thread?
A thread can be in any of the five states :
1) New : When the instance of thread is created it will be in New state
...
The thread is created but not in active state to make it active we
need to call start() method on it
...
3) Running state : If thread scheduler allocates cpu time, then the thread will be in running state
...
A thread can be in
the above state in any of the following ways:
1) The thread waits to acquire lock of an object
...
3) The thread waits for notification of other thread
...
It dies
automatically when thread’s run method execution is completed and the thread object will be garbage
collected
...
99) Can one thread block the other thread?
No one thread cannot block the other thread in java
...
100) Can we restart a thread already started in java?
A thread can be started in java using start() method in java
...
A runnable thread cannot be
restarted
...
Then default implementation of Thread class run() method will be
executed and hence the thread will never be in runnable state
...
But the overloaded method will not be called by start method we have to explicitly call this
start() method
...
A lock is associated to shared resource
...
If already a lock has been acquired by other it can’t access that shared resource
...
To lock an
object we use synchronization in java
...
106) In how many ways we can do synchronization in java?
There are two ways to do synchronization in java:
1) Synchronized methods
2) Synchronized blocks
To do synchronization we use synchronize keyword
...
Signature :
public synchronized void methodName(){}
To execute synchronized method first lock has to be acquired on that object
...
once lock has been acquired then synchronized method gets executed
...
The prerequisite to execute a
synchronized method is to acquire lock before method execution
...
108) When do we use synchronized methods in java?
If multiple threads tries to access a method where method can manipulate the state of object , in such
scenario we can declare a method as synchronized
...
110) When a thread is executing a synchronized method , then is it possible for the same
thread to access other synchronized methods of an object ?
Yes it is possible for thread executing a synchronized method to execute another synchronized method of
an object
...
Once synchronized method
is called lock will be automatically acquired on that method when no other thread has lock on that
method
...
Once synchronized
method execution completes automatically lock will be released
...
If there is a lock already acquired by
any other thread it waits till the other thread completes
...
Signature :
Synchronized (object reference){// code}
112) When do we use synchronized blocks and advantages of using synchronized blocks?
If very few lines of code requires synchronization then it is recommended to use synchronized blocks
...
25
113) What is class level lock ?
Acquiring lock on the class instance rather than object of the class is called class level lock
...
class instance
and in object level lock ,lock is acquired on object of class
...
If a thread wants to execute static synchronize
method it need to acquire first class level lock
...
But it can execute the following methods simultaneously :
1) Normal static methods
2) Normal instance methods
3) synchronize instance methods
Signature :
synchronized(Classname
...
116) What are thread priorities and importance of thread priorities in java?
When there are several threads in waiting, thread priorities determine which thread to run
...
A thread inherits priority of its parent thread
...
Thread scheduler uses thread priorities to decide when each
thread is allowed to run
...
117) Explain different types of thread priorities ?
Every thread in java has priorities in between 1 to 10
...
NORM_PRIORITY)
...
Thread class
defines the following constants(static final variables) to define properties
...
MIN_PRIORITY = 1;
Thread
...
MAX_PRIORITY=10;
118) How to change the priority of thread or how to set priority of thread?
Thread class has a set method to set the priority of thread and get method to get the priority of the
thread
...
JVM may or may not oblige the request
...
final int getPriority()
{
}
119) If two threads have same priority which thread will be executed first ?
We are not guaranteed which thread will be executed first when there are threads with equal priorities in
the pool
...
The scheduler can do any of the
following things :
1) It can pick any thread from the pool and run it till it completes
...
120) What all methods are used to prevent thread execution ?
There are three methods in Thread class which prevents execution of thread
...
yield() makes current thread to
sleep for a specified amount of time
...
It all depends on thread scheduler it doesn’t gurantee anything
...
The thread does’nt lose
any lock if it has acquired a lock earlier
...
Thread scheduler decides whether it get chance for execution again or not
...
123) Explain the importance of join() method in thread class?
A thread can invoke the join() method on other thread to wait for other thread to complete its
execution
...
A running thread t1 invokes join() on
thread t2 then t1 thread will wait in to waiting state until t2 completes
...
join() method throws Interrupted Exception so when ever we use join() method we should handle
Interrrupted Exception by throws or by using try catch block
...
sleep() method is
the minimum amount of the time the current thread sleeps but not the exact amount of time
...
Lock will not be released though the
thread sleeps for a specified amount of time
...
127) Explain about interrupt() method of thread class ?
Thread class interrupt() method is used to interrupt current thread or another thread
...
That is the reason we may not see the impact of interrupt call immediately
...
So when we call interrupt() method
status would set to true
...
If a thread is in sleeping or waiting status (i
...
This is reason we need to handle
interrupted exception with throws or try/ catch block
...
Interthread communication in java is done with the help of following three
methods :
1) wait()
2) notify()
3) notifyAll()
129) Explain wait(), notify() and notifyAll() methods of object class ?
wait() : wait() method() makes the thread current thread sleeps and releases the lock until some other
thread acquires the lock and calls notify()
...
notfiyAll() :notifyAll() method wakes up all the threads that are called wait() on the same object
...
All the above three methods are in object class and are called only in synchronized context
...
130) Explain why wait() , notify() and notifyAll() methods are in Object class rather than in
thread class?
First to know why they are in object class we should know what wait(), notify(), notifyAll() methods do
...
wait(),
notify(), notifyAll() are called on an shared object so to they are kept in object class rather than thread
class
...
Wait(), notify(),notifyAll() must always be called in synchronized context other wise we get this
run time exception
...
When these methods are
called in synchronized context
...
When wait(),
notify(), notifyAll() methods are called lock is released on that object
...
It is a way of grouping threads so that
actions can be performed on set of threads for easy maintenance and security purposes
...
We rarely use thread group class
...
Every thread belongs to a
thread group
...
135) What are thread local variables ?
Thread local variables are variables associated to a particular thread rather than object
...
Everytime a new thread accesses object by using
getter or setter we are accesing copy of object
...
136) What are daemon threads in java?
Daemon threads are threads which run in background
...
Garbage collector is one of the good example for daemon threads
...
Daemon nature of a thread can be inherited
...
137) How to make a non daemon thread as daemon?
By default all threads are non daemon
...
The important point to note here we can call setDaemon() only before start()
method is called on it
...
138) Can we make main() thread as daemon?
Main thread is always non daemon
...
Interview questions on Nested classses and inner classes
139) What are nested classes in java?
Class declared with in another class is defined as nested class
...
1) Static nested class
2) Non static nested class
A static nested class has static keyword declared before class definition
...
Generally non static nested classes are referred as inner classes
...
For example : We have a submit button upon click of submit button we need to execute some code
...
Instead of creating a new class we
can create inner class
2) To increase encapsulation :
Inner class can access private members of outer class
...
But by creating inner class private variables
can be accesed only by inner class
...
29
4) Hiding implementation :
Inner class helps us to hide implementation of class
...
Static nested classes
are not inner classes
...
A static nested doesnot have access to instance variables and non static methods of outer class
...
Syntax for instantiating Static nested class :
OuterclassName
...
StaticNestedClassName();
144) Explain about method local inner classes or local inner classes in java?
Nested classes defined inside a method are local inner classes
...
A local inner classes exist only when method is invoked and
goes out of scope when method returns
...
2) We cannot use access modifiers static for local inner class
...
3) We cannot declare static members inside local inner classes
...
5) Method local inner classes can only access final variables declared inside a method
...
146) Explain about anonymous inner classes in java?
Inner class defined without any class name is called anonymous inner class
...
The main purpose of anonymous inner classes in java are to provide
interface implementation
...
We can
use all members of enclosing class and final local variables
...
class
2) EnclsoingName$1
...
2) An anonymous inner class cannot define static methods, fields or classes
...
4) Anonymous inner class can be instantiated only once
...
If we see the above code it looks like we are instantiating Runnable interface
...
149) Explain about member inner classes?
Non static class defined with in enclosing class are called member inner class
...
A member inner class can access the members of outer class including
private members
...
2)
A member inner class can extend class or implement interface
...
4)
A member inner class can be declared with public, private, protected or default access
...
InnerclassName inner=new OuterClassReference
...
Define getter and setter methods to access instance variables
...
Ex : Employee emp=new Employee();
In the above example emp is reference variable
...
A reference variable can point to any number of objects
...
A reference variable can be declared either to a class type or interface type
...
153) Will the compiler creates a default constructor if I have a parameterized constructor in
the class?
No compiler won’t create default constructor if there is parameterized constructor in the class
...
For Example :
public classCar {}
In the above Car class there are no constructors so compiler creates a default constructor
...
154) Can we have a method name same as class name in java?
Yes we can have method name same as class name it won’t throw any compilation error but it shows a
warning message that method name is same as class name
...
Constructors can’t be inherited in java
...
156) Can Static methods access instance variables in java?
No
...
When we try to access instance variable in
static method we get compilation error
...
But to access static
variables or static methods we use Class name in java
...
If we have a static method in superclass and subclass with same
signature then we don’t say that as overriding
...
Objects are instances of class that resides in heap memory
...
There is no alternative way to
access objects except through references
...
Reference is a variable which is used to access contents of an object
...
160 ) Objects or references which of them gets garbage collected?
Objects get garbage collected not its references
...
Before the object gets garbage collected garbage
collector will call finalize() method to free the resources
...
162) Can we able to pass objects as an arguments in java?
Only references can be passed to a method not an object
...
The
largest amount of data that can passed as parameters are long or double
...
Prior to java 1
...
From java 1
...
Wrapper classes are immutable in java
...
164) Explain different types of wrapper classes in java?
For every primitive in java we have corresponding wrapper class
...
Primtive
Wrapper Class
boolean
Boolean
int
Integer
float
Float
char
Character
byte
Byte
long
Long
short
Short
165) Explain about transient variables in java?
To save the state of an object to persistent state we use serialization
...
Example : public Class Car implements serializable
{
transient int carnumber;
}
166) Can we serialize static variables in java?
Static variables cannot be serialized in java
...
Example : int a =10;
long b=a;
There are two types of conversion in java:
1)
Widening conversion
2)
Narrowing conversion
168) Explain about Automatic type conversion in java?
Java automatic type conversion is done if the following conditions are met :
1)
When two types are compatible
Ex : int, float
int can be assigned directly to float variable
...
Ex : int, long
32
Int can be assigned directly to long
...
Widening Conversion comes under Automatic type conversion
...
Narrowing conversion has to be done manually if destination type is smaller than source type
...
Cast is nothing but explicit type conversion
...
170) Explain the importance of import keyword in java?
Import keyword is used to import single class or package in to our source file
...
We use wild character (*) to import package
...
1)
Package names should be in small letters
...
Example : com
...
sales
...
class files are saved is referred as classpath
...
class files by using the
class path specified
...
CLASSPATH
environment variable can contain more than one value
...
Example to set class path from command prompt :
set CLASSPATH= C:Program FilesJavajdk1
...
0_25bin;
...
Java compiler will look for appropriate packages and
classes
...
Jars are created by using Jar
...
Jar files contains
...
Manifest file contains class name with main method
...
class files
...
class files without uncompressing this jar
...
instance variables
remain in memory till the instance gets garbage collected
175) Explain the scope or life time of class variables or static variables?
Static variables do not belong to instances of the class
...
Static variable remain in memory till the life time of application
...
When the method is created local
variables gets created in stack memory and this variable gets deleted from memory once the method
execution is done
...
0 we can import static variables in to source file
...
The advantage of static import is we can access static variables without class or
interface name
...
classname
...
abc
...
eno;
To import all static variables from a class in to our source file we use *
...
abc
...
*
33
178) Can we define static methods inside interface?
We can’t declare static methods inside interface
...
only
public and abstract modifiers are permitted for interface methods
...
methodName(); only public & abstract are
permitted”
...
An interface is also defined as pure or 100
percent abstract class
...
A class implementing interface overrides all the abstract methods defined in interface
...
180) What is the purpose of interface?
Interface is a contract
...
When we are defining
interface we are defining a contract what our class should do but not how it does
...
The power of interface lies when different classes that are unrelated can
implement interface
...
181) Explain features of interfaces in java?
1) All the methods defined in interfaces are implicitly abstract even though abstract modifier is not
declared
...
3) variables declared inside interface are by default public, static and final
...
5) we cannot declare static methods inside interface
...
7) Unlike class, interface can extend any number of interfaces
...
9) An interface can extend a class and implement an interface
10) Multiple inheritance in java is achieved through interfaces
...
0
...
We use enum
keyword to declare enumeration
...
Each enum
constant declared inside a enum class is by default public , static and final
...
183) Explain restrictions on using enum?
1) Enums cannot extend any other class or enum
...
3) We can declare fields and methods in enum class
...
184) Explain about field hiding in java?
If superclass and subclass have same fields subclass cannot override superclass fields
...
If we want to use super class variables in subclass we use
super keyword to access super class variables
...
It simplifies creation of methods when there are more number of arguments
...
Ex : public static void main(String[] args)
A variable length argument is specified using ellispses with type in signature
...
There is no need for null check if no arguments are
passed
...
So when the variable is out of scope those
variables get garbage collected
...
Starting with Java 7 we can use
strings in Switch statement
...
188) In java how do we copy objects?
In Java we cannot copy two objects but by assigning one reference to other we can copy objects
...
so when we declare r2=r1, we are assigning
reference r1 to r2 so now r2 points to the same object where r1 points
...
Oops concepts interview questions
189) Explain about procedural programming language or structured programming
language and its features?
In traditional programming language to solve a problem we use set of procedures
...
Features :
1)
In this top down approach is followed
...
2)
Concentrate more on functions and procedure rather than data
...
4)
Very little concentration on minute details
The main drawback of traditional programming languages works well only for small problems
...
Ex : C language, Pascal
190) Explain about object oriented programming and its features?
Java replaced traditional programming language developed in 1970’s
...
In this language bottom up approach is followed
...
Features :
1)
In this bottom approach is followed
...
2)
Concentrate more on data and give less importance for implementation
...
191) List out benefits of object oriented programming language?
1) Easy maintenance
2) Code reusability
3) Code extendability
4) Reliable
192) Differences between traditional programming language and object oriented programming
language?
Traditional Programming language
Object Oriented Programming Language
A program is divided in to modules and procedures
...
Implementation is done through procedures
...
In traditional programming there is no
In oops encapsulation is done by tightly coupling
encapsulation all procedures access data
...
Suitable for small programs or problems
Suitable for large programs and complex problems
...
Encapsulation exposes only part of object which are safe to exposed
and remaining part of object is kept secured
...
There are four types of access control
specifiers(public,private, protected, default) in java which supports encapsulation
...
195) What is inheritance ?
Inheritance is one of the important feature of object oriented language
...
For example a child acquires the features of their parents
...
The original class is called base class, parent class or super class
...
We use extends keyword in java to extend a class in java
...
lang
...
When we create a new class by using inheritance ‘is-a’ relationship is formed
...
We can avoid duplicating code by using
inheritance
...
For example if we take Ms word we came across number of versions of msword such as word 2003,2007
...
197) What is polymorphism in java?
Polymorphism is combination of two greek words which mean many forms
...
59) What is covariant return ?
In java 1
...
From Java 1
...
(Return type must be subtype of other method)
...
5 return type for doSomeThing() in Class B is valid
...
4 and
earlier
...
Java collections framework provides
set of interfaces and classes for storing and manipulating collections
...
util package and java
...
concurrent packages
...
4)
Reduces programming effort
...
199) What is collection ?
A collection is a container which holds group of objects
...
Collections manages group of objects as single unit
...
Here are few basic operations we do on collections :
1)
Adding objects to collection
...
3)
Retrieving object from collection
...
200) Difference between collection, Collection and Collections in java?
collection : represent group of objects where objects are stored
...
Collections : Collections contains some utility static methods that operate on collections
...
Collection extends Iterable
interface and inherits iterator method which returns Iterator object
...
Returns true if element is added
...
Return
o);
true if matching object is removed from collection
...
Returns true
addAll(Collection
if all elements are added
...
Returns true if all the elements are removed
...
boolean isEmpty();
Checks whether collection contains elements or not
...
boolean contains(Object Checks whether specified object is in collection or not
...
Iterator
Used to iterator over collection
...
boolean
Removes all the elements which are not in specified collection
...
c);
Object[] toArray();
Returns an array of elements in collection
...
We can even store duplicate elements in list
...
List is an ordered collection
...
37
Some of the operations we can perform on List :
1)
Adding an element at specified index
...
3)
To get the index of element
List contains some specific methods apart from Collection interface methods
...
This method returns an element at specified
position in the list
...
This method inserts the specified element with the
index specified
...
indexOf() method returns the index of last
occurrence of specified element
...
Returns a list iterator of elements in list
...
205) List implementations of List Interface ?
1) ArrayList
2) Vector
3) LinkedList
206) Explain about ArrayList ?
ArrayList is an ordered collection which extends AbstractList and implements List interface
...
We can insert nulls in to arraylist
...
public class ArrayList
RandomAccess, Cloneable, java
...
Serializable{}
implements List
From java 1
...
Advantages :
1)
Faster and easier access
...
Drawbacks :
1)
We cannot insert or delete elements from middle of list
...
ArrayList : It is an ordered collection which grows dynamically
...
ARRAY
ARRAY LIST
1)
While creating array we have to know the 1)
But it is not required to know size while
size
...
2) To put an element in to array we use the
2) We can add element to arraylist with following
following syntax :String array[] =
syntax :List
newString[5];array[1] = “java”;We must know ArrayList
...
If we try to put element in index which is
out of range we get ArrayIndexOutOfBounds
Exception
3) Arrays are static
3) ArrayList is dynamic
4) We can store objects and primitives
4) We can store only primitives prior to 1
...
From
1
...
5) We have to manually write logic for inserting 5) Just a method call would add or remove
and removing elements
...
6) Arrays are faster
6) Arraylist is slower
...
208) What is vector?
Vector is similar to arraylist used for random access
...
vector size increases or decreases when elements are added and removed
...
vector and Hashtable are the only collections since 1
...
Rest of the collections are added from 2
...
public class Vector
RandomAccess, Cloneable, java
...
Serializable
209) Difference between arraylist and vector ?
Both ArrayList and vector grows dynamically
...
2)
Vector is legacy collection introduced in 1
...
0
...
210) Define Linked List and its features with signature ?
Linked list is used for storing a collection of objects that allows efficient addition and removal of elements
in the middle of the collection
...
Similarly with remove if we want to remove
an element we need to remove the element and move the list of elements
...
Linked list class is in java
...
Linked List class extends class extends AbstractSequentialList and I mplements List, Deque, Cloneable
and Serializable
...
io
...
2)
public E getLast() :
getLast() returns the last element in the list
...
4)
public E removeLast() :
39
removeLast() method removes the last element in the list
...
6)
public void addLast(E e) :
Inserts the element at end of the list
...
Iterator is a standard way to
access elements one by one in collection
...
Steps for accessing elements in Iterator :
1)
Obtain Iterator object by calling iterator() method on collection
...
iterator();
2)
Call hasNext() method on iterator object in loop as long as hasNext() returns true
...
hasNext())
{
}
3)
Get each element by calling next() inside the loop
...
hasNext())
{
String str=itr
...
hasNext() points to position
before first lement
...
E next();
Returns the next element in the iteration
...
next() will move the pointer to
next position and returns the element
...
Note : If we call next() on last element it will throw java
...
NoSuchElementException
...
If there is next element we can call
next() so that we can avoid exception
...
For example : for list traversal order will be sequential, and for set the order cannot be determined, and
for sorted sorted set will sort the elements in sorted order
...
212) Explain ListIterator and methods in ListIterator?
List Iterator is similar to Iterator but ListIterator is bidirectional
...
List Iterator extends Iterator and all the methods in Iterator will be there in ListIterator too with some
additional methods
...
Position of List Iterator lies between two elements i
...
Features of ListIterator :
1)
Traversal of List in either direction
...
3)
Access to elements position
...
boolean hasNext(); Returns true if there are more elements in the list instead of throwing exception if
there are no elements
...
NoSuchElementException is thrown if there is no next
element
...
hasPrevious();
E previous();
Returns the previous element in the list
...
If there are no
elements it returns the size of the list
...
If there are no
previousIndex();
elements it returns the size of the list
...
void remove();
Removes the element that was returned by calling next() or previous()
...
void set(E e);
This method replaces an element in the list with the specified element
...
Set internally implements equals() method which
doesn’t allow duplicates
...
Set interface is
implemented in java
...
set package
...
It has only
collection methods
...
ArrayList is an ordered collection
...
But coming
to set it is an unordered collection
...
2)
Removing an element from set
...
4)
Iterating through set
...
Features of Hashset are :
1)
It does not allow duplicates
...
3)
It is unsorted and unordered set
...
5)
Allows insertion of nulls
...
public class HashSet
implements Set
...
Serializable
{
}
216) Explain Tree Set and its features?
TreeSet implements navigableSet interface and extends Abstract set
...
Features of Treeset are :
1) It does not allow duplicates
...
41
public class TreeSet
implements NavigableSet
...
Serializable
{
217) When do we use HashSet over TreeSet?
If we want to search for an element in collection and does not want any sorting order we go for HashSet
...
2)
Fast insertion and retrieval of elements
...
public class LinkedHashSet
extends HashSet
implements Set
...
Serializable {
}
Linked HashSet is similar to HashSet but in linked HashSet we maintain order but in HashSet we don’t
maintain order
...
219) Explain about Map interface in java?
A map is an association of key-value pairs
...
Features of map :
1)
Maps cannot have duplicate keys but can have duplicate value objects
...
lLinked hashmap gurantees order of elements
...
Linked HashMap uses internally double linked lists
to keep insertion order
...
2)
HashMap if faster for insertion and deletion of elements when compared to linked hashmap
...
public class LinkedHashMap
extends HashMap
implements Map
{
}
221) What is SortedMap interface?
SortedMap extends Map interface
...
By default sorted map maintains natural ordering if we want custom order we can specify using
comparator
...
When collection framework was started Hashtable extends Dictionary class and Map interface
...
Hashtable does not allow nulls either keys or values
...
223) Difference between HashMap and Hashtable?
Difference
HashMap
Hashtable
Synronization
HashMap is not synchronized
...
Nulls
HashMap allows atmost one null key Hashtable does not allow null values
...
Performance
Since HashMap is not synchronized its Performance is slower when compared to
performance is faster than Hashtable
...
Introduction
HashMap introduced starting from
Hashtable is even before collection
42
collection framework
...
224) Difference between arraylist and linkedlist?
Difference
Arraylist
Access
Implements RandomAccess interface we
can search randomly all the elements
in the list
...
Addition and removal of
Adding and removal of elements in
elements
random positions is slow
...
Similarly for removing the
element we need to follow the same
thing
...
Searching and retrieval of
elements is slow because of
sequential access to elements
...
225) Difference between Comparator and Comparable in java?
Sno
Comparator
Comparable
1
...
util package
Defined in java
...
2
...
different instances
3
...
Ex :
custom sorting
...
employeeId is natural sorting
...
Should override int compare(T o1, T Should override public int compareTo(T o) method
o2) method which takes two
which takes one instance
...
5
...
sort(list);
collections
...
util
...
Concurrent HashMap extends Abstract Map and implements concurrent Map
...
]It is similar to Hashtable and synchronized version of hashmap but with minor differences
...
227) Difference between Concurrent HashMap and Hashtable and
collections
...
The main advantage of this mechanism is better concurrency instead of synchronizing every method by
using common lock which allows only one thread to access at a time, it allows better concurrency by
allowing multiple threads to access
...
228) Explain copyOnWriteArrayList and when do we use copyOnWriteArrayList?
copyOnWriteArrayList is used in multithreaded environment
...
synchronized(list) and
iterate over the list in synchronized block to avoid concurrent modification exception
...
43
The advantage of using copyOnWriteArrayList is no need to synchronize list explicitly
...
229) Explain about fail fast iterators in java?
When iterator iterates over collection, collection should not be modified except by that iterator
...
Such kind of iterators are fail fast
iterators
...
Almost all the iterators implemented in collections framework are fail
fast
...
It does not throw concurrent modification exception because when other thread was iterating it does not
modify original list but creates a copy of list with modified contents so that the iterator won’t know the
modifications made to original list
...
Serialized object is an object represented as
sequence of bytes that includes objects data, object type, and the types of data stored in the object
...
2)
Communication :
To pass an object over network by making remote procedure call
...
4)
To distribute objects across different JVMs
...
XML based data transfer : We can use JIBX or JAXB where we can marshall our object’s data to xml and
transfer data and then unmarshall and convert to object
...
234) Explain about serializable interface in java?
To implement serialization in java there is an interface defined in java
...
Java
...
Serializable interface is an marker interface which doesnot contain any any methods
...
Syntax:
public interface Serializable {
}
235) How to make object serializable in java?
1) Our class must implement serializable interface
...
2) We use ObjectOutputStream which extends OutputStream used to write objects to a stream
...
This 64 bit long value is a hash code of the class
name,super interfaces and member
...
Whenever an
object is serialized suid value will also serialize with it
...
If the loaded class suid does not
match with suid read from object stream, readObject throws an InvalidClassException
...
But it is recommended to have suid
rather than JVM creating because at run time JVM has to compute the hashcode of all the properties of
class
...
We can’t serialize static fields one exception to this is suid
where suid gets serialized along with the object
...
The reason being static variable are class variables that belongs
to a class not to object, but serialization mechanism saves only the object state not the class state
...
If we don’t make reference objects serializable then we get
NotSerializableException
...
During deserialization transient variables are initialized with default values for primitives and null for
object references
...
com/blog/2015/07/01/327-interview-questions-java-developer/
45
Title: Java Interview Questions Guide
Description: This collection of Java Interview Questions covers essential topics to help you ace technical interviews. From core concepts like OOP principles, data types, and control structures to advanced topics such as multithreading, collections, and JVM architecture, these questions provide a thorough review. Prepare effectively with clear explanations and practical examples, ensuring you're ready for coding interviews and technical assessments.
Description: This collection of Java Interview Questions covers essential topics to help you ace technical interviews. From core concepts like OOP principles, data types, and control structures to advanced topics such as multithreading, collections, and JVM architecture, these questions provide a thorough review. Prepare effectively with clear explanations and practical examples, ensuring you're ready for coding interviews and technical assessments.