Core Java QA
Core Java QA
Core Java QA
1. What is Java?
Java technology is both general-purpose, class-based, object-oriented
programming language and a platform (a collection of programs that help
programmers to develop and run Java programming applications efficiently)
from Oracle Corporation.
Java was originally developed by James Gosling with his colleagues at Sun
Microsystems during the early 1990s.
Initially, it was called a project ‘Oak’ which had implementation similar to C
and C++.
The name Java has later selected after enough brainstorming and is based on
the name of an espresso bean.
Java 1.0, the first version was released in 1995 with the tagline of ‘write
once, run anywhere’. Later, Sun Microsystems was acquired by Oracle.
The latest version of Java is Java SE15 released on 15th September 2020.
5. What is class?
Class is nothing but different type of entity.
It is useful designing template or blueprint from which individual objects are
created.
Or
A class in Java is a blueprint which includes all your data.
A class contains fields (variables) and methods to describe the behaviour of
an object.
e.g., public class A
{
6. What is Object?
Object is an instance of a class.
Object it means separate copy of memory.
An object is a real-world entity. Every object has 2 things.
1. State
2. Behaviour
State can be change object to object but behaviour will always be same.
State
Behaviour
8. What will be the initial value of an object reference which is defined as an instance
variable?
All object references are initialized to null in Java.
2. JRE –
Java Runtime Environment (to say JRE) is an installation package which
provides environment to only run (not develop) the java program (or
application) onto your machine.
It is also written as Java RTE. It is the implementation of JVM. It physically
exists. It contains a set of libraries + other files that JVM uses at runtime.
JRE is only used by them who only wants to run the Java Programs i.e. end
users of your system.
Note: By mistake if we are using unused keywords in our program, we will get
compile time error.
Conclusion:
All reserved words in java contain only lowercase alphabet symbols.
New keywords in java are:
1. strictfp-----------1.2v
2. assert-------------1.4v
3. enum--------------1.5v
In java we have only new keyword but not delete because destruction of useless
objects is the responsibility of Garbage Collection.
instanceof but not instanceOf extends but not extend
strictfp but not strictFp implements but not implement
const but not Constant import but not imports
syncronized but not syncronize int but not Int
12. Why Main Method is public?
JVM call main method and it can be access from anywhere that’s why it is
public
19. Why main method parameter is string array only? Why not other?
String can hold any java type value in the format of stream.
A person says that he compiled a java class successfully without even having a main
method in it? Is it possible?
Main method is an entry point of Java class and is required for execution of
the program however; a class gets compiled successfully even if it doesn't
have a main method. It can't be run though.
21. What if the static modifier is removed from the signature of the main method?
Program compiles fine.
However, at runtime, It throws an error "NoSuchMethodError."
1. Instance Variables
Instance variables are those variables which are declared inside the class but
outside the method, constructor and block.
If the value of a variable is varied from object to object such type of variables
are called instance variables.
For every object a separate copy of instance variables will be created.
Instance variables will be created at the time of object creation and destroyed
at the time of object destruction hence the scope of instance variables is
exactly same as scope of objects.
Instance variables will be stored on the heap as the part of object.
Instance variables should be declared with in the class directly but outside of
any method or block or constructor.
Instance variables can be accessed directly from Instance area. But cannot be
accessed directly from static area.
But by using object reference we can access instance variables from static
area.
Example:
class Test
{
int i=10;
public static void main(String[] args)
{
//System.out.println(i);
//C.E:non-static variable i cannot be referenced from a
static context(invalid)
Test t=new Test();
System.out.println(t.i);//10(valid)
t.methodOne();
}
public void methodOne()
{
System.out.println(i);//10(valid)
}
}
For the instance variables it is not required to perform initialization JVM will
always provide default values.
Example:
class Test
{
boolean b;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.b); //false
}
}
Instance variables also known as object level variables or attributes.
2.Static/Class Variables
Static/Class variables are those variables which are declared inside the class
with static keyword.
If the value of a variable is not varied from object to object such type of
variables is not recommended to declare as instance variables. We have to
declare such type of variables at class level by using static modifier.
In the case of instance variables for every object a separate copy will be
created but in the case of static variables for entire class only one copy will be
created and shared by every object of that class.
Static variables will be crated at the time of class loading and destroyed at the
time of class unloading hence the scope of the static variable is exactly same
as the scope of the .class file.
Static variables will be stored in method area. Static variables should be
declared with in the class directly but outside of any method or block or
constructor.
Static variables can be accessed from both instance and static areas directly.
We can access static variables either by class name or by object reference but
usage of class name is recommended. But within the same class it is not
required to use class name we can access directly.
Example:
class Test
{
static int i=10;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.i); //10
System.out.println(Test.i); //10
System.out.println(i); //10
}
}
For the static variables it is not required to perform initialization explicitly,
JVM will always provide default values.
Example:
class Test
{
static String s;
public static void main(String[] args)
{
System.out.println(s);//null
}
}
Static variables also known as class level variables or fields.
3.Local Variables
Local variables are those variables which are declared inside method,
constructor and block to meet temporary requirements of the programmer.
local variables are also called as automatic variables or temporary variables or
stack variables.
The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
The local variables will be stored on the stack.
For the local variables JVM won't provide any default values compulsory we
should perform initialization explicitly before using that variable.
It is highly recommended to perform initialization for the local variables at the
time of declaration at least with default values.
28. Can we define more than one public class in a java source code? what is the rule of
public class and file name?
No, we can’t define more than one public class in one source file.
Name of the public class and the file name must match.
31. What is singleton class in Java and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given
time, in one JVM.
A class can be made singleton by making its constructor private.
32. How can we pass argument to a function by reference instead of pass by value?
In java, we can pass argument to a function only by value and not by
reference.
33. Can we have two methods in a class with the same name?
We can define two methods in a class with the same name but with different
number/type of parameters. Which method is to get invoked will depend
upon the parameters passed.
For example in the class below we have two print methods with same name
but different parameters. Depending upon the parameters, appropriate one
will be called:
34. Can variables be used in Java without initialization?
In Java, if a variable is used in a code without prior initialization by a valid
value, program doesn't compile and gives an error as no default value is
assigned to variables in Java.
36. If an application has multiple classes in it, is it okay to have a main method in more
than one class?
If there is main method in more than one classes in a java application, it won't
cause any issue as entry point for any application will be a specific class and
code will start from the main method of that particular class only.
Constructor
1. What is constructor in java? How many types of Constructor, which they are?
Constructor is a block of code that initializes the newly created object.
Constructor has same name as the class and looks like this in a java code.
1. Default Constructor:
If you do not implement any constructor in your class, Java compiler inserts a
default constructor into your code on your behalf and initializes all member
variables to zero. This constructor is known as default constructor. You would
not find it in your source code (the java file) as it would be inserted into the
code during compilation and exists in .class file. This process is shown in the
diagram below:
If you implement any constructor then you no longer receive a default
constructor from Java compiler.
2. no-arg constructor:
As the name specifies the no argument constructors of Java does not accept
any parameters instead, using these constructors the instance variables of a
method will be initialized with fixed values for all objects.
The signature is same as default constructor so some people claim that that
default and no-arg constructor is same but in fact they are not same.
3. Parameterized Constructor:
Constructor with arguments (or you can say parameters) is known as
Parameterized constructor.
Parameters are added to a constructor in the same way that they are added
to a method, just declare them inside the parentheses after the constructor's
name.
From the above example also, it is clear that if we are defining constructor as
final the compiler will give an error as modifier final not allowed.
10. How objects of a class are created if no constructor is defined in the class?
Even if no explicit constructor is defined in a java class, objects get created
successfully as a default constructor is implicitly used for object creation. This
constructor has no parameters.
11. Can we call the constructor of a class more than once for an object?
Constructor is called automatically when we create an object using new
keyword.
It's called only once for an object at the time of object creation and hence, we
can't invoke the constructor again for an object after its creation.
12. Can we use a default constructor of a class even if an explicit constructor is defined?
Java provides a default no argument constructor if no explicit constructor is
defined in a Java class.
But if an explicit constructor has been defined, default constructor can't be
invoked and developer can use only those constructors which are defined in
the class.
13. Can a constructor have different name than a Class name in Java?
Constructor in Java must have same name as the class name and if the name
is different, it doesn't act as a constructor and compiler thinks of it as a normal
method.
Package
1. What is package?
Package is nothing but folder.
It is used for representing group of similar purpose .class file.
The main advantage of package is to overcome name conflict problem.
Static Concept
1. Why we use static keyword in java?
Static keyword is mainly used for memory management.
Static means single copy of memory or it is also called as class level memory.
10. What are the restrictions that are applied to the Java static methods?
Two main restrictions are applied to the static methods.
1. The static method cannot use non-static data member or call the non-
static method directly.
2. this and super cannot be used in static context as they are non-static.
17. In a class implementing an interface, can we change the value of any variable defined
in the interface?
No, we can't change the value of any variable of an interface in the
implementing class as all variables defined in the interface are by default
public, static and Final and final variables are like constants which can't be
changed later.
Array
1. What is an Array?
Array is used to store homogeneous data types values in a single variable
instead of declaring separate variables for each value.
Arrays are fixed in size.
Array indexing/position starts from 0th index.
Arrays only can store Homogeneous data type.
2. In case of an array which variable is created automatically? Can u modify it? If no,
why?
In java whenever u create array, u get “length” variable by default which is
nothing but size of array.
No u can’t modify it because it is final.
3. Is there a way to increase the size of an array after its declaration?
Arrays are static and once we have specified its size, we can't change it.
If we want to use such collections where we may require a change of size (no
of items), we should prefer vector over array.
String Concept
1. What is String?
String is the sequence of characters or say string is an array of characters.
6. What is special about string objects as compared to objects of other derived types?
One special thing about string objects is that you can create string objects
without using new operator i.e using string literals. This is not possible with
other derived types (except wrapper classes).
One more special thing about strings is that you can concatenate two string
objects using ‘+’. This is the relaxation java gives to string objects as they will
be used most of the time while coding. And also java provides string constant
pool to store the string objects
8. Which is the final class in these three classes – String, StringBuffer and StringBuilder?
All three are final. (Interviewer will ask this type of questions to confuse you)
9. Why StringBuffer and StringBuilder classes are introduced in java when there already
exist String class to represent the set of characters?
The objects of String class are immutable in nature. i.e you can’t modify them
once they are created.
If you try to modify them, a new object will be created with modified content.
This may cause memory and performance issues if you are performing lots of
string modifications in your code.
To overcome these issues, StringBuffer and StringBuilder classes are
introduced in java.
11. Which one will you prefer among “==” and equals() method to compare two string
objects?
prefer equals() method because it compares two string objects based on their
content and returns true if the two have same value. That provides more
logical comparison of two string objects.
If you use “==” operator, it checks only references of two objects are equal or
not. It may not be suitable in all situations.
So, rather stick to equals() method to compare two string objects.
12. Which class will you recommend among String, StringBuffer and StringBuilder classes
if I want mutable and thread safe objects?
StringBuffer
14. What do you think about string constant pool? Why they have provided this pool as
we can store string objects in the heap memory itself?
String constant pool increases the reusability of existing string objects.
When you are creating a string object using string literal, JVM first checks
string constant pool. If that object is available, it returns reference of that
object rather creating a new object.
This will also speed up your application as only reference is returned and also
saves the memory as no two objects with same content are created.
Differences
final means that you can’t change the object’s reference to point to another
reference or another object, but you can still mutate its state (using setter
methods e.g). Whereas immutable means that the object’s actual value can’t
be changed, but you can change its reference to another one.
final modifier is applicable for variable but not for objects, Whereas
immutability applicable for an object but not for variables.
By declaring a reference variable as final, we won’t get any immutability
nature, even though reference variable is final. We can perform any type of
change in the corresponding Object. But we can’t perform reassignment for
that variable.
final ensures that the address of the object remains the same whereas the
Immutable suggests that we can’t change the state of the object once created.
OOPs-Inheritance
1. What is OOPs? Which are Main Pillars of OOPS?
OOPs is objected oriented programming Concept.
As the name suggests, Object-Oriented Programming or OOPs refers to
languages that uses objects in programming.
Object-Oriented Programming (OOPs) is a type of programming that is based
on objects rather than just functions and procedures. Individual objects are
grouped into classes. OOPs implements real-world entities like inheritance,
polymorphism, hiding, etc into programming. It also allows binding data and
code together.
One of the Language java also uses this concept that’s why we call java as OOP
language.
This concept is totally dealing with class and objects and designed from our
day-to-day life.
The main purpose of this concept- make readability and understanding should
be easy.
3. Encapsulation- Binding (or wrapping) code and data together into a single unit
are known as encapsulation.
A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
.
1. Single inheritance consists of one parent class and one child class. The child
class inherits parent class methods and data members.
2. Multi-level inheritance is like a parent-child inheritance relationship—the
difference is that a child class inherits another child class.
3. When two or more child classes inherits a single parent class, it is known as
hierarchical inheritance.
4. Hybrid inheritance can be a combination of any of the three types of
inheritances supported in Java.
5. There is also a fifth type of Inheritance, but it is not supported in Java, as
multiple class inheritance causes ambiguities. Multiple inheritance is also
called a diamond problem. Hence, Java does not support multiple class
inheritance.
Polymorphism-Overloading
1. What is Polymorphism and how we can achieve it?
Polymorphism in Java is a concept by which we can perform a single action in
different ways.
Polymorphism is derived from 2 Greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So, polymorphism
means many forms.
There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism.
We can perform polymorphism in java by Method Overloading(Static
Binding) and Method Overriding(Dynamic Binding).
Real-life Example
Assume, you are supposed just perform the function of talking. Say, you have to tell
the story of your day, to a total stranger. Your function will get over pretty quickly.
Say, now you are telling the same to your beloved. You will go through more details
as compared to the previous one. What has happened here, is, you have performed
the same function, but based on the parameter, stranger/beloved, your way of
implementing the function changed!
Here, the func() method is overloaded. These methods have the same name but
accept different arguments.
Notice that, the return type of these methods is not the same. Overloaded methods
may or may not have different return types, but they must differ in parameters they
accept.
Syntax Rules: -
1. Method name must be same.
2. Method parameter or signature must be different.
3. Access modifier and return type doesn’t matter.
4. Can we overload main method in java?
Yes, we can overload the main() method.
The main() method is the starting point of any Java program.
The JVM starts the execution of any Java program form the main() method.
Without the main() method, JVM will not execute the program.
It is a default signature that is predefined in the JVM.
It is called by JVM to execute a program line by line and ends the execution
after completion of the method.
Note:
The JVM always calls the original main() method. It does not call the
overloaded main() method.
6. Can we achieve method overloading by changing the return type of method only?
No, in java method overloading is not possible by changing the return type of
method only because of ambiguity.
7. Can we override a method that throws runtime exception without throws clause?
Yes, there is no restriction on unchecked exceptions while overriding.
On the other hand, in the case of checked exception, an overriding exception
cannot throw a checked exception which comes higher in type hierarchy.
e.g. if the original method is throwing IOException than the overriding method
cannot throw java.lang.Exception or java.lang.Throwable.
Polymorphism-Overriding
1. Define Overriding. What are advantages and example of overriding?
If child class is not satisfied with parent class method implementation then
child class rewrite their own implementation that is called method
overriding.
In this case the method in parent class is called overridden method and the
method in child class is called overriding method.
Advantages of method overriding in java
1. Main purpose of overriding is to provide additional meaning of existing
functionality.
2. Method Overriding is used for Runtime Polymorphism.
Real life example
you learnt driving from you dad! But you both drive the same vehicle differently! (Dad
drives cautiously and you drive rash) That is overriding.
Programming perspective example
public class Parent public class Child extends Parent
{ {
void display() @Override
{ public void display()
System.out.println("parent_display_method"); { System.out.println("child_display_method");
} }
} }
3. Write the difference between method Overloading and method Overriding in java.
Method Overloading Method Overriding
Method Overriding is used to provide
Method overloading is used to increase
additional meaning of existing
the readability of the program.
functionality.
Method overloading is performed Method overriding occurs in two classes
within class. that have IS-A (inheritance) relationship.
Inheritance is not involved. Inheritance is involved.
In case of method overloading, In case of method overriding, parameter
parameter must be different. must be same.
Leads to static binding and static Leads to dynamic binding and dynamic
polymorphism. polymorphism.
In java, method overloading can't be
performed by changing return type of
the method only. Return type can be Return type must be same or covariant
same or different in method in method overriding.
overloading. But you must have to
change the parameter.
Subclass overridden method hides
One overloaded method does not hide
super class method from access by
the other method.
subclass object.
We can overload Static, private, final We cannot override Static, private, final
method method
equals() of object class and equals() of
println() of printstream class is example
string class are example of method
of method overloading.
overriding.
6. Can we override a method by using same method name and arguments but different
return types?
The basic condition of method overriding is that method name, arguments as
well as return type must be exactly same as is that of the method being
overridden. Hence using a different return type doesn't override a method.
7. What is object class? How many methods are present in object class?
The Object class is the parent class of all the classes in java by default. In other
words, it is the topmost class of java.
There are total 11 methods present in object class.
1. getClass(): Class<?> 2.hashCode(): int 3.equals(Object): boolean
4.clone(): Object 5.toString(): String 6.notify(): void
7.notifyAll(): void 8.wait(): void 9.wait(long): void
10.wait(long, int): void 11.finalize(): void
hashcode: It returns hash value of the object
equals: It compares the object references
wait: It causes current thread to wait until notify or notifyAll is not called
notify: Wakes up single thread which is waiting for lock
notifyAll: Wakes up all threads which is waiting for lock
toString: Provides String representation of the object
clone: This method is used to clone the object
finalize: This method is called when object is being garbage collected.
Encapsulation
1. What is Encapsulation? Explain with example.
Wrapping of methods and variables in class is called Encapsulation.
Every java class is example of Encapsulation.
Setter-Getter class (POJO) is best example of proper Encapsulation.
The time field in the Clock class has no access modifier, which means that it is
implicitly assigned the default / package access modifier. Therefore, the
ClockReader class can read the time member variable of the Clock object,
provided that ClockReader and Clock are located in the same Java package.
3.protected Access Modifier
The protected access modifier provides the same access as the default access
modifier, with the addition that subclasses can access protected methods and
member variables (fields) of the superclass. This is true even if the subclass is
not located in the same package as the superclass.
Here is a protected access modifier example:
public class Clock {
protected long time = 0; // time in milliseconds
}
5. Which OOPS concept exposes only the necessary information to the calling functions?
Encapsulation
Abstraction
1. What is Abstraction?
Abstraction is the process of hiding certain details and showing only essential
information to the user. i.e., we have to highlight set of services what we are
offering and we have to hide internal implementation details.
E.g., By using ATM GUI screen bank people are highlighting the set of services
what they are offering without highlighting internal implementation.
In java we achieve abstraction by using Interface and abstract class.
We can achieve 100% abstraction using “Interface” and partial by using
“Abstract Class”.
1. Inbuilt API: -
Their rules & guidelines are written by sun microsystem and their
implementation are also written by them.
E.g., Multithreading API
2. Open-Specification API: -
Their rules & guidelines are written by sun microsystem but their
implementation are written by some other vendors.
E.g., Jdbc API, jsp API, servlet API
3. Third Party API: -
Their rules & guidelines are written by another person and their
implementation are also written by other.
E.g., hibernate API, spring API
5. What is Interface?
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
Interface is set of rules and guidelines.
We can provide same protocol for class through interface.
e.g., RBI and All banks.
The interface in Java is a mechanism to achieve abstraction and multiple
inheritance.
Interfaces can have abstract methods and variables. It cannot have a method
body.
10. What is Marker Interface? What is use of marker interface and How many marker
interfaces available in Java?
Interface which has blank body (there is no method, no variable) is called
marker or tag interface or null interface.
Marker interface is used for decision making purpose.
JVM will take decision through marker interface.
In java we have the following major marker interfaces as under:
1. Serializable interface
2. Cloneable interface
3. Remote interface
4. ThreadSafe interface
20. Why we can restrict a class which has all implemented methods?
We can make that class abstract.
22. How we can create child class of abstract class which has both types of methods
implemented and non-implemented?
Rule 1: -
Child class must implement all abstract methods of abstract class.
Rule 2: -
If child class is unable to implement all methods of abstract class then make
child class as abstract.
23. Is there any constructor inside abstract class? If yes then what is the use of abstract
class constructor?
Yes, there is constructor inside abstract class.
It is used to initialize instance variable of class.
Abstraction Encapsulation
Abstraction is a feature of OOPs that Encapsulation is also a feature of OOPs.
hides the unnecessary detail but shows It hides the code and data into a single
the essential information. entity or unit so that the data can be
protected from the outside world.
It is the process or method of gaining It is the process or method of containing
information. the information.
It solves an issue at the design or It solves an issue at implementation
Interface level. level.
It can be implemented using abstract It can be implemented by using the
classes and interfaces. access modifiers (private, public,
protected).
In abstraction, we use abstract classes We use the getters and setters methods
and interfaces to hide the code to hide the data.
complexities
The objects that help to perform Whereas the objects that result in
abstraction are encapsulated. encapsulation need not be abstracted.
27. What are the performance implications of Interfaces over abstract classes?
Interfaces are slower in performance as compared to abstract classes as extra
indirections are required for interfaces.
Another key factor for developers to take into consideration is that any class
can extend only one abstract class while a class can implement many
interfaces.
Use of interfaces also puts an extra burden on the developers as any time an
interface is implemented in a class; developer is forced to implement each
and every method of interface.
Exception Handling
1. What is exception? Draw the hierarchy.
Exception is an abnormal condition or unwanted situation which occurs
during the execution of a program and disrupts normal flow of the program.
It is an object which is thrown at runtime.
When exception occurs then the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
4. How the exceptions are handled in java? OR Explain exception handling mechanism
in java?
Exceptions in java are handled using try, catch and finally blocks.
try block: The code or set of statements which are to be monitored for
exception are kept in this block.
catch block: This block catches the exceptions occurred in the try block.
9. Which class is the super class for all types of errors and exceptions in java?
java.lang.Throwable is the super class for all types of errors and exceptions in
java.
Syntax
catch try
{
//code that cause exception;
}
catch(Exception_type e)
{
//exception handling code
}
The "finally" block is used to execute the important code of
the program.
It is executed whether an exception is handled or not.
Java finally block follows try or catch block.
finally For each try block, there can be zero or more catch blocks,
but only one finally block.
The finally block will not be executed if program exits
(either by calling System.exit() or by causing a fatal error
that causes the process to abort).
throw The "throw" keyword is used to throw an exception.
The flow of execution stops immediately after the throw
statement; any subsequent statements are not executed.
The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of exception. If it
does find a match, control is transferred to that statement.
If not, then the next enclosing try statement is inspected,
and so on. If no matching catch is found, then the default
exception handler halts the program and prints the stack
trace.
The "throws" keyword is used to declare exceptions. It
doesn't throw an exception.
It gives an information to the programmer that there may
occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can
be maintained.
It is always used with method signature.
We declare only checked exception using a throws keyword.
throws If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not
performing checkup before the code is used.
13. Can we write only try block without catch and finally blocks?
No, it shows compilation error.
The try block must be followed by either catch or finally block.
You can remove either catch block or finally block but not both.
14. There are three statements in a try block – statement1, statement2 and statement3.
After that there is a catch block to catch the exceptions occurred in the try block.
Assume that exception has occurred in statement2. Does statement3 get executed or
not?
No. Once a try block throws an exception, remaining statements will not be
executed. control comes directly to catch block.
catch(Exception ex)
{
//Cathcing the exceptions here
}
finally
{
// This block is always executed
}
17. What are the legal combinations of try, catch and finally blocks?
try try try
{ { {
//try block //try block //try block
} } }
catch(Exception ex) finally catch(Exception ex)
{ { {
//catch block //finally block //catch block
} } }
finally
{
//finally block
}
catch(Exception ex)
{
System.out.println("This block handles all exception
types");
}
catch(NumberFormatException ex)
{
//Compile time error
//This block becomes unreachable as
//exception is already caught by above catch block
}
}
}
try
{
//Statements that may cause an exception
}
catch
{
//Handling exception
}
finally
{
//Statements to be executed
}
20. Is it compulsory to use the finally block?
It is always a good practice to use the finally block.
The reason for using the finally block is, any unreleased resources can be
released and the memory can be freed.
For example, while closing a connection object an exception has occurred. In
finally block we can close that object.
Coming to the question, you can omit the finally block when there is a catch
block associated with that try block.
A try block should have at least a catch or a finally block.
21. Can we keep the statements after finally block If the control is returning from the
finally block itself?
No, it gives unreachable code error. Because, control is returning from the
finally block itself.
Compiler will not see the statements after it. That’s why it shows unreachable
code error.
22. Why it is always recommended that clean-up operations like closing the DB resources
to keep inside a finally block?
Because finally block is always executed whether exceptions are raised in the
try block or not and raised exceptions are caught in the catch block or not.
By keeping the clean-up operations in finally block, you will ensure that those
operations will be always executed irrespective of whether exception is
occurred or not.
28. Can we override a super class method which is throwing an unchecked exception with
checked exception in the sub class?
No. If a super class method is throwing an unchecked exception, then it can
be overridden in the sub class with same exception or any other unchecked
exceptions but cannot be overridden with checked exceptions.
We all know that every class in java is a sub class of java.lang.Object class.
String is also a subclass of Obeject class and Integer is also a subclass of Object
class.
In the above example, String object is created and it is automatically up casted
to Object type.
Further, this object is explicitly downcasted to Integer type. This causes
ClassCastException, because, String object is not an Integer type.
The finally is a block that always be executed either there is exception occur
inside “try” block or there is no exception occur inside “try” block. In both
situations, “finally” block code will be executed.
35. How to decide that the custom exceptions are checked or unchecked?
If you extend Exception then it is “checked “, i.e., if you throw it, it must be
caught or declared in the method signature.
Unchecked exceptions extend RuntimeException and do not need to be
declared or caught.
Collection Framework
1. What do you mean by collection in java? Draw the hierarchy of collection
The Collection in Java is a framework that provides an architecture to store
and manipulate the group of objects.
Collection represents group of objects: Homogeneous or Heterogeneous.
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects.
Java Collection framework provides many interfaces (Set, List, Queue, Deque)
and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet)
2. What is List?
List in Java provides the facility to maintain the ordered collection.
It contains the index-based methods to insert, update, delete and search the
elements.
It can have the duplicate elements also. We can also store the null elements
in the list.
3. What is Set?
A Set is a Collection that cannot contain duplicate elements.
It models the mathematical set abstraction.
The Set interface contains only methods inherited from Collection and adds
the restriction that duplicate elements are prohibited.
13. What are legacy classes and interfaces present in Collections framework?
Early version of java did not include the Collections framework. In the early
version of Java, we have several classes and interfaces which allow us to store
objects.
After adding the Collection framework in JSE 1.2, for supporting the
collections framework, these classes were re-engineered.
So, classes and interfaces that formed the collections framework in the older
version of Java are known as Legacy classes.
For supporting generic in JDK5, these classes were re-engineered.
All the legacy classes are synchronized.
The java.util package defines the following legacy classes:
1. HashTable
2. Stack
3. Dictionary
4. Properties
5. Vector
There is only one legacy interface called Enumeration.
collections.synchronizedList(l); //Synchronized
for(String nm:l)
{
System.out.println(nm);
}
29. How Linkedlist works? (Why insertion & deletion is fast in Linkedlist?)
When we create an object of Linkedlist and add an element to it then it stores
element as a node in which previous & next node address is also stored.
Node format = ||prev. node addr.| (value) |next node addr.||
Due to previous & next node address is stored, hence while updation or
insertion & deletion operation data shift operation need not to perform and
it makes Linkedlist fast.
Map
1. Draw the hierarchy of map in java?
2. Write the difference between HashMap and Hashtable.
HashMap Hashtable(Legacy Class)
Not synchronized (Not Threadsafe) Synchronized (Threadsafe)
Every method present in HashMap is not Every method present in Hashtable is
synchronized. synchronized.
At a time, Multiple Threads are allowed At a time, Only One Thread is allowed to
to Operate on HashMap Object Operate on the Hashtable Object and
simultaneously and Hence it is Not Hence it is Thread Safe.
ThreadSafe.
Relatively Performance is High because Relatively Performance is low because
threads are not required to wait to threads are required to wait to operate
operate on HashMap object. on Hashtable object.
null is allowed for Both Key and Value. null is not allowed for Both Keys and
Values otherwise we will get
NullPointerException.
Retrieval of elements can be achieved Retrieval of elements can be achieved
through Iterator through Enumeration (Legacy Interface)
Introduced in jdk 1.2 version and it is not Introduced in jdk 1.0 version and it is
legacy. legacy.
9. Which two methods should you override while putting the custom object as Key in
HashMap?
You need to override hashcode and equals method in custom class while
putting objects of custom class in HashMap.
Let's see at which index the Key, value pair will be saved into HashMap. When
we call the put() method, then it calculates the hash code of the Key "Aman."
Hash code of key may be large enough to create an array. hash code
generated may be in the range of integer and if we create arrays for such a
range, then it will easily cause outOfMemoryException. So, we generate index
to minimize the size of array.
Suppose the hash code of "Aman" is 2657860. To store the Key in memory,
we have to calculate the index.
Basically, following operation is performed to calculate index.
index = hashCode(key) & (n-1)
where n is number of buckets or the size of array.
Index = 2657860 & (16-1) = 4
The value 4 is the computed index value where the Key and value will store
in HashMap.
If the key is null, the value is stored in table[0] position, because hashcode
for null is always 0.
Hash Collision
This is the case when the calculated index value is the same for two or more
Keys.
Let's calculate the hash code for another Key "Sunny." Suppose the hash code
for "Sunny" is 63281940. To store the Key in the memory, we have to calculate
index by using the index formula.
Index=63281940 & (16-1) = 4
Place this object at index 4 if no other object is presented there.
In this case a node object is found at the index 4 – this is a case of collision.
In this case, equals() method check that both Keys are equal or not. If Keys are
same, replace the value with the current value. Otherwise, connect this node
object to the existing node object through the LinkedList. Hence both Keys will
be stored at index 4.
In case of collision, i.e. index of two or more nodes are same, nodes are joined
by link list i.e. second node is referenced by first node and third by second and
so on.
Similarly, we will store the Key "Ritesh." Suppose hash code for the Key is
2349873. The index value will be 1. Hence this Key will be stored at index 1.
get() method in HashMap
get() method is used to get the value by its Key. It will not fetch the value if
you don't know the Key. When get(K Key) method is called, it calculates the
hash code of the Key.
Suppose we have to fetch the Key "Aman." The following method will be
called.
map.get(new Key("Aman"));
It generates the hash code as 2657860. Now calculate the index value of
2657860 by using index formula. The index value will be 4, as we have
calculated above.
get() method search for the index value 4. It compares the first element Key
with the given Key. If both keys are equal, then it returns the value else check
for the next element in the node if it exists.
In our scenario, it is found as the first element of the node and return the
value 19.
Let's fetch another Key "Sunny." The hash code of the Key "Sunny" is
63281940. The calculated index value of 63281940 is 4, as we have calculated
for put() method.
Go to index 4 of array and compare first element’s key with given key. If both
are equals then return the value, otherwise check for next element if it exists.
In our case it is not found as first element and next of node object is not null.
If next of node is not null traverse to the second element and repeat the
process until key is not found or next is not null. It compares the second
element Key with the specified Key and returns the value 29.
If next of node is null then return null.
Re-Hashing:
Whenever the number of entries in the hashmap crosses the threshold value
then the bucket size of the hashmap is doubled and rehashing is performed
and all the already existing entries of the map are copied and new entries are
added to this increased hashmap.
Threshold value = Bucket size * Load factor
Eg. If bucket size is 16 and the load factor is 0.75 then the threshold value is
12.
Time complexity
Time complexity is almost constant for put and get method until rehashing is
not done.
In a fairly distributed hashMap where the entries go to all the buckets in such
a scenario, the hashMap has O(1) time for search, insertion, and deletion
operations.
In the worst case, where all the entries go to the same bucket and the singly
linked list stores these entries, O(n) time is required for operations like search,
insert, and delete.
In a case where the threshold for converting this linked list to a self-balancing
binary search tree(i.e. AVL/Red black) is used then for the operations, search,
insert and delete O(logN) is required as AVL/Red Black tree has a max length
of logN in the worst case.
Answer in Short:
HashMap uses its static inner class Node<K,V> for storing map entries. That
means each entry in hashMap is a Node.
Internally HashMap uses a hashCode of the key Object and this hashCode is
further used by the hash function to find the index of the bucket where the
new entry can be added.
HashMap uses multiple buckets and each bucket points to a Singly Linked List
where the entries (nodes) are stored.
Once the bucket is identified by the hash function using hashcode, then
hashCode is used to check if there is already a key with the same hashCode or
not in the bucket(singly linked list).
If there already exists a key with the same hashCode, then the equals()
method is used on the keys. If the equals method returns true, that means
there is already a node with the same key and hence the value against that
key is overwritten in the entry(node), otherwise, a new node is created and
added to this Singly Linked List of that bucket.
If there is no key with the same hashCode in the bucket found by the hash
function then the new Node is added into the bucket found.
Or
When we create HashMap object, HashMap instance as per default capacity
16 buckets is created.
When we perform add (put ( )) operation, it accepts data in key & value
format.
Internally hashing technique is used, that generates hashcode for key and also
calculate index to find bucket location for inserting data in HashMap instance.
It will store element at that location as a node format.
||previous node address| (Key) | (Value) |next node address||
Now when we perform retrieval (get ( )) operation, it asks for key.
Again hashing technique is used and bucket location is identified, then equals
( ) method is used to compare key content and if it returns true then value is
retrieved.
13. Why String, Integer and other wrapper classes are considered good keys for
HashMap?
String, Integer and other wrapper classes are natural candidates of HashMap
key, and String is most frequently used key as well because String is immutable
and final, and overrides equals and hashcode() method.
Other wrapper class also shares similar property.
Immutability is required, in order to prevent changes on fields used to
calculate hashCode() because if key object returns different hashCode during
insertion and retrieval than it won't be possible to get an object from
HashMap.
public int compareTo(Object obj): It is used to compare the current object with the
specified object.
It returns
positive integer, if the current object is greater than the specified object.
negative integer, if the current object is less than the specified object.
zero, if the current object is equal to the specified object.
2. What is Multithreading?
The process of executing multiple threads simultaneously is known as
multithreading.
Multithreading in java is process of execution of two or more parts of a
program to maximum utilize the CPU time.
A multithreaded program contains two or more parts that can run
concurrently.
Each such part of a program called thread.’
Threads are lightweight sub-processes, they share the common memory
space.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1. It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2. You can perform many operations together, so it saves time.
3. Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
5. What is lock?
Every object in java has a unique lock.
Whenever we are using Synchronized keyword the only lock concept will
come into the picture.
6. Why we need to apply lock? How many types of lock explain with example?
System.out.println("Current System.out.println("Current
thread name: "+ thread name: "+
Thread.currentThread().getName( Thread.currentThread().getName(
)); ));
System.out.println("run() System.out.println("run()
method called"); method called");
} }
} }
Output: Output:
Current thread name: Thread-0 Current thread name: main
run() method called run() method called
in the above program, when we call the in the above example, when we called
start() method of our thread class the run() method of our MyThread class,
instance, a new thread is created with no new thread is created and the run()
default name Thread-0 and then run() method is executed on the current
method is called and everything inside it
thread i.e. main thread. Hence, no
is executed on the newly created multi-threading took place. The run()
thread. method is called as a normal function
call.
we can’t call the start() method twice run() method can be called multiple
otherwise it will throw an times as it is just a normal method
IllegalThreadStateException calling.
Defined in java.lang.Thread class and Defined in java.lang.Runnable interface
we should not override start() and must be overriden in the
implementing class.
9. Write difference between sleep() and wait() method.
sleep() wait()
Through sleep() lock will be hold. Through wait() lock will be released.
Through sleep() running thread will wait Through wait() running thread will wait
only for time interval. for time interval as well as till the
notify() or notifyAll() will get call.
sleep is static method of Thread class. wait is non-static method of Object
class.
sleep() we can call inside any of the wait() we can call only inside
context. synchronized context (Synchronized
Method/ Block).
10. Explain about synchronized keyword? What are its advantages and disadvantages?
If a multiple thread wants to operate on a same object simultaneously, there
may be problem of data inconsistency (Race Condition).
To overcome this problem, we need to apply lock and for applying lock we can
use synchronized keyword.
Synchronized keyword is only applicable to methods & blocks and not to
variables & class.
If a method or block declared as the Synchronized then at a time one Thread
is allow to execute that methods of block on the given object.
Advantages:
The main advantage of synchronization is that by using the synchronized keyword we
can resolve the data inconsistency problem.
Disadvantages:
It increases waiting time of thread. At a time only one thread can operate on object
so other threads have to wait. So it affects performance of the system.
In above program any 1 thread from each object comes for execution inside
the method/block at a time then it will be decided which thread will execute
method/block first. After complete execution of method/block 2nd thread will
execute the method/block
Remaining threads of each objects will wait outside the method until 1st set of
threads performs their operation completely.
13. What is difference between object level lock and class level lock?
Key Object Level Lock Class Level Lock
It can be used when you Class level locking means
Basic want non-static method you want to synchronize
or non-static block of the static method or block so
code should be accessed that it can be accessed by
by only one thread only one thread for whole
class.
It should always be used It should always be used
Static/Non Static to make non-static data to make static data thread
thread safe safe.
Multiple objects of class
Every object in the class may exist but there is
Number of Locks
may have their own lock always one class’s class
object lock available
Syntax:
synchronized (object reference expression)
{
//code block
}
Example 1: To get lock of current object we can declare synchronized block as follows.
If Thread got lock of current object then only it is allowed to execute this block.
synchronized(this)
{
}
Example 2: To get the lock of a particular object 'b' we have to declare a synchronized
block as follows.
If thread got lock of 'b' object then only it is allowed to execute this block.
synchronized(b)
{
}
Example 3: To get class level lock we have to declare synchronized block as follows.
If thread got class level lock of Display then only it allowed to execute this block.
synchronized(Display.class)
{
}
Note: As the argument to the synchronized block, we can pass either object reference
or ".class file" and we can't pass primitive values as argument because lock concept
is dependent only for objects and classes but not for primitives.
Example: Output:
Int x=b; Compile time error.
Synchronized(x) Unexpected type.
{ Found: int
} Required: reference
15. What is advantage of synchronize block over synchronize method? (Which is more
preffered?)
The main advantage of synchronized block over synchronized method is it
reduces waiting time of Thread and improves performance of the system.
Synchronized method locks the entire object. This means no other thread can
use any synchronized method in the whole object while the method is being
run by one thread.
Synchronized block just locks the code within the block. This means no other
thread can acquire a lock on the locked object until the synchronized block
exits.
16. Write the difference between Runnable Interface and Callable Interface.
Runnable Interface Callable Interface
Runnable Interface have run(). Callable Interface have call().
run() does not return any value. call() returns object.
run() does not throws any exception. call() throws exception.
It simply belongs to Java.lang. It simply belongs to java.util.concurrent.
17. While a Thread executing a synchronized method on the given object is the remaining
Threads are allowed to execute other synchronized methods simultaneously on the
same object?
No
19. Why wait(), notify() and notifyAll() methods are available in Object class but not in
Thread class ?
Because Thread can call these methods on any common object.
20. Every java program contains by default how many Threads and which Thread by
default runs?
Only 1 Thread and that is main thread and by default main Thread runs in
every java program.
21. Which method is executed by any Thread?
A Thread executes only public void run() method.
22. In multi-threading how can we ensure that a resource isn't used by multiple threads
simultaneously?
In multi-threading, access to the resources which are shared among multiple
threads can be controlled by using the concept of synchronization.
Using synchronized keyword, we can ensure that only one thread can use
shared resource at a time and others can get control of the resource only once
it has become free from the other one using it.
23. I want to control database connections in my program and want that only one thread
should be able to make database connection at a time. How can I implement this
logic?
This can be implemented by use of the concept of synchronization. Database
related code can be placed in a method which has synchronized keyword so
that only one thread can access it at a time.
25. How can we pause the execution of a Thread for specific time?
We can use Thread class sleep() method to pause the execution of thread for
certain time.