1) What is Java?
Java is the high-level, object-oriented, robust, secure programming language,
platform-independent, high performance, Multithreaded, and portable
programming language. It was developed by James Gosling in June 1991. It
can also be known as the platform as it provides its own JRE and API.
List the features of Java Programming language.
There are the following features in Java Programming Language.
Simple: Java is easy to learn. The syntax of Java is based on C++
which makes easier to write the program in it.
Object-Oriented: Java follows the object-oriented paradigm which
allows us to maintain our code as the combination of different type of
objects that incorporates both data and behavior.
Portable: Java supports read-once-write-anywhere approach. We can
execute the Java program on every machine. Java program (.java) is
converted to bytecode (.class) which can be easily run on every
machine.
Platform Independent: Java is a platform independent programming
language. It is different from other programming languages like C and
C++ which needs a platform to be executed. Java comes with its
platform on which its code is executed. Java doesn't depend upon the
operating system to be executed.
Secured: Java is secured because it doesn't use explicit pointers. Java
also provides the concept of ByteCode and Exception handling which
makes it more secured.
Robust: Java is a strong programming language as it uses strong
memory management. The concepts like Automatic garbage collection,
Exception handling, etc. make it more robust.
Architecture Neutral: Java is architectural neutral as it is not
dependent on the architecture. In C, the size of data types may vary
according to the architecture (32 bit or 64 bit) which doesn't exist in
Java.
Interpreted: Java uses the Just-in-time (JIT) interpreter along with the
compiler for the program execution.
High Performance: Java is faster than other traditional interpreted
programming languages because Java bytecode is "close" to native
code. It is still a little bit slower than a compiled language (e.g., C++).
Multithreaded: We can write Java programs that deal with many
tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-
media, Web applications, etc.
Distributed: Java is distributed because it facilitates users to create
distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.
Dynamic: Java is a dynamic language. It supports dynamic loading of
classes. It means classes are loaded on demand. It also supports
functions from its native languages, i.e., C and C++.
4) What do you understand by Java virtual machine?
Java Virtual Machine is a virtual machine that enables the computer to run
the Java program. JVM acts like a run-time engine which calls the main
method present in the Java code. JVM is the specification which must be
implemented in the computer system.
The Java code is compiled by JVM to be a Bytecode which is machine
independent and close to the native code.
What is the difference between JDK, JRE, and JVM?
JVM
JVM is an acronym for Java Virtual Machine; it is an abstract machine which
provides the runtime environment in which Java bytecode can be executed.
It is a specification which specifies the working of Java Virtual Machine. Its
implementation has been provided by Oracle and other companies. Its
implementation is known as JRE.
JVMs are available for many hardware and software platforms (so JVM is
platform dependent). It is a runtime instance which is created when we run
the Java class. There are three notions of the JVM: specification,
implementation, and instance.
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM.
The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment.
It is the implementation of JVM. It physically exists. It contains a set of
libraries + other files that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. It is a software development
environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools. JDK is an
implementation of any one of the below given Java Platforms released by
Oracle Corporatio
6) How many types of memory areas are allocated by JVM?
Many types:
1. Class(Method) Area: Class Area stores per-class structures such as
the runtime constant pool, field, method data, and the code for
methods.
2. Heap: It is the runtime data area in which the memory is allocated to
the objects
3. Stack: Java Stack stores frames. It holds local variables and partial
results, and plays a part in method invocation and return. Each thread
has a private JVM stack, created at the same time as the thread. A new
frame is created each time a method is invoked. A frame is destroyed
when its method invocation completes.
4. Program Counter Register: PC (program counter) register contains
the address of the Java virtual machine instruction currently being
executed.
5. Native Method Stack: It contains all the native methods used in the
application.
7) What is JIT compiler?
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT
compiles parts of the bytecode that have similar functionality at the same
time, and hence reduces the amount of time needed for compilation. Here
the term “compiler” refers to a translator from the instruction set of a Java
virtual machine (JVM) to the instruction set of a specific CPU.
What is the platform?
A platform is the hardware or software environment in which a piece of
software is executed. There are two types of platforms, software-based and
hardware-based. Java provides the software-based platform.
What is classloader?
Classloader is a subsystem of JVM which is used to load class files. Whenever
we run the java program, it is loaded first by the classloader. There are three
built-in classloaders in Java.
6. Bootstrap ClassLoader: This is the first classloader which is the
superclass of Extension classloader. It loads the rt.jar file which
contains all class files of Java Standard Edition like java.lang package
classes, java.net package classes, java.util package classes, java.io
package classes, java.sql package classes, etc.
7. Extension ClassLoader: This is the child classloader of Bootstrap and
parent classloader of System classloader. It loads the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
8. System/Application ClassLoader: This is the child classloader of
Extension classloader. It loads the class files from the classpath. By
default, the classpath is set to the current directory. You can change
the classpath using "-cp" or "-classpath" switch. It is also known as
Application classloader.
What are the various access specifiers in Java?
In Java, access specifiers are the keywords which are used to define the
access scope of the method, class, or a variable. In Java, there are four
access specifiers given below.
Public The classes, methods, or variables which are defined as public,
can be accessed by any class or method.
Protected Protected can be accessed by the class of the same
package, or by the sub-class of this class, or within the same class.
Default Default are accessible within the package only. By default, all
the classes, methods, and variables are of default scope.
Private The private class, methods, or variables defined as private can
be accessed within the class only.
What is the purpose of static methods and variables?
The methods or variables defined as static are shared among all the objects
of the class. The static is the part of the class and not of the object. The
static variables are stored in the class area, and we do not need to create
the object to access such variables. Therefore, static is used in the case,
where we need to define variables or methods which are common to all the
objects of the class.
For example, In the class simulating the collection of the students in a
college, the name of the college is the common attribute to all the students.
Therefore, the college name will be defined as static.
What are the advantages of Packages in Java?
There are various advantages of defining packages in Java.
Packages avoid the name clashes.
The Package provides easier access control.
We can also have the hidden classes that are not visible outside and
used by the package.
It is easier to locate the related classes.
What is an object?
The Object is the real-time entity having some state and behavior. In Java,
Object is an instance of the class having the instance variables as the state
of the object and the methods as the behavior of the object. The object of a
class can be created by using the new keyword.
What is the constructor?
The constructor can be defined as the special type of method that is used to
initialize the state of an object. It is invoked when the class is instantiated,
and the memory is allocated for the object. Every time, an object is created
using the new keyword, the default constructor of the class is called. The
name of the constructor must be similar to the class name. The constructor
must not have an explicit return type.
More Details.
How many types of constructors are used in Java?
Based on the parameters passed in the constructors, there are two types of
constructors in Java.
Default Constructor: default constructor is the one which does not
accept any value. The default constructor is mainly used to initialize
the instance variable with the default values. It can also be used for
performing some useful task on object creation. A default constructor
is invoked implicitly by the compiler if there is no constructor defined
in the class.
Parameterized Constructor: The parameterized constructor is the
one which can initialize the instance variables with the given values. In
other words, we can say that the constructors which can accept the
arguments are called parameterized constructors.
What is the purpose of a default constructor?
The purpose of the default constructor is to assign the default value to the
objects. The java compiler creates a default constructor implicitly if there is
no constructor in the class.
What are the differences between the constructors and methods?
There are many differences between constructors and methods. They are
given below.
Java Constructor Java Method
A constructor is used to initialize the state of A method is used to expose
an object. the behavior of an object.
A constructor must not have a return type. A method must have a
return type.
The constructor is invoked implicitly. The method is invoked
explicitly.
The Java compiler provides a default The method is not provided
constructor if you don't have any constructor by the compiler in any case.
in a class.
The constructor name must be same as the The method name may or
class name. may not be same as class
name.
What is the static variable?
The static variable is used to refer to the common property of all objects
(that is not unique for each object), e.g., The company name of employees,
college name of students, etc. Static variable gets memory only once in the
class area at the time of class loading. Using a static variable makes your
program more memory efficient (it saves memory). Static variable belongs to
the class rather than the object.
What is the static method?
A static method belongs to the class rather than the object.
There is no need to create the object to call the static methods.
A static method can access and change the value of the static variable.
What are the restrictions that are applied to the Java static
methods?
Two main restrictions are applied to the static methods.
The static method can not use non-static data member or call the non-
static method directly.
this and super cannot be used in static context as they are non-static.
Why is the main method static?
Because the object is not required to call the static method. If we make the
main method non-static, JVM will have to create its object first and then call
main() method which will lead to the extra memory allocation. More Details.
What is the static block?
Static block is used to initialize the static data member. It is executed before
the main method, at the time of classloading.
Can we execute a program without main() method?
Ans) No, It was possible before JDK 1.7 using the static block. Since JDK 1.7,
it is not possible. More Details.
What is the difference between static (class) method and instance
method?
static or class method instance method
1)A method that is declared as static is known A method that is not
as the static method. declared as static is
known as the instance
method.
2)We don't need to create the objects to call The object is required to
the static methods. call the instance methods.
3)Non-static (instance) members cannot be Static and non-static
accessed in the static context (static method, variables both can be
static block, and static nested class) directly. accessed in instance
methods.
4)For example: public static int cube(int n) For example: public void
{ return n*n*n;} msg(){...}.
Can we make constructors static?
As we know that the static context (method, block, or variable) belongs to
the class, not the object. Since Constructors are invoked only when the
object is created, there is no sense to make the constructors static. However,
if you try to do so, the compiler will show the compiler error.
49) Can we make the abstract methods static in Java?
In Java, if we make the abstract methods static, It will become the part of the
class, and we can directly call it which is unnecessary. Calling an undefined
method is completely useless therefore it is not allowed.
Can we declare the static variables and methods in an abstract
class?
Yes, we can declare static variables and methods in an abstract method. As
we know that there is no requirement to make the object to access the static
context, therefore, we can access the static context declared inside the
abstract class by using the name of the abstract class. Consider the following
example.
1) What is this keyword in java?
The this keyword is a reference variable that refers to the current object.
There are the various uses of this keyword in Java. It can be used to refer to
current class properties such as instance methods, variable, constructors,
etc. It can also be passed as an argument into the methods or constructors.
It can also be returned from the method as the current class instance.
More Details.
52) What are the main uses of this keyword?
There are the following uses of this keyword.
this can be used to refer to the current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke the current class constructor.
this can be passed as an argument in the method call.
this can be passed as an argument in the constructor call.
this can be used to return the current class instance from the method.
53) Can we assign the reference to this variable?
No, this cannot be assigned to any value because it always points to the
current class object and this is the final reference in Java. However, if we try
to do so, the compiler error will be shown. Consider the following example.
9. public class Test
10. {
11. public Test()
12. {
13. this = null;
14. System.out.println("Test class constructor called");
15. }
16. public static void main (String args[])
17. {
18. Test t = new Test();
19. }
20. }
Output
Test.java:5: error: cannot assign a value to final variable this
this = null;
^
1 error
54) Can this keyword be used to refer static members?
Yes, It is possible to use this keyword to refer static members because this is
just a reference variable which refers to the current class object. However, as
we know that, it is unnecessary to access static variables through objects,
therefore, it is not the best practice to use this to refer static members.
Consider the following example.
21. public class Test
22. {
23. static int i = 10;
24. public Test ()
25. {
26. System.out.println(this.i);
27. }
28. public static void main (String args[])
29. {
30. Test t = new Test();
31. }
32. }
Output
10
55) How can constructor chaining be done using this keyword?
Constructor chaining enables us to call one constructor from another
constructor of the class with respect to the current class object. We can use
this keyword to perform constructor chaining within the same class. Consider
the following example which illustrates how can we use this keyword to
achieve constructor chaining.
33. public class Employee
34. {
35. int id,age;
36. String name, address;
37. public Employee (int age)
38. {
39. this.age = age;
40. }
41. public Employee(int id, int age)
42. {
43. this(age);
44. this.id = id;
45. }
46. public Employee(int id, int age, String name, String address)
47. {
48. this(id, age);
49. this.name = name;
50. this.address = address;
51. }
52. public static void main (String args[])
53. {
54. Employee emp = new Employee(105, 22, "Vikas", "Delhi");
55. System.out.println("ID: "+emp.id+" Name:"+emp.name+"
age:"+emp.age+" address: "+emp.address);
56. }
57.
58. }
Output
ID: 105 Name:Vikas age:22 address: Delhi
56) What are the advantages of passing this into a method instead
of the current class object itself?
As we know, that this refers to the current class object, therefore, it must be
similar to the current class object. However, there can be two main
advantages of passing this into a method instead of the current class object.
this is a final variable. Therefore, this cannot be assigned to any new
value whereas the current class object might not be final and can be
changed.
this can be used in the synchronized block.
What is the Inheritance?
Inheritance is a mechanism by which one object acquires all the properties
and behavior of another object of another class. It is used for Code
Reusability and Method Overriding. The idea behind inheritance in Java is
that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of the
parent class. Moreover, you can add new methods and fields in your current
class also. Inheritance represents the IS-A relationship which is also known
as a parent-child relationship.
There are five types of inheritance in Java.
Single-level inheritance
Multi-level inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multiple inheritance is not supported in Java through class.
More Details.
58) Why is Inheritance used in Java?
There are various advantages of using inheritance in Java that is given
below.
Inheritance provides code reusability. The derived class does not need
to redefine the method of base class unless it needs to provide the
specific implementation of the method.
Runtime polymorphism cannot be achieved without using inheritance.
We can simulate the inheritance of classes with the real-time objects
which makes OOPs more realistic.
Inheritance provides data hiding. The base class can hide some data
from the derived class by making it private.
Method overriding cannot be achieved without inheritance. By method
overriding, we can give a specific implementation of some basic
method contained by the base class.
Which class is the superclass for all the classes?
The object class is the superclass of all other classes in Java.
60) Why is multiple inheritance not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is
not supported in java. Consider a scenario where A, B, and C are three
classes. The C class inherits A and B classes. If A and B classes have the
same method and you call it from child class object, there will be ambiguity
to call the method of A or B class.
Since the compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have the same
method or different, there will be a compile time error.
59. class A{
60. void msg(){System.out.println("Hello");}
61. }
62. class B{
63. void msg(){System.out.println("Welcome");}
64. }
65. class C extends A,B{//suppose if it were
66.
67. Public Static void main(String args[]){
68. C obj=new C();
69. obj.msg();//Now which msg() method would be invoked?
70. }
71. }
Why does Java not support pointers?
The pointer is a variable that refers to the memory address. They are not
used in Java because they are unsafe(unsecured) and complex to
understand.
What are the main uses of the super keyword?
There are the following uses of super keyword.
super can be used to refer to the immediate parent class instance
variable.
super can be used to invoke the immediate parent class method.
super() can be used to invoke immediate parent class constructor
What are the differences between this and super keyword?
There are the following differences between this and super keyword.
The super keyword always points to the parent class contexts whereas
this keyword always points to the current class context.
The super keyword is primarily used for initializing the base class
variables within the derived class constructor whereas this keyword
primarily used to differentiate between local and instance variables
when passed in the class constructor.
The super and this must be the first statement inside constructor
otherwise the compiler will throw an error.
Can you use this() and super() both in a constructor?
No, because this() and super() must be the first statement in the class
constructor.
)What is object cloning?
The object cloning is used to create the exact copy of an object. The clone()
method of the Object class is used to clone an object. The
java.lang.Cloneable interface must be implemented by the class whose
object clone we want to create. If we don't implement Cloneable interface,
clone() method generates CloneNotSupportedException.
What is method overloading?
Method overloading is the polymorphism technique which allows us to create
multiple methods with the same name but different signature. We can
achieve method overloading in two ways.
By Changing the number of arguments
By Changing the data type of arguments
Method overloading increases the readability of the program. Method
overloading is performed to figure out the program quickly.
Why is method overloading not possible by changing the return type
in java?
In Java, method overloading is not possible by changing the return type of
the program due to avoid the ambiguity.
72. class Adder{
73. static int add(int a,int b){return a+b;}
74. static double add(int a,int b){return a+b;}
75. }
76. class TestOverloading3{
77. public static void main(String[] args){
78. System.out.println(Adder.add(11,11));//ambiguity
79. }}
Can we overload the methods by making them static?
No, We cannot overload the methods by just applying the static keyword to
them(number of parameters and types are the same). Consider the following
example.
80. public class Animal
81. {
82. void consume(int a)
83. {
84. System.out.println(a+" consumed!!");
85. }
86. static void consume(int a)
87. {
88. System.out.println("consumed static "+a);
89. }
90. public static void main (String args[])
91. {
92. Animal a = new Animal();
93. a.consume(10);
94. Animal.consume(20);
95. }
96. }
Output
Animal.java:7: error: method consume(int) is already defined in
class Animal
static void consume(int
a)
^
Animal.java:15: error: non-static method consume(int) cannot be
referenced from a static context
Animal.consume(20);
^
2 errors
75) Can we overload the main() method?
Yes, we can have any number of main methods in a Java program by using
method overloading.
What is method overriding:
If a subclass provides a specific implementation of a method that is already
provided by its parent class, it is known as Method Overriding. It is used for
runtime polymorphism and to implement the interface methods.
Rules for Method overriding
The method must have the same name as in the parent class.
The method must have the same signature as in the parent class.
Two classes must have an IS-A relationship between them.
an we override the static method?
No, you can't override the static method because they are the part of the
class, not the object.
80) Why can we not override static method?
It is because the static method is the part of the class, and it is bound with
class whereas instance method is bound with the object, and static gets
memory in class area, and instance gets memory in a heap.
81) Can we override the overloaded method?
Yes.
82) Difference between method Overloading and Overriding.
Method Overloading Method Overriding
1) Method overloading Method overriding provides the specific
increases the readability of implementation of the method that is already
the program. provided by its superclass.
2) Method overloading Method overriding occurs in two classes that
occurs within the class. have IS-A relationship between them.
3) In this case, the In this case, the parameters must be the
parameters must be same.
different.
83) Can we override the private methods?
No, we cannot override the private methods because the scope of private
methods is limited to the class and we cannot access them outside of the
class.
84) Can we change the scope of the overridden method in the
subclass?
Yes, we can change the scope of the overridden method in the subclass.
However, we must notice that we cannot decrease the accessibility of the
method. The following point must be taken care of while changing the
accessibility of the method.
The private can be changed to protected, public, or default.
The protected can be changed to public or default.
The default can be changed to public.
The public will always remain public.
85) Can we modify the throws clause of the superclass method
while overriding it in the subclass?
Yes, we can modify the throws clause of the superclass method while
overriding it in the subclass. However, there are some rules which are to be
followed while overriding in case of exception handling.
If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception, but it can
declare the unchecked exception.
If the superclass method declares an exception, subclass overridden
me
What is the final variable?
In Java, the final variable is used to restrict the user from updating it. If we
initialize the final variable, we can't change its value. In other words, we can
say that the final variable once assigned to a value, can never be changed
after that. The final variable which is not assigned to any value can only be
assigned through the class constructor.
97. class Bike9{
98. final int speedlimit=90;//final variable
99. void run(){
100. speedlimit=400;
101. }
102. public static void main(String args[]){
103. Bike9 obj=new Bike9();
104. obj.run();
105. }
106. }//end of class
Test it Now
Output:Compile Time Error
More Details.
91) What is the final method?
If we change any method to a final method, we can't override it. More
Details.
107. class Bike{
108. final void run(){System.out.println("running");}
109. }
110.
111. class Honda extends Bike{
112. void run(){System.out.println("running safely with
100kmph");}
113.
114. public static void main(String args[]){
115. Honda honda= new Honda();
116. honda.run();
117. }
118. }
Test it Now
Output:Compile Time Error
92) What is the final class?
If we make any class final, we can't inherit it into any of the subclasses.
119. final class Bike{}
120.
121. class Honda1 extends Bike{
122. void run(){System.out.println("running safely with
100kmph");}
123.
124. public static void main(String args[]){
125. Honda1 honda= new Honda1();
126. honda.run();
127. }
128. }
Test it Now
Output:Compile Time Error
More Details.
93) What is the final blank variable?
A final variable, not initialized at the time of declaration, is known as the final
blank variable. We can't initialize the final blank variable directly. Instead, we
have to initialize it by using the class constructor. It is useful in the case
when the user has some data which must not be changed by others, for
example, PAN Number. Consider the following example:
129. class Student{
130. int id;
131. String name;
132. final String PAN_CARD_NUMBER;
133. ...
134. }
More Details.
94) Can we initialize the final blank variable?
Yes, if it is not static, we can initialize it in the constructor. If it is static blank
final variable, it can be initialized only in the static block. More Details.
95) Can you declare the main method as final?
Yes, We can declare the main method as public static final void main(String[]
args){}.
Can we declare an interface as final?
No, we cannot declare an interface as final because the interface must be
implemented by some class to provide its definition. Therefore, there is no
sense to make an interface final. However, if you try to do so, the compiler
will show an error.
100) What is the difference between the final method and abstract
method?
The main difference between the final method and abstract method is that
the abstract method cannot be final as we need to override them in the
subclass to give its definition.
What is the difference between compile-time polymorphism and
runtime polymorphism?
There are the following differences between compile-time polymorphism and
runtime polymorphism.
S compile-time polymorphism Runtime polymorphism
N
1 In compile-time In runtime polymorphism, call to an
polymorphism, call to a overridden method is resolved at
method is resolved at runtime.
compile-time.
2 It is also known as static It is also known as dynamic binding, late
binding, early binding, or binding, overriding, or dynamic method
overloading. dispatch.
3 Overloading is a way to Overriding is a way to achieve runtime
achieve compile-time polymorphism in which, we can redefine
polymorphism in which, we some particular method or variable in the
can define multiple derived class. By using overriding, we can
methods or constructors give some specific implementation to the
with different signatures. base class properties in the derived class.
4 It provides fast execution It provides slower execution as compare
because the type of an to compile-time because the type of an
object is determined at object is determined at run-time.
compile-time.
5 Compile-time Run-time polymorphism provides more
polymorphism provides less flexibility because all the things are
flexibility because all the resolved at runtime.
things are resolved at
compile-time.
What is Runtime Polymorphism?
Runtime polymorphism or dynamic method dispatch is a process in which a
call to an overridden method is resolved at runtime rather than at compile-
time. In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable.
135. class Bike{
136. void run(){System.out.println("running");}
137. }
138. class Splendor extends Bike{
139. void run(){System.out.println("running safely with 60km");}
140. public static void main(String args[]){
141. Bike b = new Splendor();//upcasting
142. b.run();
143. }
144. }
Test it Now
Output:
running safely with 60km.
Can you achieve Runtime Polymorphism by data members?
No, because method overriding is used to achieve runtime polymorphism
and data members cannot be overridden. We can override the member
functions but not the data members. Consider the example given below.
145. class Bike{
146. int speedlimit=90;
147. }
148. class Honda3 extends Bike{
149. int speedlimit=150;
150. public static void main(String args[]){
151. Bike obj=new Honda3();
152. System.out.println(obj.speedlimit);//90
153. }
What is the difference between static binding and dynamic binding?
In case of the static binding, the type of the object is determined at compile-
time whereas, in the dynamic binding, the type of the object is determined at
runtime.
Static Binding
154. class Dog{
155. private void eat(){System.out.println("dog is eating...");}
156.
157. public static void main(String args[]){
158. Dog d1=new Dog();
159. d1.eat();
160. }
161. }
Dynamic Binding
162. class Animal{
163. void eat(){System.out.println("animal is eating...");}
164. }
165.
166. class Dog extends Animal{
167. void eat(){System.out.println("dog is eating...");}
168.
169. public static void main(String args[]){
170. Animal a=new Dog();
171. a.eat();
172. }
173. }
What is the abstraction?
Abstraction is a process of hiding the implementation details and showing
only functionality to the user. It displays just the essential things to the user
and hides the internal information, for example, sending SMS where you type
the text and send the message. You don't know the internal processing
about the message delivery. Abstraction enables you to focus on what the
object does instead of how it does it. Abstraction lets you focus on what the
object does instead of how it does it.
In Java, there are two ways to achieve the abstraction.
ADVERTISEMENT
Abstract Class
Interface
What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation wraps
code and data into a single unit.
More details.
What is the abstract class?
A class that is declared as abstract is known as an abstract class. It needs to
be extended and its method implemented. It cannot be instantiated. It can
have abstract methods, non-abstract methods, constructors, and static
methods. It can also have the final methods which will force the subclass not
to change the body of the method. Consider the following example.
174. abstract class Bike{
175. abstract void run();
176. }
177. class Honda4 extends Bike{
178. void run(){System.out.println("running safely");}
179. public static void main(String args[]){
180. Bike obj = new Honda4();
181. obj.run();
182. }
183. }
Can there be an abstract method without an abstract class?
No, if there is an abstract method in a class, that class must be abstract.
Can you use abstract and final both with a method?
No, because we need to override the abstract method to provide its
implementation, whereas we can't override the final method.
113) Is it possible to instantiate the abstract class?
No, the abstract class can never be instantiated even if it contains a
constructor and all of its methods are implemented.
114) What is the interface?
The interface is a blueprint for a class that has static constants and abstract
methods. It can be used to achieve full abstraction and multiple inheritance.
It is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java. In other words, you can say that
interfaces can have abstract methods and variables. Java Interface also
represents the IS-A relationship. It cannot be instantiated just like the
abstract class. However, we need to implement it to define its methods.
Since Java 8, we can have the default, static, and private methods in an
interface.
Can you declare an interface method static?
No, because methods of an interface are abstract by default, and we can not
use static and abstract together.
Can the Interface be final?
No, because an interface needs to be implemented by the other class and if
it is final, it can't be implemented by any class.
117) What is a marker interface?
A Marker interface can be defined as the interface which has no data
member and member functions. For example, Serializable, Cloneable are
marker interfaces. The marker interface can be declared as follows.
184. public interface Serializable{
185. }
118) What are the differences between abstract class and
interface?
Abstract class Interface
An abstract class can have a method The interface has only abstract
body (non-abstract methods). methods.
An abstract class can have instance An interface cannot have instance
variables. variables.
An abstract class can have the The interface cannot have the
constructor. constructor.
An abstract class can have static The interface cannot have static
methods. methods.
You can extend one abstract class. You can implement multiple
interfaces.
The abstract class can provide the The Interface can't provide the
implementation of the interface. implementation of the
abstract class.
The abstract keyword is used to The interface keyword is used
declare an abstract class. to declare an interface.
An abstract class can extend another An interface can extend another
Java class and implement multiple Java Java interface only.
interfaces.
An abstract class can be extended An interface class can be
using keyword extends implemented using keyword
implements
A Java abstract class can have class Members of a Java interface are
members like private, protected, etc. public by default.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
119) Can we define private and protected modifiers for the
members in interfaces?
No, they are implicitly public.
120) When can an object reference be cast to an interface
reference?
An object reference can be cast to an interface reference when the object
implements the referenced interface.
What are the advantages of Encapsulation in Java?
There are the following advantages of Encapsulation in Java?
By providing only the setter or getter method, you can make the class
read-only or write-only. In other words, you can skip the getter or
setter methods.
It provides you the control over the data. Suppose you want to set the
value of id which should be greater than 100 only, you can write the
logic inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not
be able to access the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters
and setters. So, it is easy and fast to create an encapsulated class in
Java.
What is the package?
A package is a group of similar type of classes, interfaces, and sub-packages.
It provides access protection and removes naming collision. The packages in
Java can be categorized into two forms, inbuilt package, and user-defined
package. There are many built-in packages such as Java, lang, awt, javax,
swing, net, io, util, sql, etc. Consider the following example to create a
package in Java.
186. //save as Simple.java
187. package mypack;
188. public class Simple{
189. public static void main(String args[]){
190. System.out.println("Welcome to package");
191. }
192. }
How can we access some class in another class in Java?
There are two ways to access a class in another class.
By using the fully qualified name: To access a class in a different
package, either we must use the fully qualified name of that class, or
we must import the package containing that class.
By using the relative path, We can use the path of the class that is
related to the package that contains our class. It can be the same or
subpackage.
How many types of exception can occur in a Java program?
There are mainly two types of exceptions: checked and unchecked. Here, an
error is considered as the unchecked exception. According to Oracle, there
are three types of exceptions:
Checked Exception: Checked exceptions are the one which are
checked at compile-time. For example, SQLException,
ClassNotFoundException, etc.
Unchecked Exception: Unchecked exceptions are the one which are
handled at runtime because they can not be checked at compile-time.
For example, ArithmaticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
Error: Error cause the program to exit since they are not recoverable.
For Example, OutOfMemoryError, AssertionError, etc.
132) What is Exception Handling?
Exception Handling is a mechanism that is used to handle runtime errors. It
is used primarily to handle checked exceptions. Exception handling
maintains the normal flow of the program. There are mainly two types of
exceptions: checked and unchecked. Here, the error is considered as the
unchecked exception.
More details.
133) Explain the hierarchy of Java Exception classes?
The java.lang.Throwable class is the root class of Java Exception hierarchy
which is inherited by two subclasses: Exception and Error. A hierarchy of Java
Exception classes are given below:
134) What is the difference between Checked Exception and
Unchecked Exception?
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions, e.g., IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions, e.g., ArithmeticException, NullPointerException, etc. Unchecked
exceptions are not checked at compile-time.
More details.
135) What is the base class for Error and Exception?
The Throwable class is the base class for Error and Exception.
136) Is it necessary that each try block must be followed by a catch
block?
It is not necessary that each try block must be followed by a catch block. It
should be followed by either a catch block OR a finally block. So whatever
exceptions are likely to be thrown should be declared in the throws clause of
the method. Consider the following example.
193. public class Main{
194. public static void main(String []args){
195. try{
196. int a = 1;
197. System.out.println(a/0);
198. }
199. finally
200. {
201. System.out.println("rest of the code...");
202. }
203. }
204. }
205.
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
What is finally block?
The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not. In other words, we can say
that finally block is the block which is always executed. Finally block follows
try or catch block. If you don't handle the exception, before terminating the
program, JVM runs finally block, (if any). The finally block is mainly used to
place the cleanup code such as closing a file or closing a connection. Here,
we must know that 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).
More details.
139) Can finally block be used without a catch?
Yes, According to the definition of finally block, it must be followed by a try
or catch block, therefore, we can use try block instead of catch. More details.
140) Is there any case when finally will not be executed?
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).More details.
141) What is the difference between throw and throws?
throw keyword throws keyword
1) The throw keyword is used The throws keyword is used to declare an
to throw an exception exception.
explicitly.
2) The checked exceptions The checked exception can be propagated
cannot be propagated with with throws
throw only.
3) The throw keyword is The throws keyword is followed by class.
followed by an instance.
4) The throw keyword is used The throws keyword is used with the
within the method. method signature.
5) You cannot throw multiple You can declare multiple exceptions, e.g.,
exceptions. public void method()throws IOException,
SQLException.
More details.
What is String Pool?
String pool is the space reserved in the heap memory that can be used to
store the strings. The main advantage of using the String pool is whenever
we create a string literal; the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is
created and placed in the pool. Therefore, it saves the memory by avoiding
the duplicacy.
150) What is the meaning of immutable regarding String?
The simple meaning of immutable is unmodifiable or unchangeable. In Java,
String is immutable, i.e., once string object has been created, its value can't
be changed. Consider the following example for better understanding.
206. class Testimmutablestring{
207. public static void main(String args[]){
208. String s="Sachin";
209. s.concat(" Tendulkar");//concat() method appends the string at
the end
210. System.out.println(s);//will print Sachin because strings are
immutable objects
211. }
212. }
Test it Now
Output:
Sachin
More details.
151) Why are the objects immutable in java?
Because Java uses the concept of the string literal. Suppose there are five
reference variables, all refer to one object "sachin". If one reference variable
changes the value of the object, it will be affected by all the reference
variables. That is why string objects are immutable in java.
More details.
152) How many ways can we create the string object?
1) String Literal
Java String literal is created by using double quotes. For Example:
213. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the pooled
instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. String objects are stored in a
special memory area known as the string constant pool For example:
214. String s1="Welcome";
215. String s2="Welcome";//It doesn't create a new instance
2) By new keyword
216. String s=new String("Welcome");//creates two objects and one
reference variable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the constant string pool.
The variable s will refer to the object in a heap (non-pool).
153) How many objects will be created in the following code?
217. String s1="Welcome";
218. String s2="Welcome";
219. String s3="Welcome";
Only one object will be created using the above code because strings in Java
are immutable.
More details.
154) Why java uses the concept of the string literal?
To make Java more memory efficient (because no new objects are created if
it exists already in the string constant pool).
More details.
155) How many objects will be created in the following code?
220. String s = new String("Welcome");
Two objects, one in string constant pool and other in non-pool(heap).
More details.
What are the differences between String and StringBuffer?
The differences between the String and StringBuffer is given in the table
below.
N String StringBuffer
o
.
1 The String class is immutable. The StringBuffer class is
) mutable.
2 The String is slow and consumes more The StringBuffer is fast and
) memory when you concat too many consumes less memory
strings because every time it creates a when you cancat strings.
new instance.
3 The String class overrides the equals() The StringBuffer class
) method of Object class. So you can doesn't override the
compare the contents of two strings by equals() method of Object
equals() method. class.
159) What are the differences between StringBuffer and
StringBuilder?
The differences between the StringBuffer and StringBuilder is given below.
N StringBuffer StringBuilder
o
.
1 StringBuffer is synchronized, i.e., StringBuilder is non-
) thread safe. It means two synchronized,i.e., not thread safe. It
threads can't call the methods of means two threads can call the
StringBuffer simultaneously. methods of StringBuilder
simultaneously.
2 StringBuffer is less efficient than StringBuilder is more efficient than
) StringBuilder. StringBuffer.
What is the purpose of toString() method in Java?
The toString() method returns the string representation of an object. If you
print any object, java compiler internally invokes the toString() method on
the object. So overriding the toString() method, returns the desired output, it
can be the state of an object, etc. depending upon your implementation. By
overriding the toString() method of the Object class, we can return the
values of the object, so we don't need to write much code. Consider the
following example.
221. class Student{
222. int rollno;
223. String name;
224. String city;
225.
226. Student(int rollno, String name, String city){
227. this.rollno=rollno;
228. this.name=name;
229. this.city=city;
230. }
231.
232. public String toString(){//overriding the toString() method
233. return rollno+" "+name+" "+city;
234. }
235. public static void main(String args[]){
236. Student s1=new Student(101,"Raj","lucknow");
237. Student s2=new Student(102,"Vijay","ghaziabad");
238.
239. System.out.println(s1);//compiler writes here s1.toString()
240. System.out.println(s2);//compiler writes here s2.toString()
241. }
242. }
What are the advantages of Java inner classes?
There are two types of advantages of Java inner classes.
Nested classes represent a special type of relationship that is it can
access all the members (data members and methods) of the outer
class including private.
Nested classes are used to develop a more readable and maintainable
code because it logically groups classes and interfaces in one place
only.
Code Optimization: It requires less code to write.
What is a nested class?
The nested class can be defined as the class which is defined inside another
class or interface. We use the nested class to logically group classes and
interfaces in one place so that it can be more readable and maintainable. A
nested class can access all the data members of the outer class including
private data members and methods. The syntax of the nested class is
defined below.
What is Garbage Collection?
Garbage collection is a process of reclaiming the unused runtime objects. It
is performed for memory management. In other words, we can say that It is
the process of removing unused objects from the memory to free up space
and make this space available for Java Virtual Machine. Due to garbage
collection java gives 0 as output to a variable whose value is not set, i.e., the
variable has been defined but not initialized. For this purpose, we were using
free() function in the C language and delete() in C++. In Java, it is performed
automatically. So, java provides better memory management.
More details.
180) What is gc()?
The gc() method is used to invoke the garbage collector for cleanup
processing. This method is found in System and Runtime classes. This
function explicitly makes the Java Virtual Machine free up the space occupied
by the unused objects so that it can be utilized or reused. Consider the
following example for the better understanding of how the gc() method
invoke the garbage collector.
How is garbage collection controlled?
Garbage collection is managed by JVM. It is performed when there is not
enough space in the memory and memory is running low. We can externally
call the System.gc() for the garbage collection. However, it depends upon
the JVM whether to perform it or not.
What is the purpose of the finalize() method?
The finalize() method is invoked just before the object is garbage collected. It
is used to perform cleanup processing. The Garbage collector of JVM collects
only those objects that are created by new keyword. So if you have created
an object without new, you can use the finalize method to perform cleanup
processing (destroying remaining objects). The cleanup processing is the
process to free up all the resources, network which was previously used and
no longer needed. It is essential to remember that it is not a reserved
keyword, finalize method is present in the object class hence it is available in
every class as object class is the superclass of every class in java. Here, we
must
What is the difference between final, finally and finalize?
N final finally finalize
o
.
1 Final is used to apply Finally is used to Finalize is used to
) restrictions on class, method, place important perform clean up
and variable. The final class code, it will be processing just
can't be inherited, final executed whether before an object
method can't be overridden, an exception is is garbage
and final variable value can't handled or not. collected.
be changed.
2 Final is a keyword. Finally is a block. Finalize is a
) method.
What do you understand by an IO stream?
The stream is a sequence of data that flows from source to destination. It is
composed of bytes. In Java, three streams are created for us automatically.
System.out: standard output stream
System.in: standard input stream
System.err: standard error stream
What is serialization?
Serialization in Java is a mechanism of writing the state of an object into a
byte stream. It is used primarily in Hibernate, RMI, JPA, EJB and JMS
technologies. It is mainly used to travel object's state on the network (which
is known as marshaling). Serializable interface is used to perform
serialization. It is helpful when you require to save the state of a program to
storage such as the file. At a later point of time, the content of this file can
be restored using deserialization. It is also required to implement
RMI(Remote Method Invocation). With the help of RMI, it is possible to invoke
the method of a Java object on one machine to another machine.
More details.
200) How can you make a class serializable in Java?
A class can become serializable by implementing the Serializable interface.
201) How can you avoid serialization in child class if the base class
is implementing the Serializable interface?
It is very tricky to prevent serialization of child class if the base class is
intended to implement the Serializable interface. However, we cannot do it
directly, but the serialization can be avoided by implementing the
writeObject() or readObject() methods in the subclass and throw
NotSerializableException from these methods. Consider the following
example.
What is Deserialization?
Deserialization is the process of reconstructing the object from the serialized
state. It is the reverse operation of serialization. An ObjectInputStream
deserializes objects and primitive data written using an ObjectOutputStream.
What is the difference between Serializable and Externalizable
interface?
N Serializable Externalizable
o
.
1 The Serializable interface The Externalizable interface contains is
) does not have any method, not a marker interface, It contains two
i.e., it is a marker interface. methods, i.e., writeExternal() and
readExternal().
2 It is used to "mark" Java The Externalizable interface provides
) classes so that objects of control of the serialization logic to the
these classes may get the programmer.
certain capability.
3 It is easy to implement but It is used to perform the serialization
) has the higher performance and often result in better performance.
cost.
4 No class constructor is called We must call a public default
) in serialization. constructor while using this interface.
. What are wrapper classes?
Wrapper classes are classes that allow primitive types to be accessed as
objects. In other words, we can say that wrapper classes are built-in java
classes which allow the conversion of objects to primitives and primitives to
objects. The process of converting primitives to objects is called autoboxing,
and the process of converting objects to primitives is called unboxing. There
are eight wrapper classes present in java.lang package is given below.
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
219)What are autoboxing and unboxing? When does it occur?
The autoboxing is the process of converting primitive data type to the
corresponding wrapper class object, eg., int to Integer. The unboxing is the
process of converting wrapper class object to primitive data type. For eg.,
integer to int. Unboxing and autoboxing occur automatically in Java.
However, we can externally convert one into another by using the methods
like valueOf() or xxxValue().
It can occur whenever a wrapper class object is expected, and primitive data
type is provided or vice versa.
Adding primitive types into Collection like ArrayList in Java.
Creating an instance of parameterized classes ,e.g., ThreadLocal which
expect Type.
Java automatically converts primitive to object whenever one is
required and another is provided in the method calling.
When a primitive type is assigned to an object type.
What is object cloning?
The object cloning is a way to create an exact copy of an object. The clone()
method of the Object class is used to clone an object. The
java.lang.Cloneable interface must be implemented by the class whose
object clone we want to create. If we don't implement Cloneable interface,
clone() method generates CloneNotSupportedException. The clone() method
is defined in the Object class. The syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException
What is the purpose of the System class?
The purpose of the System class is to provide access to system resources
such as standard input and output. It cannot be instantiated. Facilities
provided by System class are given below.
Standard input
Error output streams
Standard output
utility method to copy the portion of an array
utilities to load files and libraries
What is a JavaBean?
JavaBean is a reusable software component written in the Java programming
language, designed to be manipulated visually by a software development
environment, like JBuilder or VisualAge for Java. t. A JavaBean encapsulates
many objects into one object so that we can access this object from multiple
places. Moreover, it provides the easy maintenance. Consider the following
example to create a JavaBean class.
What is the purpose of using the Java bean?
According to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object so that we can access this object
from multiple places. Moreover, it provides the easy maintenance.
241) What do you understand by the bean persistent property?
The persistence property of Java bean comes into the act when the
properties, fields, and state information are saved to or retrieve from the
storage.
What is multithreading?
Multithreading is a process of executing multiple threads simultaneously.
Multithreading is used to obtain the multitasking. It consumes less memory
and gives the fast and efficient performance. Its main advantages are:
Threads share the same address space.
The thread is lightweight.
The cost of communication between the processes is low.
More details.
2) What is the thread?
A thread is a lightweight subprocess. It is a separate path of execution
because each thread runs in a different stack frame. A process may contain
multiple threads. Threads share the process resources, but still, they execute
independently.
More details.
3) Differentiate between process and thread?
There are the following differences between the process and thread.
A Program in the execution is called the process whereas; A thread is a
subset of the process
Processes are independent whereas threads are the subset of process.
Process have different address space in memory, while threads contain
a shared address space.
Context switching is faster between the threads as compared to
processes.
Inter-process communication is slower and expensive than inter-thread
communication.
Any change in Parent process doesn't affect the child process whereas
changes in parent thread can affect the child thread.
4) What do you understand by inter-thread communication?
The process of communication between synchronized threads is
termed as inter-thread communication.
Inter-thread communication is used to avoid thread polling in Java.
The thread is paused running in its critical section, and another thread
is allowed to enter (or lock) in the same critical section to be executed.
It can be obtained by wait(), notify(), and notifyAll() methods.
5) What is the purpose of wait() method in Java?
The wait() method is provided by the Object class in Java. This method is
used for inter-thread communication in Java. The java.lang.Object.wait() is
used to pause the current thread, and wait until another thread does not call
the notify() or notifyAll() method. Its syntax is given below.
public final void wait()
6) Why must wait() method be called from the synchronized block?
We must call the wait method otherwise it will throw
java.lang.IllegalMonitorStateException exception. Moreover, we need
wait() method for inter-thread communication with notify() and notifyAll().
Therefore It must be present in the synchronized block for the proper and
correct communication.
7) What are the advantages of multithreading?
Multithreading programming has the following advantages:
Multithreading allows an application/program to be always reactive for
input, even already running with some background tasks
Multithreading allows the faster execution of tasks, as threads execute
independently.
Multithreading provides better utilization of cache memory as threads
share the common memory resources.
Multithreading reduces the number of the required server as one
server can execute multiple threads at a time.
8) What are the states in the lifecycle of a Thread?
A thread can have one of the following states during its lifetime:
243. New: In this state, a Thread class object is created using a new
operator, but the thread is not alive. Thread doesn't start until we call
the start() method.
244. Runnable: In this state, the thread is ready to run after calling
the start() method. However, the thread is not yet selected by the
thread scheduler.
245. Running: In this state, the thread scheduler picks the thread
from the ready state, and the thread is running.
246. Waiting/Blocked: In this state, a thread is not running but still
alive, or it is waiting for the other thread to finish.
247. Dead/Terminated: A thread is in terminated or dead state
when the run() method exits.
9) What is the difference between preemptive scheduling and time
slicing?
Under preemptive scheduling, the highest priority task executes until it
enters the waiting or dead states or a higher priority task comes into
existence. Under time slicing, a task executes for a predefined slice of time
and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.
10) What is context switching?
In Context switching the state of the process (or thread) is stored so that it
can be restored and execution can be resumed from the same point later.
Context switching enables the multiple processes to share the same CPU.
11) Differentiate between the Thread class and Runnable interface
for creating a Thread?
The Thread can be created by using two ways.
By extending the Thread class
By implementing the Runnable interface
However, the primary differences between both the ways are given below:
By extending the Thread class, we cannot extend any other class, as
Java does not allow multiple inheritances while implementing the
Runnable interface; we can also extend other base class(if required).
By extending the Thread class, each of thread creates the unique
object and associates with it while implementing the Runnable
interface; multiple threads share the same object
Thread class provides various inbuilt methods such as getPriority(),
isAlive and many more while the Runnable interface provides a single
method, i.e., run().
12) What does join() method?
The join() method waits for a thread to die. In other words, it causes the
currently running threads to stop executing until the thread it joins with
completes its task. Join method is overloaded in Thread class in the following
ways.
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
More details.
13) Describe the purpose and working of sleep() method.
The sleep() method in java is used to block a thread for a particular time,
which means it pause the execution of a thread for a specific time. There are
two methods of doing so.
Syntax:
public static void sleep(long milliseconds)throws InterruptedException
public static void sleep(long milliseconds, int nanos)throws
InterruptedException
Working of sleep() method
When we call the sleep() method, it pauses the execution of the current
thread for the given time and gives priority to another thread(if available).
Moreover, when the waiting time completed then again previous thread
changes its state from waiting to runnable and comes in running state, and
the whole process works so on till the execution doesn't complete.
14) What is the difference between wait() and sleep() method?
wait() sleep()
1) The wait() method is defined in The sleep() method is defined in
Object class. Thread class.
2) The wait() method releases the The sleep() method doesn't release
lock. the lock.
15) Is it possible to start a thread twice?
ADVERTISEMENT
No, we cannot restart the thread, as once a thread started and executed, it
goes to the Dead state. Therefore, if we try to start a thread twice, it will give
a runtimeException "java.lang.IllegalThreadStateException". Consider the
following example.
248. public class Multithread1 extends Thread
249. {
250. public void run()
251. {
252. try {
253. System.out.println("thread is executing now........");
254. } catch(Exception e) {
255. }
256. }
257. public static void main (String[] args) {
258. Multithread1 m1= new Multithread1();
259. m1.start();
260. m1.start();
261. }
262. }
Output
thread is executing now........
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at Multithread1.main(Multithread1.java:13)
More details.
16) Can we call the run() method instead of start()?
Yes, calling run() method directly is valid, but it will not work as a thread
instead it will work as a normal object. There will not be context-switching
between the threads. When we call the start() method, it internally calls the
run() method, which creates a new stack for a thread while directly calling
the run() will not create a new stack.
More details.
17) What about the daemon threads?
The daemon threads are the low priority threads that provide the
background support and services to the user threads. Daemon thread gets
automatically terminated by the JVM if the program remains with the
daemon thread only, and all other user threads are ended/died. There are
two methods for daemon thread available in the Thread class:
public void setDaemon(boolean status): It used to mark the
thread daemon thread or a user thread.
public boolean isDaemon(): It checks the thread is daemon or not.
More details.
18)Can we make the user thread as daemon thread if the thread is
started?
ADVERTISEMENT
ADVERTISEMENT
No, if you do so, it will throw IllegalThreadStateException. Therefore, we can
only create a daemon thread before starting the thread.
263. class Testdaemon1 extends Thread{
264. public void run(){
265. System.out.println("Running thread is daemon...");
266. }
267. public static void main (String[] args) {
268. Testdaemon1 td= new Testdaemon1();
269. td.start();
270. setDaemon(true);// It will throw the exception: td.
271. }
272. }
Output
Running thread is daemon...
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1359)
at Testdaemon1.main(Testdaemon1.java:8)
More details.
19)What is shutdown hook?
The shutdown hook is a thread that is invoked implicitly before JVM shuts
down. So we can use it to perform clean up the resource or save the state
when JVM shuts down normally or abruptly. We can add shutdown hook by
using the following method:
273. public void addShutdownHook(Thread hook){}
274. Runtime r=Runtime.getRuntime();
275. r.addShutdownHook(new MyThread());
Some important points about shutdown hooks are :
Shutdown hooks initialized but can only be started when JVM shutdown
occurred.
Shutdown hooks are more reliable than the finalizer() because there
are very fewer chances that shutdown hooks not run.
The shutdown hook can be stopped by calling the halt(int) method of
Runtime class.
More details.
20)When should we interrupt a thread?
We should interrupt a thread when we want to break out the sleep or wait
state of a thread. We can interrupt a thread by calling the interrupt()
throwing the InterruptedException.
More details.
21) What is the synchronization?
Synchronization is the capability to control the access of multiple threads to
any shared resource. It is used:
276. To prevent thread interference.
277. To prevent consistency problem.
When the multiple threads try to do the same task, there is a possibility of an
erroneous result, hence to remove this issue, Java uses the process of
synchronization which allows only one thread to be executed at a time.
Synchronization can be achieved in three ways:
by the synchronized method
by synchronized block
by static synchronization
Syntax for synchronized block
278. synchronized(object reference expression)
279. {
280. //code block
281. }
282.
More details.
22) What is the purpose of the Synchronized block?
The Synchronized block can be used to perform synchronization on any
specific resource of the method. Only one thread at a time can execute on a
particular resource, and all other threads which attempt to enter the
synchronized block are blocked.
Synchronized block is used to lock an object for any shared resource.
The scope of the synchronized block is limited to the block on which, it
is applied. Its scope is smaller than a method.
More details.
23)Can Java object be locked down for exclusive use by a given
thread?
Yes. You can lock an object by putting it in a "synchronized" block. The
locked object is inaccessible to any thread other than the one that explicitly
claimed it.
ADVERTISEMENT
ADVERTISEMENT
24) What is static synchronization?
If you make any static method as synchronized, the lock will be on the class
not on the object. If we use the synchronized keyword before a method so it
will lock the object (one thread can access an object at a time) but if we use
static synchronized so it will lock a class (one thread can access a class at a
time). More details.
25)What is the difference between notify() and notifyAll()?
The notify() is used to unblock one waiting thread whereas notifyAll() method
is used to unblock all the threads in waiting state.
26)What is the deadlock?
Deadlock is a situation in which every thread is waiting for a resource which
is held by some other waiting thread. In this situation, Neither of the thread
executes nor it gets the chance to be executed. Instead, there exists a
universal waiting state among all the threads. Deadlock is a very
complicated situation which can break our code at runtime.
More details.
27) How to detect a deadlock condition? How can it be avoided?
We can detect the deadlock condition by running the code on cmd and
collecting the Thread Dump, and if any deadlock is present in the code, then
a message will appear on cmd.
Ways to avoid the deadlock condition in Java:
Avoid Nested lock: Nested lock is the common reason for deadlock
as deadlock occurs when we provide locks to various threads so we
should give one lock to only one thread at some particular time.
Avoid unnecessary locks: we must avoid the locks which are not
required.
Using thread join: Thread join helps to wait for a thread until another
thread doesn't finish its execution so we can avoid deadlock by
maximum use of join method.
28) What is Thread Scheduler in java?
In Java, when we create the threads, they are supervised with the help of a
Thread Scheduler, which is the part of JVM. Thread scheduler is only
responsible for deciding which thread should be executed. Thread scheduler
uses two mechanisms for scheduling the threads: Preemptive and Time
Slicing.
Java thread scheduler also works for deciding the following for a thread:
It selects the priority of the thread.
It determines the waiting time for a thread
It checks the Nature of thread
29) Does each thread have its stack in multithreaded programming?
Yes, in multithreaded programming every thread maintains its own or
separate stack area in memory due to which every thread is independent of
each other.
30) How is the safety of a thread achieved?
If a method or class object can be used by multiple threads at a time without
any race condition, then the class is thread-safe. Thread safety is used to
make a program safe to use in multithreaded programming. It can be
achieved by the following ways:
Synchronization
Using Volatile keyword
Using a lock based mechanism
Use of atomic wrapper classes
31) What is race-condition?
A Race condition is a problem which occurs in the multithreaded
programming when various threads execute simultaneously accessing a
shared resource at the same time. The proper use of synchronization can
avoid the Race condition.
32) What is the volatile keyword in java?
Volatile keyword is used in multithreaded programming to achieve the
thread safety, as a change in one volatile variable is visible to all other
threads so one variable can be used by one thread at a time.
33) What do you understand by thread pool?
Java Thread pool represents a group of worker threads, which are
waiting for the task to be allocated.
Threads in the thread pool are supervised by the service provider
which pulls one thread from the pool and assign a job to it.
After completion of the given task, thread again came to the thread
pool.
The size of the thread pool depends on the total number of threads
kept at reserve for execution.
The advantages of the thread pool are :
Using a thread pool, performance can be enhanced.
Using a thread pool, better system stability can occur.
1) What is the Collection framework in Java?
Collection Framework is a combination of classes and interface, which is
used to store and manipulate the data in the form of objects. It provides
various classes such as ArrayList, Vector, Stack, and HashSet, etc. and
interfaces such as List, Queue, Set, etc. for this purpose.
2) What are the main differences between array and collection?
Array and Collection are somewhat similar regarding storing the references
of objects and manipulating the data, but they differ in many ways. The main
differences between the array and Collection are defined below:
Arrays are always of fixed size, i.e., a user can not increase or
decrease the length of the array according to their requirement or at
runtime, but In Collection, size can be changed dynamically as per
need.
Arrays can only store homogeneous or similar type objects, but in
Collection, heterogeneous objects can be stored.
Arrays cannot provide the ?ready-made? methods for user
requirements as sorting, searching, etc. but Collection includes
readymade methods to use.
3) Explain various interfaces used in Collection framework?
Collection framework implements various interfaces, Collection interface and
Map interface (java.util.Map) are the mainly used interfaces of Java
Collection Framework. List of interfaces of Collection Framework is given
below:
PauseNext
Unmute
Current Time 0:08
/
Duration 18:10
Loaded: 4.40%
Â
Fullscreen
1. Collection interface: Collection (java.util.Collection) is the primary
interface, and every collection must implement this interface.
Syntax:
283. public interface Collection<E>extends Iterable
Where <E> represents that this interface is of Generic type
2. List interface: List interface extends the Collection interface, and it is an
ordered collection of objects. It contains duplicate elements. It also allows
random access of elements.
Syntax:
284. public interface List<E> extends Collection<E>
3. Set interface: Set (java.util.Set) interface is a collection which cannot
contain duplicate elements. It can only include inherited methods of
Collection interface
Syntax:
285. public interface Set<E> extends Collection<E>
Queue interface: Queue (java.util.Queue) interface defines queue data
structure, which stores the elements in the form FIFO (first in first out).
Syntax:
286. public interface Queue<E> extends Collection<E>
4. Dequeue interface: it is a double-ended-queue. It allows the insertion
and removal of elements from both ends. It implants the properties of both
Stack and queue so it can perform LIFO (Last in first out) stack and FIFO (first
in first out) queue, operations.
Syntax:
287. public interface Dequeue<E> extends Queue<E>
5. Map interface: A Map (java.util.Map) represents a key, value pair
storage of elements. Map interface does not implement the Collection
interface. It can only contain a unique key but can have duplicate elements.
There are two interfaces which implement Map in java that are Map interface
and Sorted Map.
4) What is the difference between ArrayList and Vector?
N ArrayList Vector
o
.
1 ArrayList is not synchronized. Vector is synchronized.
)
2 ArrayList is not a legacy class. Vector is a legacy class.
)
3 ArrayList increases its size by Vector increases its size by doubling
) 50% of the array size. the array size.
4 ArrayList is not ?thread-safe? as Vector list is ?thread-safe? as it?s
) it is not synchronized. every method is synchronized.
5) What is the difference between ArrayList and LinkedList?
N ArrayList LinkedList
o
.
1 ArrayList uses a dynamic LinkedList uses a doubly linked list.
) array.
2 ArrayList is not efficient for LinkedList is efficient for manipulation.
) manipulation because too
much is required.
3 ArrayList is better to store LinkedList is better to manipulate data.
) and fetch data.
4 ArrayList provides random LinkedList does not provide random
) access. access.
5 ArrayList takes less memory LinkedList takes more memory
) overhead as it stores only overhead, as it stores the object as well
object as the address of that object.
6) What is the difference between Iterator and ListIterator?
Iterator traverses the elements in the forward direction only whereas
ListIterator traverses the elements into forward and backward direction.
N Iterator ListIterator
o
.
1 The Iterator traverses the ListIterator traverses the elements in
) elements in the forward backward and forward directions
direction only. both.
2 The Iterator can be used in List, ListIterator can be used in List only.
) Set, and Queue.
3 The Iterator can only perform ListIterator can perform ?add,? ?
) remove operation while remove,? and ?set? operation while
traversing the collection. traversing the collection.
7) What is the difference between Iterator and Enumeration?
N Iterator Enumeration
o
.
1 The Iterator can traverse legacy Enumeration can traverse only
) and non-legacy elements. legacy elements.
2 The Iterator is fail-fast. Enumeration is not fail-fast.
)
3 The Iterator is slower than Enumeration is faster than
) Enumeration. Iterator.
4 The Iterator can perform remove The Enumeration can perform
) operation while traversing the only traverse operation on the
collection. collection.
8) What is the difference between List and Set?
The List and Set both extend the collection interface. However, there are
some differences between the both which are listed below.
The List can contain duplicate elements whereas Set includes unique
items.
The List is an ordered collection which maintains the insertion order
whereas Set is an unordered collection which does not preserve the
insertion order.
The List interface contains a single legacy class which is Vector class
whereas Set interface does not have any legacy class.
The List interface can allow n number of null values whereas Set
interface only allows a single null value.
9) What is the difference between HashSet and TreeSet?
The HashSet and TreeSet, both classes, implement Set interface. The
differences between the both are listed below.
HashSet maintains no order whereas TreeSet maintains ascending
order.
HashSet impended by hash table whereas TreeSet implemented by a
Tree structure.
HashSet performs faster than TreeSet.
HashSet is backed by HashMap whereas TreeSet is backed by
TreeMap.
10) What is the difference between Set and Map?
The differences between the Set and Map are given below.
Set contains values only whereas Map contains key and values both.
Set contains unique values whereas Map can contain unique Keys with
duplicate values.
Set holds a single number of null value whereas Map can include a
single null key with n number of null values.
11) What is the difference between HashSet and HashMap?
The differences between the HashSet and HashMap are listed below.
HashSet contains only values whereas HashMap includes the entry
(key, value). HashSet can be iterated, but HashMap needs to convert
into Set to be iterated.
HashSet implements Set interface whereas HashMap implements the
Map interface
HashSet cannot have any duplicate value whereas HashMap can
contain duplicate values with unique keys.
HashSet contains the only single number of null value whereas
HashMap can hold a single null key with n number of null values.
12) What is the difference between HashMap and TreeMap?
The differences between the HashMap and TreeMap are given below.
HashMap maintains no order, but TreeMap maintains ascending order.
HashMap is implemented by hash table whereas TreeMap is
implemented by a Tree structure.
HashMap can be sorted by Key or value whereas TreeMap can be
sorted by Key.
HashMap may contain a null key with multiple null values whereas
TreeMap cannot hold a null key but can have multiple null values.
13) What is the difference between HashMap and Hashtable?
N HashMap Hashtable
o
.
1 HashMap is not synchronized. Hashtable is synchronized.
)
2 HashMap can contain one null key Hashtable cannot contain any null
) and multiple null values. key or null value.
3 HashMap is not ?thread-safe,? so it Hashtable is thread-safe, and it
) is useful for non-threaded can be shared between various
applications. threads.
4 4) HashMap inherits the Hashtable inherits the Dictionary
) AbstractMap class class.
14) What is the difference between Collection and Collections?
ADVERTISEMENT
The differences between the Collection and Collections are given below.
The Collection is an interface whereas Collections is a class.
The Collection interface provides the standard functionality of data
structure to List, Set, and Queue. However, Collections class is to sort
and synchronize the collection elements.
The Collection interface provides the methods that can be used for
data structure whereas Collections class provides the static methods
which can be used for various operation on a collection.
15) What is the difference between Comparable and Comparator?
N Comparable Comparator
o
.
1 Comparable provides only one sort of The Comparator provides
) sequence. multiple sorts of sequences.
2 It provides one method named It provides one method
) compareTo(). named compare().
3 It is found in java.lang package. It is located in java.util
) package.
4 If we implement the Comparable The actual class is not
) interface, The actual class is modified. changed.
16) What do you understand by BlockingQueue?
BlockingQueue is an interface which extends the Queue interface. It provides
concurrency in the operations like retrieval, insertion, deletion. While
retrieval of any element, it waits for the queue to be non-empty. While
storing the elements, it waits for the available space. BlockingQueue cannot
contain null elements, and implementation of BlockingQueue is thread-safe.
Syntax:
288. public interface BlockingQueue<E> extends Queue <E>
17) What is the advantage of Properties file?
If you change the value in the properties file, you don't need to recompile
the java class. So, it makes the application easy to manage. It is used to
store information which is to be changed frequently. Consider the following
example.
289. import java.util.*;
290. import java.io.*;
291. public class Test {
292. public static void main(String[] args)throws Exception{
293. FileReader reader=new FileReader("db.properties");
294.
295. Properties p=new Properties();
296. p.load(reader);
297.
298. System.out.println(p.getProperty("user"));
299. System.out.println(p.getProperty("password"));
300. }
301. }
Output
system
oracle
18) What does the hashCode() method?
The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number if two keys (by
calling equals() method) are identical.
However, it is possible that two hash code numbers can have different or the
same keys.
If two objects do not produce an equal result by using the equals() method,
then the hashcode() method will provide the different integer result for both
the objects.
19) Why we override equals() method?
The equals method is used to check whether two objects are the same or
not. It needs to be overridden if we want to check the objects based on the
property.
For example, Employee is a class that has 3 data members: id, name, and
salary. However, we want to check the equality of employee object by the
salary. Then, we need to override the equals() method.
20) How to synchronize List, Set and Map elements?
Yes, Collections class provides methods to make List, Set or Map elements as
synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}
21) What is the advantage of the generic collection?
There are three main advantages of using the generic collection.
If we use the generic class, we don't need typecasting.
It is type-safe and checked at compile time.
Generic confirms the stability of the code by making it bug detectable
at compile time.
22) What is hash-collision in Hashtable and how it is handled in
Java?
Two different keys with the same hash value are known as hash-collision.
Two separate entries will be kept in a single hash bucket to avoid the
collision. There are two ways to avoid hash-collision.
Separate Chaining
Open Addressing
23) What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.
24) What is the default size of load factor in hashing based
collection?
The default size of load factor is 0.75. The default capacity is computed as
initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the
default capacity of Map.
25) What do you understand by fail-fast?
The Iterator in java which immediately throws
ConcurrentmodificationException, if any structural modification occurs in, is
called as a Fail-fast iterator. Fail-fats iterator does not require any extra
space in memory.
26) What is the difference between Array and ArrayList?
The main differences between the Array and ArrayList are given below.
S Array ArrayList
N
1 The Array is of fixed size, means ArrayList is not of the fixed size we
we cannot resize the array as per can change the size dynamically.
need.
2 Arrays are of the static type. ArrayList is of dynamic size.
3 Arrays can store primitive data ArrayList cannot store the primitive
types as well as objects. data types it can only store the
objects.
27) What is the difference between the length of an Array and size
of ArrayList?
The length of an array can be obtained using the property of length whereas
ArrayList does not support length property, but we can use size() method to
get the number of objects in the list.
Finding the length of the array
302. Int [] array = new int[4];
303. System.out.println("The size of the array is " + array.length);
304.
Finding the size of the ArrayList
305. ArrayList<String> list=new ArrayList<String>();
306. list.add("ankit");
307. list.add("nippun");
308. System.out.println(list.size());
309.
28) How to convert ArrayList to Array and Array to ArrayList?
We can convert an Array to ArrayList by using the asList() method of Arrays
class. asList() method is the static method of Arrays class and accepts the
List object. Consider the following syntax:
310. Arrays.asList(item)
We can convert an ArrayList to Array using toArray() method of the ArrayList
class. Consider the following syntax to convert the ArrayList to the List
object.
311. List_object.toArray(new String[List_object.size()])
29) How to make Java ArrayList Read-Only?
We can obtain java ArrayList Read-only by calling the
Collections.unmodifiableCollection() method. When we define an ArrayList as
Read-only then we cannot perform any modification in the collection through
add(), remove() or set() method.
30) How to remove duplicates from ArrayList?
There are two ways to remove duplicates from the ArrayList.
Using HashSet: By using HashSet we can remove the duplicate
element from the ArrayList, but it will not then preserve the insertion
order.
Using LinkedHashSet: We can also maintain the insertion order by
using LinkedHashSet instead of HashSet.
The Process to remove duplicate elements from ArrayList using the
LinkedHashSet:
Copy all the elements of ArrayList to LinkedHashSet.
Empty the ArrayList using clear() method, which will remove all the
elements from the list.
Now copy all the elements of LinkedHashset to ArrayList.
31) How to reverse ArrayList?
To reverse an ArrayList, we can use reverse() method of Collections class.
Consider the following example.
312. import java.util.ArrayList;
313. import java.util.Collection;
314. import java.util.Collections;
315. import java.util.Iterator;
316. import java.util.List;
317. public class ReverseArrayList {
318. public static void main(String[] args) {
319. List list = new ArrayList<>();
320. list.add(10);
321. list.add(50);
322. list.add(30);
323. Iterator i = list.iterator();
324. System.out.println("printing the list....");
325. while(i.hasNext())
326. {
327. System.out.println(i.next());
328. }
329. Iterator i2 = list.iterator();
330. Collections.reverse(list);
331. System.out.println("printing list in reverse order....");
332. while(i2.hasNext())
333. {
334. System.out.println(i2.next());
335. }
336. }
337. }
Output
printing the list....
10
50
30
printing list in reverse order....
30
50
10
32) How to sort ArrayList in descending order?
To sort the ArrayList in descending order, we can use the reverseOrder
method of Collections class. Consider the following example.
338. import java.util.ArrayList;
339. import java.util.Collection;
340. import java.util.Collections;
341. import java.util.Comparator;
342. import java.util.Iterator;
343. import java.util.List;
344.
345. public class ReverseArrayList {
346. public static void main(String[] args) {
347. List list = new ArrayList<>();
348. list.add(10);
349. list.add(50);
350. list.add(30);
351. list.add(60);
352. list.add(20);
353. list.add(90);
354.
355. Iterator i = list.iterator();
356. System.out.println("printing the list....");
357. while(i.hasNext())
358. {
359. System.out.println(i.next());
360. }
361.
362. Comparator cmp = Collections.reverseOrder();
363. Collections.sort(list,cmp);
364. System.out.println("printing list in descending order....");
365. Iterator i2 = list.iterator();
366. while(i2.hasNext())
367. {
368. System.out.println(i2.next());
369. }
370.
371. }
372. }
Output
printing the list....
10
50
30
60
20
90
printing list in descending order....
90
60
50
30
20
10
33) How to synchronize ArrayList?
We can synchronize ArrayList in two ways.
Using Collections.synchronizedList() method
Using CopyOnWriteArrayList<T>
34) When to use ArrayList and LinkedList?
LinkedLists are better to use for the update operations whereas ArrayLists
are better to use for the search operations.
JDBC Interview Questions
A list of top frequently asked JDBC interview questions and answers is given
below.
1) What is JDBC?
JDBC is a Java API that is used to connect and execute the query to the
database. JDBC API uses JDBC drivers to connect to the database. JDBC API
can be used to access tabular data stored into any relational database.
More details.
2) What is JDBC Driver?
JDBC Driver is a software component that enables Java application to interact
with the database. There are 4 types of JDBC drivers:
373. JDBC-ODBC bridge driver: The JDBC-ODBC bridge driver uses
the ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is
now discouraged because of the thin driver. It is easy to use and can
be easily connected to any database.
374. Native-API driver (partially java driver): The Native API
driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written
entirely in Java. Its performance is better than JDBC-ODBC bridge
driver. However, the native driver must be installed on each client
machine.
375. Network Protocol driver (fully java driver): The Network
Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It
is entirely written in Java. There is no requirement of the client-side
library because of the application server that can perform many tasks
like auditing, load balancing, logging, etc.
376. Thin driver (fully java driver): The thin driver converts JDBC
calls directly into the vendor-specific database protocol. That is why it
is known as the thin driver. It is entirely written in Java language. Its
performance is better than all other drivers however these drivers
depend upon the database.
More details.
3) What are the steps to connect to the database in java?
The following steps are used in database connectivity.
Registering the driver class:
The forName() method of the Class class is used to register the driver class.
This method is used to load the driver class dynamically. Consider the
following example to register OracleDriver class.
a. Class.forName("oracle.jdbc.driver.OracleDriver");
Creating connection:
The getConnection() method of DriverManager class is used to establish the
connection with the database. The syntax of the getConnection() method is
given below.
b. 1) public static Connection getConnection(String url)throws
SQLException
c. 2) public static Connection getConnection(String url,String
name,String password)
d. throws SQLException
Consider the following example to establish the connection with the Oracle
database.
e. Connection con=DriverManager.getConnection(
f. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
Creating the statement:
The createStatement() method of Connection interface is used to create the
Statement. The object of the Statement is responsible for executing queries
with the database.
g. public Statement createStatement()throws SQLException
consider the following example to create the statement object
h. Statement stmt=con.createStatement();
Executing the queries:
The executeQuery() method of Statement interface is used to execute
queries to the database. This method returns the object of ResultSet that can
be used to get all the records of a table.
Syntax of executeQuery() method is given below.
i. public ResultSet executeQuery(String sql)throws SQLException
Example to execute the query
j. ResultSet rs=stmt.executeQuery("select * from emp");
k. while(rs.next()){
l. System.out.println(rs.getInt(1)+" "+rs.getString(2));
m. }
However, to perform the insert and update operations in the database,
executeUpdate() method is used which returns the boolean value to indicate
the successful completion of the operation.
Closing connection:
By closing connection, object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close
the connection.
Syntax of close() method is given below.
n. public void close()throws SQLException
Consider the following example to close the connection.
o. con.close();
More details.
4) What are the JDBC API components?
The java.sql package contains following interfaces and classes for JDBC API.
Interfaces:
Connection: The Connection object is created by using
getConnection() method of DriverManager class. DriverManager is the
factory for connection.
Statement: The Statement object is created by using
createStatement() method of Connection class. The Connection
interface is the factory for Statement.
PreparedStatement: The PrepareStatement object is created by
using prepareStatement() method of Connection class. It is used to
execute the parameterized query.
ResultSet: The object of ResultSet maintains a cursor pointing to a
row of a table. Initially, cursor points before the first row. The
executeQuery() method of Statement interface returns the ResultSet
object.
ResultSetMetaData: The object of ResultSetMetaData interface
cotains the information about the data (table) such as numer of
columns, column name, column type, etc. The getMetaData() method
of ResultSet returns the object of ResultSetMetaData.
DatabaseMetaData: DatabaseMetaData interface provides methods
to get metadata of a database such as the database product name,
database product version, driver name, name of the total number of
tables, the name of the total number of views, etc. The getMetaData()
method of Connection interface returns the object of
DatabaseMetaData.
CallableStatement: CallableStatement interface is used to call the
stored procedures and functions. We can have business logic on the
database through the use of stored procedures and functions that will
make the performance better because these are precompiled. The
prepareCall() method of Connection interface returns the instance of
CallableStatement.
Classes:
DriverManager: The DriverManager class acts as an interface
between the user and drivers. It keeps track of the drivers that are
available and handles establishing a connection between a database
and the appropriate driver. It contains several methods to keep the
interaction between the user and drivers.
Blob: Blob stands for the binary large object. It represents a collection
of binary data stored as a single entity in the database management
system.
Clob: Clob stands for Character large object. It is a data type that is
used by various database management systems to store character
files. It is similar to Blob except for the difference that BLOB represent
binary data such as images, audio and video files, etc. whereas Clob
represents character stream data such as character files, etc.
SQLException It is an Exception class which provides information on
database access errors.
5) What are the JDBC statements?
In JDBC, Statements are used to send SQL commands to the database and
receive data from the database. There are various methods provided by
JDBC statements such as execute(), executeUpdate(), executeQuery, etc.
which helps you to interact with the database.
There is three type of JDBC statements given in the following table.
Statements Explanation
Statement Statement is the factory for resultset. It is used for general
purpose access to the database. It executes a static SQL
query at runtime.
PreparedSta The PreparedStatement is used when we need to provide
tement input parameters to the query at runtime.
CallableStat CallableStatement is used when we need to access the
ement database stored procedures. It can also accept runtime
parameters.
6) What is the return type of Class.forName() method?
The Class.forName() method returns the object of java.lang.Class object.
7) What are the differences between Statement and
PreparedStatement interface?
Statement PreparedStatement
The Statement interface provides The PreparedStatement
methods to execute queries with the interface is a subinterface of
database. The statement interface is a Statement. It is used to
factory of ResultSet; i.e., it provides the execute the parameterized
factory method to get the object of query.
ResultSet.
In the case of Statement, the query is In the case of
compiled each time we run the program. PreparedStatement, the query
is compiled only once.
The Statement is mainly used in the case PreparedStatement is used
when we need to run the static query at when we need to provide input
runtime. parameters to the query at
runtime.
More details.
8) How can we set null value in JDBC PreparedStatement?
By using setNull() method of PreparedStatement interface, we can set the
null value to an index. The syntax of the method is given below.
377. void setNull(int parameterIndex, int sqlType) throws
SQLException
378.
9) What are the benefits of PreparedStatement over Statement?
The benefits of using PreparedStatement over Statement interface is given
below.
The PreparedStatement performs faster as compare to Statement
because the Statement needs to be compiled everytime we run the
code whereas the PreparedStatement compiled once and then execute
only on runtime.
PreparedStatement can execute Parameterized query whereas
Statement can only run static queries.
The query used in PreparedStatement is appeared to be similar every
time. Therefore, the database can reuse the previous access plan
whereas, Statement inline the parameters into the String, therefore,
the query doesn't appear to be same everytime which prevents cache
reusage.
10) What are the differences between execute, executeQuery, and
executeUpdate?
execute executeQuery executeUpdate
The execute method can The executeQuery The executeUpdate
be used for any SQL method can be method can be used to
statements(Select and used only with the update/delete/insert
Update both). select statement. operations in the
database.
The execute method The The executeUpdate()
returns a boolean type executeQuery() method returns an
value where true indicates method returns a integer value
that the ResultSet s ResultSet object representing the number
returned which can later which contains the of records affected
be extracted and false data retrieved by where 0 indicates that
indicates that the integer the select query returns nothing.
or void value is returned. statement.
11) What are the different types of ResultSet?
ResultSet is categorized by the direction of the reading head and sensitivity
or insensitivity of the result provided by it. There are three general types of
ResultSet.
Type Description
ResultSet.TYPE_Forward_ The cursor can move in the forward direction
ONLY only.
ResultSet.TYPE_SCROLL_I The cursor can move in both the direction
NSENSITIVE (forward and backward). The ResultSet is not
sensitive to the changes made by the others
to the database.
ResultSet.TYPE_SCROLL_S The cursor can move in both the direction. The
ENSITIVE ResultSet is sensitive to the changes made by
the others to the database.
12) What are the differences between ResultSet and RowSet?
ResultSet RowSet
ResultSet cannot be RowSet is disconnected from the database and can
serialized as it be serialized.
maintains the
connection with the
database.
ResultSet object is ResultSet Object is a JavaBean object.
not a JavaBean object
ResultSet is returned Rowset Interface extends ResultSet Interface and
by the returned by calling the
executeQuery() RowSetProvider.newFactory().createJdbcRowSet()
method of Statement method.
Interface.
ResultSet object is RowSet object is scrollable and updatable by
non-scrollable and default.
non-updatable by
default.
13) How can we execute stored procedures using
CallableStatement?
Following are the steps to create and execute stored procedures. Here, we
are creating a table user420 by using a stored procedure and inserting
values into it.
Create the procedure in the database.
To call the stored procedure, you need to create it in the database. Here, we
are assuming that the stored procedure looks like this.
a. create or replace procedure "INSERTR"
b. (id IN NUMBER,
c. name IN VARCHAR2)
d. is
e. begin
f. insert into user420 values(id,name);
g. end;
h. /
The table structure is given below:
i. create table user420(id number(10), name varchar2(200));
Establish a network connection.
j. Class.forName("oracle.jdbc.driver.OracleDriver");
k. Connection con=DriverManager.getConnection(
l. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Create the Object of CallableStatement.
m. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
Provide the values and execute the query by using the
following syntax.
n. stmt.setInt(1,1011);
o. stmt.setString(2,"Amit");
p. stmt.execute();
Check the database; the values will be found there. However,
the complete code will look like the following.
q. import java.sql.*;
r. public class Proc {
s. public static void main(String[] args) throws Exception{
t.
u. Class.forName("oracle.jdbc.driver.OracleDriver");
v. Connection con=DriverManager.getConnection(
w. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
x.
y. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
z. stmt.setInt(1,1011);
aa. stmt.setString(2,"Amit");
bb. stmt.execute();
cc.
dd. System.out.println("success");
ee. }
ff. }
14) What is the role of the JDBC DriverManager class?
The DriverManager class acts as an interface between user and drivers. It
keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. The
DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver().
More details.
15) What are the functions of the JDBC Connection interface?
The Connection interface maintains a session with the database. It can be
used for transaction management. It provides factory methods that return
the instance of Statement, PreparedStatement, CallableStatement, and
DatabaseMetaData.
More details.
16) What does the JDBC ResultSet interface?
The ResultSet object represents a row of a table. It can be used to change
the cursor pointer and get the information from the database. By default,
ResultSet object can move in the forward direction only and is not updatable.
However, we can make this object to move the forward and backward
direction by passing either TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE in createStatement(int, int) method.
More details.
17) What does the JDBC ResultSetMetaData interface?
The ResultSetMetaData interface returns the information of table such as the
total number of columns, column name, column type, etc.
More details.
18) What does the JDBC DatabaseMetaData interface?
The DatabaseMetaData interface returns the information of the database
such as username, driver name, driver version, number of tables, number of
views, etc. Consider the following example.
379. import java.sql.*;
380. class Dbmd{
381. public static void main(String args[]){
382. try{
383. Class.forName("oracle.jdbc.driver.OracleDriver");
384.
385. Connection con=DriverManager.getConnection(
386. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
387. DatabaseMetaData dbmd=con.getMetaData();
388.
389. System.out.println("Driver Name: "+dbmd.getDriverName());
390. System.out.println("Driver Version: "+dbmd.getDriverVersion());
391. System.out.println("UserName: "+dbmd.getUserName());
392. System.out.println("Database Product Name:
"+dbmd.getDatabaseProductName());
393. System.out.println("Database Product Version:
"+dbmd.getDatabaseProductVersion());
394.
395. con.close();
396. }catch(Exception e){ System.out.println(e);}
397. }
398. }
Output
Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
More details.
19) Which interface is responsible for transaction management in
JDBC?
The Connection interface provides methods for transaction management
such as commit(), rollback() etc.
More details.
20) What is batch processing and how to perform batch processing
in JDBC?
By using the batch processing technique in JDBC, we can execute multiple
queries. It makes the performance fast. The java.sql.Statement and
java.sql.PreparedStatement interfaces provide methods for batch processing.
The batch processing in JDBC requires the following steps.
Load the driver class
Create Connection
Create Statement
Add query in the batch
Execute the Batch
Close Connection
ADVERTISEMENT
ADVERTISEMENT
Consider the following example to perform batch processing using the
Statement interface.
399. import java.sql.*;
400. class FetchRecords{
401. public static void main(String args[])throws Exception{
402. Class.forName("oracle.jdbc.driver.OracleDriver");
403. Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:x
e","system","oracle");
404. con.setAutoCommit(false);
405.
406. Statement stmt=con.createStatement();
407. stmt.addBatch("insert into user420 values(190,'abhi',40000)");
408. stmt.addBatch("insert into user420 values(191,'umesh',50000)");
409.
410. stmt.executeBatch();//executing the batch
411.
412. con.commit();
413. con.close();
414. }}
More details.
21) What are CLOB and BLOB data types in JDBC?
BLOB: Blob can be defined as the variable-length, binary large object which
is used to hold the group of Binary data such as voice, images, and mixed
media. It can hold up to 2GB data on MySQL database and 128 GB on Oracle
database. BLOB is supported by many databases such as MySQL, Oracle, and
DB2 to store the binary data (images, video, audio, and mixed media).
CLOB: Clob can be defined as the variable-length, character-large object
which is used to hold the character-based data such as files in many
databases. It can hold up to 2 GB on MySQL database, and 128 GB on Oracle
Database. A CLOB is considered as a character string.
22) What are the different types of lockings in JDBC?
A lock is a certain type of software mechanism by using which, we can
restrict other users from using the data resource. There are four type of locks
given in JDBC that are described below.
Row and Key Locks: These type of locks are used when we update
the rows.
Page Locks: These type of locks are applied to a page. They are used
in the case, where a transaction remains in the process and is being
updated, deleting, or inserting some data in a row of the table. The
database server locks the entire page that contains the row. The page
lock can be applied once by the database server.
Table locks: Table locks are applied to the table. It can be applied in
two ways, i.e., shared and exclusive. Shared lock lets the other
transactions to read the table but not update it. However, The
exclusive lock prevents others from reading and writing the table.
Database locks: The Database lock is used to prevent the read and
update access from other transactions when the database is open.
23) How can we store and retrieve images from the database?
By using the PreparedStatement interface, we can store and retrieve images.
Create a table which contains two columns namely NAME and PHOTO.
415. CREATE TABLE "IMGTABLE"
416. ( "NAME" VARCHAR2(4000),
417. "PHOTO" BLOB
418. )
Consider the following example to store the image in the database.
419. import java.sql.*;
420. import java.io.*;
421. public class InsertImage {
422. public static void main(String[] args) {
423. try{
424. Class.forName("oracle.jdbc.driver.OracleDriver");
425. Connection con=DriverManager.getConnection(
426. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
427.
428. PreparedStatement ps=con.prepareStatement("insert into
imgtable values(?,?)");
429. ps.setString(1,"sonoo");
430.
431. FileInputStream fin=new FileInputStream("d:\\g.jpg");
432. ps.setBinaryStream(2,fin,fin.available());
433. int i=ps.executeUpdate();
434. System.out.println(i+" records affected");
435.
436. con.close();
437. }catch (Exception e) {e.printStackTrace();}
438. }
439. }
ADVERTISEMENT
Consider the following example to retrieve the image from the table.
440. import java.sql.*;
441. import java.io.*;
442. public class RetrieveImage {
443. public static void main(String[] args) {
444. try{
445. Class.forName("oracle.jdbc.driver.OracleDriver");
446. Connection con=DriverManager.getConnection(
447. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
448.
449. PreparedStatement ps=con.prepareStatement("select * from
imgtable");
450. ResultSet rs=ps.executeQuery();
451. if(rs.next()){//now on 1st row
452.
453. Blob b=rs.getBlob(2);//2 means 2nd column data
454. byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
455.
456. FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
457. fout.write(barr);
458.
459. fout.close();
460. }//end of if
461. System.out.println("ok");
462.
463. con.close();
464. }catch (Exception e) {e.printStackTrace(); }
465. }
466. }
More details.
24) How can we store the file in the Oracle database?
The setCharacterStream() method of PreparedStatement interface is used to
set character information into the parameterIndex. For storing the file into
the database, CLOB (Character Large Object) datatype is used in the table.
For example:
467. CREATE TABLE "FILETABLE"
468. ( "ID" NUMBER,
469. "NAME" CLOB
470. )
Java Code
471. import java.io.*;
472. import java.sql.*;
473.
474. public class StoreFile {
475. public static void main(String[] args) {
476. try{
477. Class.forName("oracle.jdbc.driver.OracleDriver");
478. Connection con=DriverManager.getConnection(
479. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
480.
481. PreparedStatement ps=con.prepareStatement(
482. "insert into filetable values(?,?)");
483.
484. File f=new File("d:\\myfile.txt");
485. FileReader fr=new FileReader(f);
486.
487. ps.setInt(1,101);
488. ps.setCharacterStream(2,fr,(int)f.length());
489. int i=ps.executeUpdate();
490. System.out.println(i+" records affected");
491.
492. con.close();
493.
494. }catch (Exception e) {e.printStackTrace();}
495. }
496. }
25) How can we retrieve the file in the Oracle database?
The getClob() method of PreparedStatement is used to get file information
from the database. Let's see the table structure of the example to retrieve
the file.
497. CREATE TABLE "FILETABLE"
498. ( "ID" NUMBER,
499. "NAME" CLOB
500. )
The example to retrieve the file from the Oracle database is given below.
501. import java.io.*;
502. import java.sql.*;
503.
504. public class RetrieveFile {
505. public static void main(String[] args) {
506. try{
507. Class.forName("oracle.jdbc.driver.OracleDriver");
508. Connection con=DriverManager.getConnection(
509. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
510.
511. PreparedStatement ps=con.prepareStatement("select * from
filetable");
512. ResultSet rs=ps.executeQuery();
513. rs.next();//now on 1st row
514.
515. Clob c=rs.getClob(2);
516. Reader r=c.getCharacterStream();
517.
518. FileWriter fw=new FileWriter("d:\\retrivefile.txt");
519.
520. int i;
521. while((i=r.read())!=-1)
522. fw.write((char)i);
523.
524. fw.close();
525. con.close();
526.
527. System.out.println("success");
528. }catch (Exception e) {e.printStackTrace(); }
529. }
530. }
26) What are the differences between stored procedure and
functions?
The differences between stored procedures and functions are given below:
Stored Procedure Function
Is used to perform business logic. Is used to perform the calculation.
Must not have the return type. Must have the return type.
May return 0 or more values. May return only one value.
The procedure supports input and The function supports only input
output parameters. parameter.
Exception handling using try/catch Exception handling using try/catch
block can be used in stored can't be used in user-defined
procedures. functions.
27) How can we maintain the integrity of a database by using
JDBC?
To maintain the integrity of a database, we need to ensure the ACID
properties. ACID properties mean Atomicity, Consistency, Isolation, and
durability. In JDBC, Connection interface provides methods like
setAutoCommit(), commit(), and rollback() which can be used to manage
transaction. Let's see an example of transaction management in JDBC.
531. import java.sql.*;
532. class FetchRecords{
533. public static void main(String args[])throws Exception{
534. Class.forName("oracle.jdbc.driver.OracleDriver");
535. Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:x
e","system","oracle");
536. con.setAutoCommit(false);
537.
538. Statement stmt=con.createStatement();
539. stmt.executeUpdate("insert into user420
values(190,'abhi',40000)");
540. stmt.executeUpdate("insert into user420
values(191,'umesh',50000)");
541.
542. con.commit();
543. con.close();
544. }}
28) What is the JDBC Rowset?
JDBC Rowset is the wrapper of ResultSet. It holds tabular data like ResultSet,
but it is easy and flexible to use. The implementation classes of RowSet
interface are as follows:
JdbcRowSet
CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet
29) What is the major difference between java.util.Date and
java.sql.Date data type?
The major difference between java.util.Date and java.sql.Date is that,
java.sql.Date represents date without time information whereas,
java.util.Date represents both date and time information.
30) What does JDBC setMaxRows method do?
The setMaxRows(int i) method limits the number of rows the database can
return by using the query. This can also be done within the query as we can
use the limit cause in MySQL.
You
what is oops in java
In Java, Object-Oriented Programming (OOP) is a programming paradigm that
revolves around the concept of "objects." Objects are instances of classes,
and classes define the blueprint or template for creating objects. The key
principles of OOP in Java are encapsulation, inheritance, polymorphism, and
abstraction. Here's a brief explanation of these concepts:
1. **Encapsulation:** Encapsulation involves bundling the data (attributes)
and the methods (functions) that operate on the data into a single unit called
a class. It helps in hiding the internal details of an object and exposing only
what is necessary.
Example:
```java
public class Car {
private String model;
private int year;
// Constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
// Getter methods
public String getModel() {
return model;
}
public int getYear() {
return year;
}
}
```
2. **Inheritance:** Inheritance is a mechanism that allows a class (subclass
or derived class) to inherit properties and behaviors from another class
(superclass or base class). It promotes code reusability and establishes an
"is-a" relationship between classes.
Example:
```java
// Superclass
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
// Subclass
public class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
```
3. **Polymorphism:** Polymorphism allows objects to be treated as instances
of their parent class, enabling the use of a single interface to represent
different types. There are two types of polymorphism in Java: compile-time
(method overloading) and runtime (method overriding).
Example:
```java
// Method Overloading (Compile-time polymorphism)
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
```
```java
// Method Overriding (Runtime polymorphism)
public class Animal {
public void makeSound() {
System.out.println("Some generic sound");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
```
4. **Abstraction:** Abstraction involves simplifying complex systems by
modeling classes based on essential characteristics. Abstract classes and
interfaces are used to achieve abstraction in Java.
Example:
```java
// Abstract class
public abstract class Shape {
abstract void draw();
}
// Concrete class
public class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
```
These OOP principles in Java provide a way to structure code, enhance code
organization, and promote code reuse. They contribute to the creation of
modular, maintainable, and scalable software systems.