Java Interview Questions and Answers
Java Interview Questions and Answers
Interview Theory:-
--
1)What are the main features of Java?
-->
java is high programming and widely use language which are having some key features like.
1) object oriented- java supports oops principles and implements like Encapsulation,
Inheritance , polymorphism, Abstraction.
2)platform Independent- java is design as platform independent which achieved through the
JVM, which allows program to be executed from any device or OS which is having the JVM..
the principle write once and run anywhere encapsulates this feature.
3)secure
4)robust -java provides the robust exception handling and automatic garbage collection
mechanism.
5)simple and easy to learn - java syntax's are relatively Straightforward.
6)Multithread- java has built-in support for multithreading, so we can run multiple thread
concurrently.
7)High-performance.
---
2)Explain the concept of Object-Oriented Programming (OOP) and how it is implemented in
Java.
-->
Oops is an methodology to design the program or software using different classes and
objects. in which software is organised as combination of different objects incorporates with
data and behaviours. it provides code reusability, modularity and clear structure. it helps to
design, develop and maintain complex software Systems.
In java we are implementing in some concepts which is Encapsulation, Inheritance,
polymorphism, Abstraction.
----
3)What is the difference between == and .equals() in Java?
-->
i) "==" operator compares the references of two objects not their content. however ".equals"
compares the contents of two objects.
ii) ".equals" is use to compare the String, and "=="" we use for other datatypes.
iii) ex- Str1.equals(str2); and ch=='a' or index==name.indexOf(ch) or flag == true
------
4)Primitives and Non Primitives datatypes in java? String is primitive or non primitive?
-->
Primitive DATATYPE-
whole number-
byte 1byte default is 0
short 2byte
int 4byte
long 8byte
--fraction number
float 4byte default is 0.0
double 8byte
--single Char
char 2byte default is null
--true/false
boolean 1byte default is false
NON Primitive
String not fixed place default is null
-----------------------------------------------
PROTECTED:
protected is a keyword and an access modifier.
method and instance variable can be declared as protected.
protected member having wider visibility then default and lower visibility then public.
protected members can be accessible exactly in the same way as of default in case of same
package.
protected members can be accessible outside of the package provided inheritance happens
and members should be
accessed in a protected way (direct or child class reference type and object is must).
class can never be declared as protected.
PUBLIC:
public is a keyword.
class,instance variable, methods can be declared as public.
public members are accessible within same class, within different classes of same package
and can be accessible outside of the package too.
----------------------------------------------------------
6)How many values will a method return in Java ?
--------------------------------------------------------------
7)Which design patterns have you used to develop frameworks? Explain the same.
-->
i) Page object model(POM).
"every HTML page represented by java object such model known as POM." its a design
pattern.
All the locators and business logic to fulfil the service/facilities/methods related to pages will
be written here.
*advantage of POM-
1. It helps to achieve centralised object repository. so maintenance will be easy.
2. code reusability - to reduce the repetitive code, (ex: should not write repeated login code
again.)
ii) PageFactory--
PageFactory is design pattern like POM. it's an extension of page object Model(POM).
that provides the annotations to initialised the elements automatically. so instead of manually
locating the elements, page factory uses the Annotation @FindBy - to define the initialisation
of element.
so whenever we use the element it will get initialised , its lazy loading.
POM provides reusability and centralised object repository. and PageFactory provide the
these along with find element/element initialisation facility.
----------------------------------------------------------------
Interfaces which have only one abstract methods.. called functional interfaces.
ex;Comparable and comparator and runnable(java 1.0)
Constructor overloading--
constructor will have same name as Class-- para will be different(in terms of No. of para,
type of para or sequence of para).
but constructor don't have any return type explicitly, bcoz implicitly its returning an object of
class.
and cant call constructors like methods explicitly, as it will get called automatically when
object will get created.or IN constructor to constructor calling.
--------------------------------------------------------------------
9) Explain meaning of “System.out.println();”
-----------------------------------------------------------------
10)Explain meaning of “public static void main(String[] args)”
->
Jvm search for the main method as starting point of execution so, it should be visible to JVM,
as JVM is in different package, so thats why Main method is public.
main method is static bcoz, so that Jvm can call main method directly with class without
creating an object.
to just avoid object creation and avoid unnecessary space and memory for obj creation..main
method is Static.
If main method returns anything then it will return to JVM only, we should not return anything
to JVM, should not return anything from main so thats why its return type is void.
-----------------------------------------------------------------------------------------------
---------------------------
11) Explain the features of JAVA
-->done above
----------------------------------------------------------------------
12) Is the JVM platform independent?
-->yes
java is platform independent, it achieved through the JVM only, as JVM allows to execute the
program in any device on any OS which is having JVM. SO encapsulated the principle the
"write once and run anywhere".
-----------------------------------------------------------------------------------------------
--------------
13)What are Wrapper classes? Why do we use them when we have primitive data types?
-->
Each primitive type has a corresponding wrapper class:
ii)Auto boxing and Unboxing: Java provides auto boxing (automatic conversion of primitives
to wrapper objects) and unboxing (automatic conversion of wrapper objects to primitives).
This feature simplifies the interaction with collections and other APIs that require objects.
List<Integer> numbers = new ArrayList<>();
numbers.add(5); // auto boxing: int to Integer
int number = numbers.get(0); // unboxing: Integer to int
-----------------------------------------------------------------------------------------------
-------
14) Can we make local variable static or final?
-->
local variables mean which declared inside the method, which has life throughout the method
only.. and static meaning is shared copy or single copy throughout the class. so we can't
make local variable as static.
--------------------------------------------------------------------------------------------
15) Can we use same name for local and instance variable? If yes, how to access instance
variable in the method?
-->yes,
we can use, but local variables will have high priority than instance, so if u want to use
instance veriable in method have to use 'this' keyword, which represent the current class
object, and can call current object instance variables.
--------------------------------------------------------------------------------
16) Is string a class or a data type ?
-->String is a class as well as non-primitive Datatype.
----------------------------------------------------------------
17)Do you know the usage of access specifiers or access modifiers?
-->"- In Java, Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member
- It provides security, accessibility, etc. to the user depending upon the access modifier used
with the element.
- Access modifiers are: private, default, protected, public".
------------------------------------------------------------------------------------
18) Can you tell me difference in between protected and public.
-->
protected is keyword,
method, variable, constructor can be protected.
it has wider visibility than private and default as protected members can be accessible in
same class and same package also..
and if we want to access the protected members outside the package.then there should be
inheritance provided and should create an childs object and should access the methods and
variables on child object.
----------------------------------------------------------------------------------------------
20) What is range of datatype byte?
What will happen if I try to store value outside its Range?
How to do typecasting?
What will be output, if I do:
byte b = (byte) 130;
-->
byte-- 1byte -- 8bite
If we store the value outside the Range then Compiler give an error.
if we want to fit the value within range of return type then we have to type cast it with same
data type.
but we have written byte b= 130 -- compiler will never give an error , it will calculate
circularly we have to fit that in byte range
-----------------------------------------------------------------------------------------------
------------------------------
21)Can we import same class twice? Like below:
import p1.p2.A;
import p3.A;
If not, what is the reason behind that?
-----------------------------------------------------------------------------------------------
-------------
22)Explain Encapsulation. Can you tell if java provides default encapsulation? Can you tell me
how? What do you mean by proper encapsulation? Can you explain it by an example?
---java provides the default encapsulation, as variables and methods are binding in single
entry call class, so its default encapsulation by java.
class School(){
String name = "";
display(){
SOP(name);
}
}
class Car{
void display(){
System.out.println(speed);
}
in this case , this class is not logically correct, speed can not be in negative so we should
make sensitive data as private means speed and should use proper condition while modifying
or updating this sensitive data.
class Car{
void display(){
System.out.println(speed);
}
-----------------------------------------------------------------------------------------------
---------------------
23.Can you explain what is Inheritance, what are different types of inheritance?
-->
Deriving properties from parent class to child class or superclass to subclass.
inheritance gives ability to reuse the code and with help inheritance we can rewrite the
methods.
Types of Inheritance:-
1. single Inheritance A->B
2. multilevel Inheritance A->B->c->
3. hierarchy inheritance A having 2 child's b and c as well - its like tree.
4. hybrid Inheritance -- combination of hierarchy and multiple inheritance
5.Multiple Inheritance-- NOT allowed in java in terms of classes.
-----------------------------------------------------------------------------------------------
------
24.Can you explain polymorphism. Explain different cases of polymorphism
-->one name, multiple forms means Polymorphism.
there are 2 cases of polymorphism-
overloading( Static /compile time polymorphism)
Overriding (dynamic/runtime polymorphism)
-----------------------------------------------------------------------------------------------
------------
25.Explain Method Overloading and Method Overriding
-->->overloading( Static /compile time polymorphism)
it happens in same class.
method name should be same, parameters should be different, (in terms of , no of
parameters, sequence of parameters or type of paramets should be different.)
return type can be same or different
AM can be same or different
ANM can be same or different
Implementation/body can be anything.
Can you explain what is need of overloading, with the help of example.
->when we want to use diff kind of methods with same name. we need overloading.
class Student{
void m1(){
}
-----------------------------------------------------------------------------------------------
-------------------
26. Explain method hiding concept.
-> when we have static method in parents class and same static method in child class also,
so during the dynamic polymorphism, parent static method will hide the behaviour of child
static method, this is called method hiding.
so S-S overriding not possible.
-----------------------------------------------------------------------------------------------
-----------------------
27.Can we make class as 'protected'?
-->NO.
-----------------------------------------------------------------------------------------------
-----------------------
28) Suppose I have overwritten a protected method, how I can call that method
E.g. Class A [in package p1] has protected method m1. class B [in package p2] extends A,
overwrites m1, how to call m1?
--> we have to create an object of child class on that we can access this overridden method.
means have to create an object of B in this case and then call the methods M1 on that object.
B b = new B();
b.m1();
-----------------------------------------------------------------------------------------------
----------------------
29) What is private class? Can I override the private classes ?
--->
A private class is a class declared with the private access modifier, meaning it is only
accessible within the class that defines it. In most programming languages like Java, you
cannot declare top-level classes as private. However, inner classes (classes defined within
another class) can be private.
you cannot override a private class or any of its methods. Here’s why:
Overriding is the process where a subclass provides a specific implementation of a method
that is already defined in its superclass. Since a private class is not accessible outside of its
containing class, no other class can inherit from it.
Similarly, private methods within a class cannot be overridden because they are not visible to
any subclasses. They are restricted to the class that defines them.
-----------------------------------------------------------------------------------------------
--------------
31) Can we overload final method ?
--> yes, bcoz IN overloading non access modifiers can be same or anything.
-----------------------------------------------------------------------------------------------
---------
32) Can we overload static method ?
-->yes, bcoz IN overloading non access modifiers can be same or anything.
-----------------------------------------------------------------------------------------------
---------
33) Can we override static method ?
--> NO.
-----------------------------------------------------------------------------------------------
---------------------------
34) Can you explain me what is Abstraction?
-> exposing only required features by hiding internal details is called Abstraction.
-> In java, abstraction can be achieved in two ways, either with interface or abstract class.
Interface:
->Interface is keyword.
-> interface can either be declared as public or default
-> all the methods in interface are by default public and abstract.
-> all the variables in interface are by default public static final.
-> interface can have only abstract methods, abstract methods are the one having no body.
-> we can not create object of interface, we can't instantiate interface.
-> Interface is not in hierarchy of Object Class.
-> Interface can extends another Interface.
-> and class can implements the Interface.
but class which is implementing the Interface, has to override the all the abstract methods
from Interface.
->Interface can be use as ref type, but object can not be created for Interface...
->If class implements the interface but dont want to override/implements all the abstract
methods of that Interface.
then that class has to be declare as Abstract class.
->That means, Abstract class can have Abstract methods as well as Concrete methods.
so if u think about partial implementation , abstract class would be the best choice.
and if u think about full implementation/100% abstraction, then probably Interface would be
the best choice.
-> abstract class is exactly similar to concrete class except
1) we can not create object of abstract class.
2) abstract class can have abstract as well as concrete methods.
->any class having directly or indirectly any abstract method then that class has to be
declare as Abstract.
->In Interface, compiler is going to declare all the methods are by default public and
abstract, but its not same case in Abstract class,
In abstract class we have to add these keywords explicitly.
SO Interface is more restrictive, as all methods and variables are public only. where abstract
class is more relax,
here we can create private variables, private/protected methods , static methods..like normal
class.
->only thing is abstract and final OR abstract and Static can not be use together.
->Abstract class can be further extended by any class,
so that class has a responsibility to override abstract methods coming from Abstract Class.
->If the class is not having any Abstract methods sill I am declaring my class as Abstract that
means,
we don't want to expose the class in form of object.we don't want to create an object of that
class. want to restrict the obj creation.
->Abstract class is in hierarchy of Object Class.
-----------------------------------------------------------------------------------------------
----------------
35)What is the difference between abstract class and interface?
-->Both are used to achieve abstraction,
but the significant diff is Interface is having all abstract methods and abstract class can have
abstract and concrete methods as well.
If partial implementation required, Abstract class is best choice..
if we are looking for full implementation then interface would be best choice..
if we are thinking about restrictive way then interface would be best choice.. all variable and
the methods has be public.
in abstract class will get more relaxation.
-----------------------------------------------------------------------------------------------
-----------------------
36) What are the differences between normal and abstract class?
-->abstract class is exactly similar to concrete class except
1) we can not create object of abstract class.
2) abstract class can have abstract as well as concrete methods.
-----------------------------------------------------------------------------------------------
-------------------------
37) Can we instantiate abstract class?
-->NO
-----------------------------------------------------------------------------------------------
--------------------------
38) Can we have static methods in Abstract class?
-->yes we can have the static methods in abstract class provided the method is concrete
method.
-----------------------------------------------------------------------------------------------
--------------------------
39)Does abstract class can have constructor?
--> yes abstract class can have constructor
i)to complete the constructor chaining and
ii)to initialised the parent instance variable while creating an object of child class.
-----------------------------------------------------------------------------------------------
------------------------
40)Explain use of ‘final’ keyword
-->
1) if method is final, method can not be overridden by subclass.
2) if variable is final, variable can not be reinitialised.
3) if class is final, class can not be extended by any other class.
-----------------------------------------------------------------------------------------------
------------------------
41) Explain use of ‘super’ and ‘this’ keyword
-->
this :
this is a keyword in java.
this represents current class object.
this can be used to access current object instance variable.
this can be used to call current class methods.
this can be used to call current class constructor.
IMP:-
this keyword can not be used from static context (method). [done]
this keyword represent the current class object and static methods are not going in object,
so cant use this in static method.
super :
-> super is a keyword
-> When we want to use immediate parent class members (instance variables/methods) from
child class, use super keyword.
-> super can be used to access parent class instance variable.
-> super can be used to call parent class method.
-> super can be used to call parent class constructor.
super keyword can not be used from static method, even from main method as main is static
method.
-----------------------------------------------------------------------------------------------
----------------
42) Define Constructor. What is purpose of constructor in Java?
--> Constructor helps to create an object.
whenever we want to perform any actions/activities while creating an object of class, we
should write that in Constructor.
-----------------------------------------------------------------------------------------------
------------------------
43) What is a constructor in Java? How does it differ from a method?
-->whenever we want to perform any actions/activities while creating an object of class, we
should write that in Constructor.
Constructor helps to create an object.
Constructor have same name as Class.(whenever we are not writing any constructor
explicitly, compiler will add default non parameterised constructor in class which will have
same AM as class.)
constructor does not have any return type explicitly, as its returning an object of class
implicitly.
we cant call Constructor explicitly its automatically getting called while creating an
object or in constructor to constructor calling.
-----------------------------------------------------------------------------------------------
------------------------
44) Constructor chaining, why it is needed.?
--> to create an object of class, Constructor Chaining must be completed, and should get the
permission from object class for object creation, we need constructor chaining till object
class.
-----------------------------------------------------------------------------------------------
------------------------
45)Explain Java’s exception hierarchy.
throwable
error exception
checked/compiletime unchecked exception/runtimeException
IOException indexoutofboundexception(arrayindexofbound/
stringindexofbound)
numberformatexception
-filenotfound inputmissmatch exception
nullpointerException
sqlexceptions classcastException
InterruptedException arithmaticexception
classnotfoundException
-----------------------------------------------------------------------------------------------
------------------------
46)What is the difference between throw and throws in Java?
-->
- throws is used to propagate exception and throw is used to generate exception
- throws is written in method signature and throw is written in method body
- throws is written with exception class name, throw is written with exception class object
- Multiple exceptions can be written with throws, but with throw only one exception can be
written
-----------------------------------------------------------------------------------------------
------------------------
47)Parent class method doesn't throws any checked exception, is it allowed to throw
checked exception from the child class
overwritten method? What are different valid combinations?
-->
when we want to make single object of class throughout the application.so we need
singleton design pattern.
it will make only one object of class throughout the application, if we follow rule of singleton
design pattern.
If we want to apply singleton design pattern on any class, follow 3 simple steps.
-----------------------------------------------------------------------------------------------
-----------------
49)What is Lazy and eager initialisation?
-->
lazy--
class Employee{
private Employee(){
class Client{
main(){
Employee e= employee.getObject();
}
}
-->
eager--
class Employee{
private Employee(){
return e;
}
}
class Client{
main(){
Employee e= employee.getObject();
}
}
-----------------------------------------------------------------------------------------------
------------------------
50) What is the difference between Array and ArrayList?
Array is grp of elements, its block, not class and Array can not store heterogeneous object
without size limitations. and also limitations on data manupulation and also limitations on
performing operations while adding or inserting elements to array.
ArrayList- is class , we create object of this so all methods or data manipulations methods
will go to memory.
arrayList is contiguous block and can store heterogeneous object without size limitations,
data manipulation is also easy with arraylist.
-----------------------------------------------------------------------------------------------
------------------------
51)Difference between array list and linked list
when more searching operations - ArrayList is best choice as array list is contiguous block
and searching complexity is order of 1.
but addition/deletion complexity is order of nth.
whereas, linked list is in skittle way-- searching complexity is order of nth. as multiple
blocks/nodes.
addition/deletion complexity is order of 1...
So, if addition/deletion operations are more, linked list will be good choice.
-----------------------------------------------------------------------------------------------
------------------------
52) If you want to store elements, what would you prefer - ArrayList or LinkedList?
--> if no addition/deletion operations, only store then ArrayList .
-----------------------------------------------------------------------------------------------
------------------------
53)What is HashMap ? Can we store objects in hash map and how to retrieve them?
hashMap is class in Map interface, it stores the key and value pair, and keys ordering will be
based on hashcode.
we can store the objects in hashMap in values and can retrieve those by using "get()"
method.
list- maintain the insertion order , allows duplicate and index based operations are allowed.
having 3 classes- ArrayList, linkedList, vector
-----------------------------------------------------------------------------------------------
-----------------
55)How to iterate list and set, can we use list iterator to iterate set?
-->
we can iterate the list by using simple for loop, while loop, enhance loop and also using
Iterator also.
and for set we can use enhance loop and also Iterator() method.
-----------------------------------------------------------------------------------------------
-----------------
56)How to convert array into list?
list- maintain the insertion order , allows duplicate and index based operations are allowed.
having 3 classes- ArrayList, linkedList, vector
-----------------------------------------------------------------------------------------------
-----------------
58)Suppose I have added 2 keys and values using put method, would it be inserted in sorting
order in hashmap ?
-->in hash map... keys will get maintained or inserted based on HashCode.
-----------------------------------------------------------------------------------------------
-----------------
59)What is the difference between Hast Set and Tree Set?
hashSet-- duplicates not allowed , ordering will be maintain using hashCode, one null object
is allowed.
Treeset-- natural order maintain.. can use Collection utility class reverse() method as well.
and Null object is not allowed.
-----------------------------------------------------------------------------------------------
-----------------
60) Is it possible to add same keys and values in map ?
->
same key is not allowed. map stores uniques keys only.... same/duplicate values are allowed..
and if u want to use same key again with different value then old value will get override by
new value, but key will be only one which will be unique.
-----------------------------------------------------------------------------------------------
-----------------
61) What is the difference between HashMap and Linked HashMap?
hash map -- maintains the key order based on hashCode.
linked hashMap-- it maintains the insertion order of keys.
SO, in terms of performance hashMap is better than LinkedHashMap.
-----------------------------------------------------------------------------------------------
-------------------
62)
If(s1==s2) then tell me if it's true or false in below example and the reason behind it.
String s1= "hello"; String s2="hello";
-->
--- if its true--
reason:- both String s1 and s2 are pointing to same Constant(string-hello) in constant pool,
as here objects has not created. so its in SCP only.
so == will be true.
---it will come false in such condition when will create object of both, both will go in HEap
memory at different places. then only it will compare to MA by using == and it will give false.
in same condition if we use .equals then it will give true as it will compare the content.
-----------------------------------------------------------------------------------------------
--------------
63)
What will be the output
int getNum(){
try{
System.out.println(1/0);
return 1;
}catch(Exception e){
return 3;
}catch(ArithmeticException ae){
return 2;
}finally{
return 4;
}
}
--> here answer is - will get compilation error as in catch series, we have parent 1st and then
child so child block will be unreachable...
BUT
ii)--if child was 1st then answer will be return 4..
but if we had exit(0/1) anywhere like in try or catch/finally then it will terminate the program
on that line only.
--exit will get higher priority. before exit statement, everything will get execute/print.
-----------------------------------------------------------------------------------------------
-----------------
64) Tell me different combinations of Try, catch, finally which are allowed in java.
->
1)
try{
}catch(){
------------------
2)
try{
}
catch(){
}finally{
--------------------
3)
try{
}finally{
--------------
4)
try{
}catch(){
}catch(){
}catch(){
}finally{
-----------------------------------------------------------------------------------------------
-----------------
65)How to create your own Exceptions?
-> create a class, fit that class into exception hierarchy. [extends Exception]
-> create appropriate constructors. (parameterised and non-parameterised constructor.)
-> pass message using super constructor.
-----------------------------------------------------------------------------------------------
-----------------
66) try block has exit method, catch block has exception and finally block is returning an int
value. Can you explain the flow of execution?
try{
SOP(1);
exit(0);
}catch(){
x=y/0;
}finally{
return int x;
}
once we get exit method, at the point only program will get terminate, and rest flow will
stop.. so here we got the exit in try block only..
so before exit whichever the statements over there will get executed and printed and then
program will get terminated.. will not go to any block.
-----------------------------------------------------------------------------------------------
-----------------
67)Which catch block will get execute first.
There are two catch blocks in first catch block have exception e and second catch block have
arithmetic exceptions and will expect arithmetic exception in try block then which catch
block will get execute first?
---> will get compilation error as we have parent exception in 1st catch block and then
arithmatic exception..
so will get CE.
-----------------------------------------------------------------------------------------------
-----------------
68)What is mutable and immutable?
-----------------------------------------------------------------------------------------------
-----------------
69)What is string buffer and string builder?
String buffer and String builder both are mutable classes. it allows to change/place values at
same memory location.
-----------------------------------------------------------------------------------------------
-----------------
70)How do you say JAVA is platform independent?
--> bcoz java enables the principle write once and run anywhere.
Java is design as platform independent which achieved through the JVM, which allows
program to be executed from any device or OS which is having the JVM..
-----------------------------------------------------------------------------------------------
------------------
71)Which one is platform independent out of JDK/JRE/JVM?
--> JRE
--> JRE
-----------------------------------------------------------------------------------------------
----------------
73)When do you use a try-catch block?
--> when we have possibility to get the exceptions so to just handle at calling time.
we use try catch block..
try{
//abnormal situation here --
}
catch(exception name and reference variable){ --for Ex (ArithmeticException ae)
-----------------------------------------------------------------------------------------------
----------
74)What does "static" mean in Java?
-->static is non access modifier in java..
static means shared copy or single copy throughout the class.
so static members or methods will get 1st place in memory before creating an object.
so such type of methods/variables we can access directly call/access with class name,
without creating an object.
-----------------------------------------------------------------------------------------------
----------
75)Where do we use ‘default’ keyword in java.
--> we use default keyword in switch case, for any negative or invalid statements.
like else only..
-->default is access modifier, but we don't have default keyword explicitly, whenever we are
not having any modifier specified for any method variable or class. then we declare it as
default.
-----------------------------------------------------------------------------------------------
-------------------
-----------------------------------------------------------------------------------------------
-----------------
77)What is the difference between collection and collections? OR What is collection &
collections in java
collection-- its framework/interface --having the list and set as child interface.
collections--Its utility class -- having all supporting static methods to perform operations on
list Interface.(ex: Collections.sort/reverse)
-----------------------------------------------------------------------------------------------
-----------------
78)What is the return type of Collections.sort() method ?
-----------------------------------------------------------------------------------------------
-----------------
79) Does HashTable allow storing null keys.?
-->NO, HashTable doesn't allow to store null keys as well as null values.
-----------------------------------------------------------------------------------------------
-----------------
80)How maps are stored in memory?
--> Maps stores in key value pair. each key will be unique.
--internal HashMap
-->
The moment we create HashMap, it occupies the space for 16 buckets.all buckets are store in
contiguous means that buckets are store as an Arraylist.
i)put method:-
so when we use put method... we are trying to store key and value in map.
now, hm.put("disha","gupta");
disha having hashcode 100 -100%16 ==4 then disha and gupta will store at 4th block in
bucketlist.
now, hm.put("tejas","phase");
tejas having hashcode 98---98%16 == 2 --its will be stored at 2nd block in bucketlist where
maulik, kanani is already there.
SO ,when two different entries(key,value pair) wants to store in same bucket, that creates
"collision situation."
so map has resolved this situation as,
every bucket maintain linkedlist- and all node will be stored as linked list within bucket.
every bucket maintain linkedlist- and all node will be stored as linked list within bucket.
SO now tejas will be store in linked list on 2nd bucket as 2nd node.
so it will go to that 4th bucket and it will search that key is already present there or not,
using .equals method on key.
so we are already having disha with gupta.... so same key is there, so will replace the old
value with new..and return old value.
disha.equals(disha);
iii) hm.get():-
it will check every node in that bucket.. by using .equals method.. it will compare tejas key
with other keys..
with other keys..
once get the tejas at any node it will return the value of Tejas key...
** if some keys are not present in bucket.. then it will return NUll, as key is not available..
-----------------------------------------------------------------------------------------------
-----------------
81)What is the return type of Hashcode()?
-->int
-----------------------------------------------------------------------------------------------
-----------------
-----------------------------------------------------------------------------------------------
-----------------
83)When a class implements two interfaces having a common method, which interface
method does the class implement?
-->(corner case.)
interface SrManager {
void displayReport(); //3 month
}
So in above example,
--having same method with same parameter but having different purpose
displayReport(),then
in such condition ,use
--Two different classes to implements the interface, In one class one method will get
override.
--otherwise pass different parameters and create overloaded method and implements in one
class.
-----------------------------------------------------------------------------------------------
---
84) Explain concepts in collections and relate to your project.
Collections Framework :
-> To store heterogeneous objects without size limitation we need Collections framework.
-> Collections framework gives better data manipulation.
--------------------------------------------------------------
Collection (i) extends SearchContext
1) List (i)
1.1) ArrayList (IMP)
1.2) LinkedList
1.3) Vector
2) Set (i)
2.1) HashSet (IMP)
2.2) LinkedHashSet
2.3) TreeSet
-------------
3) Map (i)
3.1) HashMap (IMP)
3.2) LinkedHashMap
3.3) TreeMap
3.4) HashTable
So Map is part of Collection framework but its parent is not Collection interface.
1) List (i) -->normal for/while loops and enhance loop and iterator can use
duplicate allowed, insertion order maintain, sort can use , index base all operation
allowed.all methods same in 3, but memory different, NON thread safe class
1.2) LinkedList
duplicate allowed, insertion order maintain, sort can use, all methods same in 3, NON
thread safe class
1.3) Vector
duplicate allowed, insertion order maintain, sort can use , all methods same in 3
Vector is legacy class(introduced in JAVA 1.0 ) all methods are synchronised, it is
thread safe class
2) Set (i) Enhance loop and iterator any allow.(so normal for loop cant used).
UNIQUE (duplicate not allowed), index based all operation NOT allowed.
according to hash code order will maintain -- 1null object allow, doesn't maintain key
pair like Hash map.
2.2) LinkedHashSet
2.2) LinkedHashSet
2.3) TreeSet
natural order means ascending, we can use collection.reverse()-as well to reverse, Null
not allowed as object.
NON thread safe class1, 1 null key allowed, any number of null allowed as value ,acc
hashcode of key it will maintain order
3.2) LinkedHashMap
NON thread safe class, sequentially insertion order maintain ,1 null key allowed, any
number of null values allowed a
3.3) TreeMap
NON thread safe class, ascending order/natural order maintain, null key not allowed.
3.4) HashTable
looking for to store key and value and want thread safe class, all methods are
synchronised..
other things same as HashMap - acc Hashcode it will maintain order
HashTable is legacy class(JAVA 1.0 me intro hue)
Not only for key but for value also NULL is not allowed
-----------------------------------------------------------------------------------------------
--------------------
85) What is a class and object?
->
Binding of data members (variables) and member functions together in a single entity called
class.
A class defines the general structure and behaviour
class can be public, final or abstract.
-----------------------------------------------------------------------------------------------
--------------------
86) How to call the function of a Class without creating an object?
-> use the static keyword in-front of methods, means declare the method as static,
so we can call/access that method/function with class name directly, without creating an
object.
class A{
-----------------------------------------------------------------------------------------------
--------------------
87) Why main() method is declared as static?
-->
Its static bcoz, JVM can directly called main method with Class. to avoid unnecessary
memory and time);
It should be public bcoz JVM is outside the package. main method should be visible to JVM
so its public.
return type is void bcz.. we don't want to return anything from main method..... (it will return
to JVM if we pass anything then.)
-----------------------------------------------------------------------------------------------
---------------------
88)Is there any way to deallocate memory in JAVA?--
-->There is no explicit term for deallocation of memory in JAVA like we have in c and c++ but
with the help of Garbage collector we can clean up the sapce for which is not in use ..
when constant/object having reference count as 0. GC will automatically clean the memory.
-----------------------------------------------------------------------------------------------
---------------------
89)What is multithreading in Java? How is it achieved?
-->
Concurrent execution of multiple threads in a single program called multithreading,It allows a
program to perform multiple tasks simultaneously.
It Can be achieved-
By Extending the Thread class.
By Implementing the Runnable interface.
-----------------------------------------------------------------------------------------------
---------------------
90)How can you create a thread in Java?
There are two ways--
Example--
@Override
public void run() {
getNamePrint();
}
void getNamePrint() {
for (int index = 0; index < 100; index++) {
System.out.println(index);
}
setName("jyoti");
System.out.println(getName());
int num = getPriority();
System.out.println(num);
}
}
public class Employee2 extends Thread {
@Override
public void run() {
getQuote();
}
void getQuote() {
for (int index = 101; index < 200; index++) {
System.out.println(index);
}
setName("Nikam");
System.out.println(getName());
setPriority(10);
System.out.println(getPriority());
}
}
void getProcessData() {
Employee1 emp1 = new Employee1();
Employee2 emp2 = new Employee2();
emp1.start();
emp2.start();
System.out.println(Thread.currentThread().getName());
}
--
So here, need to 1st call start() method, it will call run() method internally.
-----------------------------------------------------------------------------------------------
--------------------
91)What is synchronisation in Java? Why is it used?
use:-
Thread Safety: Synchronisation helps in making a class thread-safe, meaning it behaves
correctly when accessed by multiple threads simultaneously.
-----------------------------------------------------------------------------------------------
--------------------
92)How to handle synchronisation?
-----------------------------------------------------------------------------------------------
-----------------
93) In your project, how do you decide when to use Abstract Class and when to use
Interface?
--> when we want to limit the object creation of any class in any layer, we make it as
Abstract.
for example: TestBase and ControlActions class..
-->All the Constant paths can be written in Interface, as will have all the variables as final and
static and can be accesible on reference type of interface.
-->when we want to defined capabilities that we promised to provide, we can use interface.
=====================================================================
==============================================
95).What is return type of any constructor?
-> Constructor can not have any explicit return type, as it is returning the object of class
implicitly.
=====================================================================
=============================================
96).Does abstract class can have constructor?
--> yes, Abstract class have constructor to
i. complete constructor chaining till object class.
ii.and to initialised the instance variables of parent while creating an object of child class.
=====================================================================
==============================================
97).Constructor overriding is allowed or not? Why?
-->
ans : no
no, bcoz we cant write our class name constructor in other class......
to override we need same Constructor name in different class...
it will give error...override is only for methods.
for example--
A parent and B is child...
constructor of A(){}
can't be override in class B----
cant write in class B{
A(){
}
}
=====================================================================
============================================
98).Why constructor cannot be ‘final’?
-->
no. Illegal modifer. --constructor can not be override then it cant be final as well.
=====================================================================
============================================
99).Why constructor cannot be ‘static’?
-->
No, constructor is the entity which helps to construct an object,
hence each object must have own copy of constructor, hence we can't create shared copy or
single copy of constructor.
=====================================================================
==============================================
=====================================================================
=============================================
101).What are different types of the constructors?
-->
i.Default Constructor.
ii.Parameterised Constructor.
iii.Copy Constructor.
=====================================================================
==============================================
102).What are the differences between constructors and methods?
-->
Constructor is eaxctly similar as method excepts two things-
i)Constructor can not have return type explicitly, it is returing an object of class implicitly.
ii)Constructor will be automaticaly called while creating an object. explicitly can not be
called from methods.
=====================================================================
===============================================
103).Can constructor be private?
-->Yes
=====================================================================
===============================================
104).What is role of access modifiers in case of Constructor? [private, default, protected,
public]
-->
Access Modifer on Constructor.
private--outside class not allowed
public, every where allowed.
default ...
1. Object : outside of the package, we can;t create object using default visibility constructor.
2. Parent - Child : outside of the package, parent child relationship is not allowed using
parent class default visibility constructor.
protected ...
1. Object : outside of the package, we can't create object using constructor having protected
visibility.
2. Parent - Child : outside of the package, parent child relationship is allowed if parent class
having protected constructor.
using this protected constructor, we can complete Chaining. can help to parent child
relation..
but cant create object using default constructor.
=====================================================================
===============================================
when we are having multiple common statement in Constructor, we should write in blocks, as
blocks are getting executed before Constructors.
blocks --having no name, no signature, no access modifiers. we cant call it explicitly as it has
no name.
we can have multiple nonstatic or static blocks in class written anywhere.it will get executed
by sequence.
non static block:- how many times we create object of class , those many time non static
blocks/constructors will get executed.
Static block:-
static blocks will go in memory 1st, it will get executed once class loaded into memory.
it will execute one time only, and then main method content will get executed.
static blocks can not travel from parent to child.
Non static blank final variable has to be initialised from ns block or constructors.
static blank final variable has to be initialised from static block only.
*Flow of Execution:-
parent static block
child static block
parent nonstatic
parent constructor
child nonstatic
child constructor
maincontent/methods.
=====================================================================
===============================================
Exception :
-> Any abnormal situation in java is known as Exception. Mechanism to handle such abnormal
situation is known as Exception handling mechanism.
- Any abnormal situation in java occurred during code execution is known as exception.
- It is always observed at runtime
=====================================================================
===============================================
107).Can we write multiple catch blocks with one try block?
-->yes we can.
=====================================================================
============================================
108).Is it a valid combination?
try{
}finally{
}
=====================================================================
============================================
109).Difference between checked and unchecked exception
-->
***Unchecked exception --
-exceptions which are in runtime exception hierarchy,called as Unchecked exception,
-coding related exception.
- Not checked at compile time, they are auto-propagated
=====================================================================
============================================
110)Extra:-
try catch:-can be written in
1.constructor
2.method. (Including main method)
3.Static and non static blocks..