In this blog we will be listing the core java interview questions along with the answers. This blog will prepare you for the frequently asked core java interview questions . The topics covered are:
- JDK Directory
- OOPs Concepts
- Functions
- Exception Handling
- Threads
- I/O Stream
Watch our video on Java 8 Essentials to learn java.
1) What is 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.
JVMs are available for many hardware and software platforms (so JVM is platform dependent).
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM and physically exists.
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.
2)How many types of memory areas are allocated by JVM?
- Class(Method) Area
- Heap
- Stack
- Program Counter Register
- Native Method Stack
3) What is JIT compiler?
Just-In-Time(JIT) compiler. It is used to improve the performance. JIT compiles parts of the byte code 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.
4) What is platform?
A platform is basically the hardware or software environment in which a program runs. There are two types of platforms : software-based and hardware-based. Java provides software-based platform.
5) What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in the sense that it’s a software-based platform that runs on top of other hardware-based platforms. It has two components:
- Runtime Environment
- API(Application Programming Interface)
6) What gives Java its ‘write once and run anywhere’ nature?
The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.
7) What is classloader?
The classloader is a subsystem of JVM that is used to load classes and interfaces. There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.
8) Is Empty .java file name a valid source file name?
Yes, save your java file by .java and compile it by javac .java then run by java yourclassname.
Let’s take a simple example:
//save by .java only
class A{
public static void main(String args[]){
System.out.println(“Hello java”);
}
}
//compile by javac .java
//run by java A
compile it by javac .java run it by java A
9) Is delete,next,main,exit or null keyword in java?
No.
10) If we don’t provide any arguments on the command line, then the String array of Main method will be empty or null?
It is empty. But not null.
11) What if we write static public void instead of public static void?
Program compiles and runs properly.
12) What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.
13) What is difference between object oriented programming language and object based programming language?
Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.
14) What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java.
15) What is constructor?
Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
16) Rules for creating a constructor
There are basically two rules defined for the constructor. Constructor name must be same as its class name and it should have no explicit return type.
17) What are the types of java constructors?
There are two types of constructors:
- Default constructor (no-arg constructor)
- Parameterized constructor
18) What is Java Default Constructor? Explain with syntax and example.
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. |
class Bike1{
Bike1(){System.out.println(“Bike is created”);}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class then the compiler automatically creates a default constructor.
19) What is the purpose of default constructor?
Default constructor provides the default values to the object like 0, null etc. depending on the type.
20) What is Java parameterized constructor? Explain with syntax and example.
A constructor that have parameters is known as parameterized constructor. Parameterized constructor is used to provide different values to the distinct objects.
Example:
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. |
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+” “+name);}
ublic static void main(String args[]){
Student4 s1 = new Student4(111,”Karan”);
Student4 s2 = new Student4(222,”Aryan”);
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
21) What is Constructor Overloading in Java?
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
Example:
class Student5{ int id; String name; int age; Student5(int i,String n){ id = i; name = n; } Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+” “+name+” “+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,”Karan”); Student5 s2 = new Student5(222,”Aryan”,25); s1.display(); s2.display(); } } Output: 111 Karan 0 222 Aryan 25 |
22) Difference between constructor and method in java
Java Constructor | Java Method |
---|---|
Constructor is used to initialize the state of an object. | Method is used to expose behaviour of an object. |
Constructor must not have return type. | Method must have return type. |
Constructor is invoked implicitly. | Method is invoked explicitly. |
The java compiler provides a default constructor if you don’t have any constructor. | Method is not provided by compiler in any case. |
Constructor name must be same as the class name. | Method name may or may not be same as class name. |
23) Is there a copy constructor in java?
There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in java. They are:
- using constructor
- by assigning the values of one object into another
- using clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
class Student6{ int id; String name; Student6(int i,String n){ id = i; name = n; } Student6(Student6 s){ id = s.id; name =s.name; } void display(){System.out.println(id+” “+name);} public static void main(String args[]){ Student6 s1 = new Student6(111,”Karan”); Student6 s2 = new Student6(s1); s1.display(); s2.display(); } } Output: 111 Karan 111 Karan |
24) Does constructor return any value?
Yes, that is current class instance (You cannot use return type yet it returns a value)
25) Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method.
26) What is static variable?
If you declare any variable as static, it is known static variable. Static variable is used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc. It gets memory only once in class area at the time of class loading.
27) What is static keyword in java?
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
- variable (also known as class variable)
- method (also known as class method)
- block
- nested class
28) What is the advantage of static variable?
It makes your program memory efficient (i.e it saves memory).
29) What is Java Static Method?
If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than object of a class and it can be invoked without the need for creating an instance of a class. Static method can access static data member and can change the value of it.
Example: Program of changing the common property of all objects(static field).
class Student9{ int rollno; String name; static String college = “ITS”; static void change(){ college = “BBDIT”; } Student9(int r, String n){ rollno = r; name = n; } void display (){System.out.println(rollno+” “+name+” “+college);} public static void main(String args[]){ Student9.change(); Student9 s1 = new Student9 (111,”Karan”); Student9 s2 = new Student9 (222,”Aryan”); Student9 s3 = new Student9 (333,”Sonoo”); s1.display(); s2.display(); s3.display(); } } Output: 111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT |
30) What are the restrictions for static method?
There are two main restrictions for the static method. They are:
- The static method can not use non static data member or call non-static method directly.
- super cannot be used in static context
class A{ int a=40;//non static public static void main(String args[]){ System.out.println(a); } } Output: Compile Time Error |
31) Why java main method is static?
Because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.
32) What is the purpose of Java static block?
Java static block is used to initialize the static data member and is executed before main method at the time of classloading.
Example:
class A2{ static{System.out.println(“static block is invoked”);} public static void main(String args[]){ System.out.println(“Hello main”); } } Output: static block is invoked |
33) Can we execute a program without main() method?
Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
class A3{ static{ System.out.println(“static block is invoked”); System.exit(0); } } Output: static block is invoked (if not JDK7) In JDK7 and above, output will be: Output: Error: Main method not found in class A3, please define the main method as: public static void main(String[] args) |
34) What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error “NoSuchMethodError”.
35) What is difference between static (class) method and instance method?
Static or Class Method | Instance Method |
---|---|
A method i.e. declared as static is known as static method. | A method i.e. not declared as static is known as instance method. |
Object is not required to call static method. | Object is required to call instance methods. |
Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly. | static and non-static variables both can be accessed in instance methods. |
For example: public static int cube(int n){ return n*n*n;} | For example: public void msg(){…}. |
36) What is “this” in java?
It is a keyword that that refers to the current object. There can be a lot of usage of java this keyword.
Usage of java this keyword:
- this keyword can be used to refer current class instance variable
- this() can be used to invoke current class constructor
- this keyword can be used to invoke current class method (implicitly)
- this can be passed as an argument in the method call and also in a constructor call
- this keyword can also be used to return the current class instance
37) Can the this keyword be used to refer current class instance variable?
The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.
Let’s understand the problem if we don’t use this keyword by the example given below:
class Student10{ int id; String name; student(int id,String name){ id = id; name = name; } void display(){System.out.println(id+” “+name);} public static void main(String args[]){ Student10 s1 = new Student10(111,”Karan”); Student10 s2 = new Student10(321,”Aryan”); s1.display(); s2.display(); } } Output: 0 null 0 null In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable. Solution of the above problem by this keyword: class Student11{ int id; String name; Student11(int id,String name){ this.id = id; this.name = name; } void display(){System.out.println(id+” “+name);} public static void main(String args[]){ Student11 s1 = new Student11(111,”Karan”); Student11 s2 = new Student11(222,”Aryan”); s1.display(); s2.display(); } } Output: 111 Karan 222 Aryan |
38) Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining.
Let’s see the example given below that displays the actual use of this keyword.
class Student14{ int id; String name; String city; Student14(int id,String name){ this.id = id; this.name = name; } Student14(int id,String name,String city){ this(id,name);//now no need to initialize id and name this.city=city; } void display(){System.out.println(id+” “+name+” “+city);} public static void main(String args[]){ Student14 e1 = new Student14(111,”karan”); Student14 e2 = new Student14(222,”Aryan”,”delhi”); e1.display(); e2.display(); } } Output: 111 Karan null 222 Aryan delhi Rule: Call to this() must be the first statement in constructor. class Student15{ int id; String name; Student15(){System.out.println(“default constructor is invoked”);} Student15(int id,String name){ id = id; name = name; this ();//must be the first statement } void display(){System.out.println(id+” “+name);} public static void main(String args[]){ Student15 e1 = new Student15(111,”karan”); Student15 e2 = new Student15(222,”Aryan”); e1.display(); e2.display(); } } Output: Compile Time Error |
39) Can the this keyword be used to invoke current class method (implicitly)?
You may invoke the method of the current class by using the this keyword because if you don’t use the this keyword, compiler automatically adds this keyword while invoking the method.
Let’s see the example:
class S{ void m(){ System.out.println(“method is invoked”); } void n(){ this.m();//no need because compiler does it for you. } void p(){ n();//complier will add this to invoke n() method as this.n() } public static void main(String args[]){ S s1 = new S(); s1.p(); } } Output: method is invoked |
40) Can this keyword be passed as an argument in the method?
The this keyword can be passed as an argument in the method and it is mainly used in the event handling. Let’s see the example:
class S2{ void m(S2 obj){ System.out.println(“method is invoked”); } void p(){ m(this); } public static void main(String args[]){ S2 s1 = new S2(); s1.p(); } } Output: method is invoked |
41) Can this keyword be passed as argument in the constructor call?
We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let’s see the example:
class B{ A4 obj; B(A4 obj){ this.obj=obj; } void display(){ System.out.println(obj.data);//using data member of A4 class } } class A4{ int data=10; A4(){ B b=new B(this); b.display(); } public static void main(String args[]){ A4 a=new A4(); } } Output:10 |
42) Can this keyword be used to return current class instance?
We can return the this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let’s see the example:
Syntax of this that can be returned as a statement return_type method_name(){ return this; } Example of this keyword that you return as a statement from the method class A{ A getA(){ return this; } void msg(){System.out.println(“Hello java”);} } class Test1{ public static void main(String args[]){ new A().getA().msg(); } } Output: Hello java |
43) What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behavior of another object of another class. It represents IS-A relationship and 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 parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Use of inheritance in java :
- For Method Overriding (so runtime polymorphism can be achieved).
- For Code Reusability.
Syntax of Java Inheritance:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class. In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.
44) Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
45) Why multiple inheritance is 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 same method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
class A{ void msg(){System.out.println(“Hello”);} } class B{ void msg(){System.out.println(“Welcome”);} } class C extends A,B{//suppose if it were Public Static void main(String args[]){ C obj=new C(); obj.msg();//Now which msg() method would be invoked? } } Compile Time Error |
46) Which class is the superclass for every class.
Object class.
47) What is composition?
Holding the reference of the other class within some other class is known as composition.
48) What is difference between aggregation and composition?
Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (composition).
49) Why Java does not support pointers?
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.
50) Can you use this() and super() both in a constructor?
No. Because super() or this() must be the first statement.
51) What is super in java?
The super keyword in java is a reference variable that is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Usage of java super keyword:
- used to refer immediate parent class instance variable.
- super() is used to invoke immediate parent class constructor.
- is used to invoke immediate parent class method.
52) What is object cloning?
The object cloning is used to create an exact copy of an object.
53) What is method overloading?
If a class have multiple methods by same name but different parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. So, we perform method overloading to figure out the program quickly.
54) What are the different ways to overload a method?
There are two ways to overload the method in java and those are:
- By changing number of arguments
- By changing the data type
55) Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let’s see how ambiguity may occur:
class Calculation3{ int sum(int a,int b){System.out.println(a+b);} double sum(int a,int b){System.out.println(a+b);} public static void main(String args[]){ Calculation3 obj=new Calculation3(); int result=obj.sum(20,20); //Compile Time Error } } int result=obj.sum(20,20); //Here how can java determine which sum() method should be called |
56) Can we overload main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let’s see the simple example:
class Overloading1{ public static void main(int a){ System.out.println(a); } public static void main(String args[]){ System.out.println(“main() method invoked”); main(10); } } Output: main() method invoked 10 |
57) What is method overriding?
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding:
- Method overriding is used to provide specific implementation of a method that is already provided by its super class.
- Method overriding is used for runtime polymorphism
Rules for Java Method Overriding:
- method must have same name as in the parent class
- method must have same parameter as in the parent class
- must be IS-A relationship (inheritance)
58) Why we cannot override static method?
It is because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.
59) Can we override java main method?
No, because main is a static method.
60) Difference between method Overloading and Method Overriding in java
Method Overloading | Method Overriding |
---|---|
Method overloading is used to increase the readability of the program. | Method overriding is used to provide the specific implementation of the method that is already provided by its super class. |
Method overloading is performed within a class. | Method overriding occurs in two classes that have IS-A relationship. |
In case of method overloading parameter must be different. | In case of method overriding parameter must be same. |
61) Can we override the overloaded method?
Yes, we can.
62) Can you have virtual functions in Java?
Yes, all functions in Java are virtual by default.
63) What is covariant return type?
Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type.
64) What is final variable?
If you make any variable as final then you cannot change the value of final variable.
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can’t be changed because final variable once assigned a value can never be changed.
class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }//end of class Output: Compile Time Error |
65) What is final method?
If you make any method as final, you cannot override it.
Example of final method:
class Bike{ final void run(){System.out.println(“running”);} } class Honda extends Bike{ void run(){System.out.println(“running safely with 100kmph”);} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Output: Compile Time Error |
66) What is final class?
If you make any class as final then you cannot extend it.
Example of final class:
final class Bike{} class Honda1 extends Bike{ void run(){System.out.println(“running safely with 100kmph”);} public static void main(String args[]){ Honda1 honda= new Honda(); honda.run(); } } Output: Compile Time Error |
67) Is final method inherited?
Yes, final method is inherited but you cannot override it.
For Example:
class Bike{ final void run(){System.out.println(“running…”);} } class Honda2 extends Bike{ public static void main(String args[]){ new Honda2().run(); } } Output: running… |
68) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable. If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialized only in constructor.
Example of blank final variable:
class Student{ int id; String name; final String PAN_CARD_NUMBER; … } Que) Can we initialize blank final variable? Yes, but only in constructor. For example: class Bike10{ final int speedlimit;//blank final variable Bike10(){ speedlimit=70; System.out.println(speedlimit); } public static void main(String args[]){ new Bike10(); } } Output: 70 |
69) What is a static blank final variable?
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
Example of static blank final variable:
class A{ static final int data;//static blank final variable static{ data=50;} public static void main(String args[]){ System.out.println(A.data); } } |
70) What is final parameter?
If you declare any parameter as final then you cannot change the value of it.
class Bike11{ int cube(final int n){ n=n+2;//can’t be changed as n is final n*n*n; } public static void main(String args[]){ Bike11 b=new Bike11(); b.cube(5); } } Output: Compile Time Error |
71) Can we declare a constructor final?
No, because constructor is never inherited.
72) Can final method be overridden?
No, final methods can’t be overridden.
73) Can final class be inherited?
Final class can’t be inherited.
74) Can we initialize blank final variable?
Yes, only in constructor if it is non-static. If it is static blank final variable then it can be initialized only in the static block.
75) Can you declare the main method as final?
Yes, such as, public static final void main(String[] args){}.
76) What is polymorphism?
Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word “poly” means many and “morphs” means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
77) 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 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.
78) What is upcasting?
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
For example:
class A{} class B extends A{} A a=new B();//upcasting |
79) Can you achieve Runtime Polymorphism by data members?
No
80) What is the difference between static binding and dynamic binding?
In case of static binding type of object is determined at compile time whereas in dynamic binding type of object is determined at runtime.
81) What is Abstraction?
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don’t know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction:
There are two ways to achieve abstraction in java
- Abstract class (0 to 100%)
- Interface (100%)
82) What is abstract class?
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
Example abstract class:
abstract class A{}
83) What is abstract method?
A method that is declared as abstract and does not have implementation is known as abstract method.
Example:
abstract void printStatus();//no body and abstract
84) What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.
85) Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
86) Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can’t override final method.
87) Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
88) What is an interface?
An interface in java is a blueprint of a class. It has static constants and abstract methods only. The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.
89) Why use Java interface?
There are mainly three reasons to use interface and they are:
- It is used to achieve fully abstraction.
- By interface, we can support the functionality of multiple inheritance.
- It can be used to achieve loose coupling.
90) Multiple inheritance is not supported through class in java but it is possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class.
For example:
interface Printable{ void print(); } interface Showable{ void print(); } class testinterface1 implements Printable,Showable{ public void print(){System.out.println(“Hello”);} public static void main(String args[]){ testinterface1 obj = new testinterface1(); obj.print(); } } Output: Hello As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class A, so there is no ambiguity. |
91) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
Serializable interface is written as:
public interface Serializable{ }
92) Can you declare an interface method static?
No, because methods of an interface is abstract by default, and static and abstract keywords can’t be used together.
93) Can an Interface be final?
No, because its implementation is provided by another class.
94) What is difference between abstract class and interface?
Abstract Class | Interface |
---|---|
Abstract class can have abstract and non-abstract methods. | Interface can have only abstract methods. |
Abstract class doesn’t support multiple inheritance. | Interface supports multiple inheritance. |
Abstract class can have final, non-final, static and non-static variables. | Interface has only static and final variables. |
Abstract class can have static methods, main method and constructor. | Interface can’t have static methods, main method or constructor. |
Abstract class can provide the implementation of interface. | Interface can’t provide the implementation of abstract class. |
The abstract keyword is used to declare abstract class. | The interface keyword is used to declare interface. |
Example: public class Shape{ public abstract void draw(); } | Example: public interface Drawable{ void draw(); } |
95) Can we define private and protected modifiers for variables in interfaces?
No, they are implicitly public.
96) 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.
97) What is Java Package?
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
- Java package is used to categorize the classes and interfaces so that they can be easily maintained.
- It provides access protection.
- Java package removes naming collision.
98) How to run java package program?
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
99) How to access package from another package?
There are three ways to access the package from outside the package.
- import package.*;
- import package.classname;
- fully qualified name
100) What is a subpackage?
Package inside the package is called the subpackage. It should be created to categorize the package further.
Let’s take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.
Example:
class Simple{ public static void main(String args[]){ System.out.println(“Hello subpackage”); } } To Compile: javac -d . Simple.java To Run: java com.javatpoint.core.Simple Output: Hello subpackage |
101) What happens if you import package.classname ?
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname:
//save by A.java package pack; public class A{ public void msg(){System.out.println(“Hello”);} } //save by B.java package mypack; import pack.A; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } Output: Hello |
102) What is the purpose of using qualified name?
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
Example of package by import fully qualified name
//save by A.java package pack; public class A{ public void msg(){System.out.println(“Hello”);} } //save by B.java package mypack; class B{ public static void main(String args[]){ pack.A obj = new pack.A();//using fully qualified name obj.msg(); } } Output: Hello |
103) What are the ways to load the class files or jar files?
Temporary
- By setting the classpath in the command prompt
- By -classpath switch
Permanent
- By setting the classpath in the environment variables
- By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.
104) How to put two public classes in a package?
If you want to put two public classes in a package, have two java source files containing one public class, but keep the package name same. For example:
//save as A.java package javatpoint; public class A{} //save as B.java package javatpoint; public class B{} |
105) Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.
106) Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. But the JVM will internally load the class only once no matter how many times you import the same class.
107) What is static import ?
By static import, we can access the static members of a class directly, there is no to qualify it with the class name.
The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.
Advantage of static import:
Less coding is required if you have access any static member of a class often.
Disadvantage of static import:
If you overuse the static import feature, it makes the program unreadable and unmaintainable.
108) What is the difference between import and static import?
The import allows the java programmer to access classes of a package without package qualification whereas the static import feature allows to access the static members of a class without the class qualification. The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.
109) What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors. It is mainly used to handle checked exceptions.
110) What is difference between Checked Exception and Unchecked Exception?
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.
Unchecked Exception:
The classes that extend RuntimeException are known as unchecked exceptions.
Example: ArithmeticException, NullPointerException etc. Unchecked exceptions are not checked at compile-time.
111) What is the base class for Error and Exception?
Throwable.
112) 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. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
113) What is finally block?
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
The block is always executed whether exception is handled or not. Java finally block must be followed by try or catch block.
Note: If you don’t handle exception, before terminating the program, JVM executes finally block(if any).
114) Why use java finally?
Finally block in java can be used to put “cleanup” code such as closing a file, closing connection etc. Let’s see the different cases where java finally block can be used.
Case 1
Let’s see the java finally example where exception doesn’t occur.
class TestFinallyBlock{ public static void main(String args[]){ try{ int data=25/5; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println(“finally block is always executed”);} System.out.println(“rest of the code…”); } } Output: 5 finally block is always executed rest of the code… |
Case 2
Let’s see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println(“finally block is always executed”);} System.out.println(“rest of the code…”); } } Output: finally block is always executed Exception in thread main java.lang.ArithmeticException:/ by zero |
Case 3
Let’s see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(ArithmeticException e){System.out.println(e);} finally{System.out.println(“finally block is always executed”);} System.out.println(“rest of the code…”); } } Output: Exception in thread main java.lang.ArithmeticException:/ by zero finally block is always executed rest of the code… |
115) Can finally block be used without catch?
Yes, by try block. finally must be followed by either try or catch.
116) 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).
117) What is difference between throw and throws?
throw Keyword | throws Keyword |
---|---|
throw is used to explicitly throw an exception. | throws is used to declare an exception. |
checked exceptions can not be propagated with throw only. | checked exception can be propagated with throws. |
throw is followed by an instance. | throws is followed by class. |
throw is used within the method. | throws is used with the method signature. |
You cannot throw multiple exception | You can declare multiple exception e.g. public void method()throws IOException,SQLException. |
118) Can an exception be rethrown?
Yes
119) Can subclass overriding method declare an exception if parent class method doesn’t throw an exception ?
Yes but only unchecked exception not checked.
120) What are the rules for Exception Handling with Method Overriding in Java?
There are many rules if we talk about method overriding with exception handling. The Rules are as follows:
If the superclass method does not declare an exception
Rule 1: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
1) if the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception import java.io.*; class Parent{ void msg(){System.out.println(“parent”);} } class TestExceptionChild extends Parent{ void msg()throws IOException{ System.out.println(“TestExceptionChild”); } public static void main(String args[]){ Parent p=new TestExceptionChild(); p.msg(); } } Output: Compile Time Error 2) If the superclass method does not declare an exception, subclass overridden method can declare the unchecked exception import java.io.*; class Parent{ void msg(){System.out.println(“parent”);} } class TestExceptionChild1 extends Parent{ void msg()throws ArithmeticException{ System.out.println(“child”); } public static void main(String args[]){ Parent p=new TestExceptionChild1(); p.msg(); } } Output: child |
If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
Example in case subclass overridden method declares parent exception import java.io.*; class Parent{ void msg()throws ArithmeticException{System.out.println(“parent”);} } class TestExceptionChild2 extends Parent{ void msg()throws Exception{System.out.println(“child”);} public static void main(String args[]){ Parent p=new TestExceptionChild2(); try{ p.msg(); }catch(Exception e){} } } Output: Compile Time Error Example in case subclass overridden method declares same exception import java.io.*; class Parent{ void msg()throws Exception{System.out.println(“parent”);} } class TestExceptionChild3 extends Parent{ void msg()throws Exception{System.out.println(“child”);} public static void main(String args[]){ Parent p=new TestExceptionChild3(); try{ p.msg(); }catch(Exception e){} } } Output: child Example in case subclass overridden method declares subclass exception import java.io.*; class Parent{ void msg()throws Exception{System.out.println(“parent”);} } class TestExceptionChild4 extends Parent{ void msg()throws ArithmeticException{System.out.println(“child”);} public static void main(String args[]){ Parent p=new TestExceptionChild4(); try{ p.msg(); }catch(Exception e){} } } Output: child Example in case subclass overridden method declares no exception import java.io.*; class Parent{ void msg()throws Exception{System.out.println(“parent”);} } class TestExceptionChild5 extends Parent{ void msg(){System.out.println(“child”);} public static void main(String args[]){ Parent p=new TestExceptionChild5(); try{ p.msg(); }catch(Exception e){} } } Output: child |
121) What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception propagation.
122) Why string objects are immutable in java?
Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object “sachin”. If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
123) What is the meaning of immutable in terms of String?
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value can’t be changed.
124) How many ways we can create the string object?
There are two ways to create the string object, by string literal and by new keyword.
125) Why java uses the concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
126) What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.
127) What is the difference between StringBuffer and StringBuilder ?
StringBuffer is synchronized whereas StringBuilder is not synchronized.
128) What is the purpose of toString() method in java ?
The toString() method returns the string representation of any 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. depends on your implementation.
129) What is nested class?
A class which is declared inside another class is known as nested class. There are 4 types of nested class member inner class, local inner class, anonymous inner class and static nested class.
130) Is there any difference between nested classes and inner classes?
Yes, inner classes are non-static nested classes i.e. inner classes are the part of nested classes.
131) Can we access the non-final local variable, inside the local inner class?
No, local variable must be constant if you want to access it in local inner class.
132) What is nested interface ?
Any interface i.e. declared inside the interface or class, is known as nested interface. It is static by default.
133) Can a class have an interface?
Yes, it is known as nested interface.
134) Can an Interface have a class?
Yes, they are static implicitly.
135) What is Garbage Collection in Java?
In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically.
Advantage of Garbage Collection:
It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector so we don’t need to make extra efforts.
136) How can an object be unreferenced?
There are many ways for an object to be unreferenced. By:
- nulling the reference
- assigning a reference to another
- anonymous object
137) What is finalize() method?
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in System class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).
138) What is gc() method?
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.
139) Can an unreferenced objects be referenced again?
Yes
140) What is difference between final, finally and finalize?
final: final is a keyword, final can be variable, method or class. You can’t change the value of final variable, can’t override final method, can’t inherit final class. |
finally: finally block is used in exception handling. finally block is always executed. |
finalize(): finalize() method is used in garbage collection.finalize() method is invoked just before the object is garbage collected. The finalize() method can be used to perform any cleanup processing. |
141) What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
142) How will you invoke any external process in Java?
By Runtime.getRuntime().exec(?) method.
143) What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
144) What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
145) What is serialization?
Serialization is a process of writing the state of an object into a byte stream. It is mainly used to travel object’s state on the network.
146) What is Deserialization?
Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.
147) What is transient keyword?
If you define any data member as transient, it will not be serialized.
148) What is Externalizable?
Externalizable interface is used to write the state of an object into a byte stream in compressed format. It is not a marker interface.
149) What is the difference between Serializable and Externalizable interface?
Serializable is a marker interface but Externalizable is not a marker interface. When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serialization process. When you use Externalizable interface, you have a complete control over your class’s serialization process.
150) What is reflection?
Reflection is the process of examining or modifying the runtime behavior of a class at runtime. It is used in IDE, Debuggers etc.
151) Can you access the private method from outside the class?
Yes, by changing the runtime behavior of a class if the class is not secured.
152) What are wrapper classes?
Wrapper classes are classes that allow primitive types to be accessed as objects.
153) What is a native method?
A native method is a method that is implemented in a language other than Java.
154) What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
155) What is singleton class?
Singleton class means that any given time only one instance of the class is present, in one JVM.
156) Which containers use a border layout as their default layout?
The Window, Frame and Dialog classes use a border layout as their default layout.
157) Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
158) What are peerless components?
The peerless components are called light weight components.
159) What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
160) What is a lightweight component?
Lightweight components are the one which doesn’t go with the native call to obtain the graphical units. They share their parent component graphical units to render them. For example, Swing components.
161) What is a heavyweight component?
For every paint call, there will be a native call to get the graphical units. For Example, AWT.
162) What is an applet?
An applet is a small java program that runs inside the browser and generates dynamic contents.
163) Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
164) What is Locale?
A Locale object represents a specific geographical, political, or cultural region.
165) How will you load a specific locale?
By ResourceBundle.getBundle(?) method.
166) What is a JavaBean?
JavaBean are reusable software components written in the Java programming language, designed to be manipulated visually by a software development environment, like JBuilder or VisualAge for Java.
167) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:
- Threads share the same address space.
- Thread is lightweight.
- Cost of communication between process is low.
168) What is thread?
A thread is a lightweight subprocess. It is a separate path of execution. It is called separate path of execution because each thread runs in a separate stack frame.
169) 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.
170) 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.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
171) What is currentThread() method?
The currentThread() method returns a reference to the currently executing thread object.
Syntax:
public static Thread currentThread()
172) What is difference between wait() and sleep() method?
wait() | sleep() |
---|---|
The wait() method is defined in Object class. | The sleep() method is defined in Thread class. |
wait() method releases the lock. | The sleep() method doesn’t releases the lock. |
173) Is it possible to start a thread twice?
No. After staring a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown.
174) Can we call the run() method instead of start()?
Yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.
175) What is a Daemon Thread?
Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc. You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc.
Points to remember for Daemon Thread in Java
- It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
- Its life depends on user threads.
- It is a low priority thread.
176) Why JVM terminates the daemon thread if there is no user thread?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.
177) Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
public void setDaemon(boolean status) | is used to mark the current thread as daemon thread or user thread. |
public boolean isDaemon() | is used to check that current is daemon. |
178) Can we make the user thread as daemon thread if thread is started?
No, if you do so, it will throw IllegalThreadStateException.
179) What is shutdown hook?
The shutdown hook is basically a thread i.e. invoked implicitly before JVM shuts down. So we can use it perform clean up resource.
180) When should we interrupt a thread?
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn’t interrupt the thread but sets the interrupt flag to true. Let’s first see the methods provided by the Thread class for thread interruption.
181) What methods are used to interrupt the thread?
- public void interrupt()
- public static boolean interrupted()
- public boolean isInterrupted()
181) How to interrupt a thread that behaves normally?
If thread is not in sleeping or waiting state, calling the interrupt() method sets the interrupted flag to true that can be used to stop the thread by the java programmer later.
182) Explain isInterrupted and interrupted method
The isInterrupted() method returns the interrupted flag either true or false. The static interrupted() method returns the interrupted flag after that it sets the flag to false if it is true.
183) What is synchronization?
Synchronization is the capabilility of control the access of multiple threads to any shared resource. It is used:
- To prevent thread interference.
- To prevent consistency problem.
184) What is the purpose of Synchronized block?
Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method.
185) 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.
186) What is static synchronization?
If you make any static method as synchronized, the lock will be on the class not on object.
187) 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.
188) What is deadlock?
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
189) What is the difference between ArrayList and Vector?
ArrayList | Vector |
---|---|
ArrayList is not synchronized. | Vector is synchronized. |
ArrayList is not a legacy class. | Vector is a legacy class. |
ArrayList increases its size by 50% of the array size. | Vector increases its size by doubling the array size. |
190) What is the difference between ArrayList and LinkedList?
ArrayList | LinkedList |
---|---|
ArrayList uses a dynamic array. | LinkedList uses doubly linked list. |
ArrayList is not efficient for manipulation because a lot of shifting is required. | LinkedList is efficient for manipulation. |
ArrayList is better to store and fetch data. | LinkedList is better to manipulate data. |
191) What is the difference between Iterator and ListIterator?
Iterator | ListIterator |
---|---|
Iterator traverses the elements in forward direction only. | ListIterator traverses the elements in backward and forward directions both. |
Iterator can be used in List, Set and Queue. | ListIterator can be used in List only. |
192) What is the difference between Iterator and Enumeration?
Iterator | Enumeration |
---|---|
Iterator can traverse legacy and non-legacy elements. | Enumeration can traverse only legacy elements. |
Iterator is fail-fast. | Enumeration is not fail-fast. |
Iterator is slower than Enumeration. | Enumeration is faster than Iterator. |
193) What is the difference between List and Set?
List can contain duplicate elements whereas Set contains only unique elements.
194) What is the difference between HashSet and TreeSet?
HashSet maintains no order whereas TreeSet maintains ascending order.
195) What is the difference between Set and Map?
Set contains values only whereas Map contains key and values both.
196) What is the difference between HashSet and HashMap?
HashSet contains only values whereas HashMap contains entry(key, value). HashSet can be iterated but HashMap need to convert into Set to be iterated.
197) What is the difference between HashMap and TreeMap?
HashMap maintains no order but TreeMap maintains ascending order.
198) What is the difference between HashMap and Hashtable?
HashMap | Hashtable |
---|---|
HashMap is not synchronized. | Hashtable is synchronized. |
HashMap can contain one null key and multiple null values. | Hashtable cannot contain any null key or null value. |
199) What is the difference between Collection and Collections?
Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.
200) What is the difference between Comparable and Comparator?
Comparable | Comparator |
---|---|
Comparable provides only one sort of sequence. | Comparator provides multiple sort of sequences. |
It provides one method named compareTo(). | It provides one method named compare(). |
It is found in java.lang package. | it is found in java.util package. |
If we implement Comparable interface, actual class is modified. | Actual class is not modified. |
201) What is the advantage of Properties file?
If you change the value in properties file, you don’t need to recompile the java class. So, it makes the application easy to manage.
202) What does the hashCode() method do?
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 same. But, it is possible that two hash code numbers can have different or same keys.
203) Why we override equals() method?
The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property.
For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.
204) 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){} |
205) What is the advantage of generic collection?
If we use generic class, we don’t need typecasting. It is typesafe and checked at compile time.
206) What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.
207) What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.
208) 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.
209) What is JDBC?
JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc drivers to connects to the database.
210) 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:
- JDBC-ODBC bridge driver
- Native-API driver (partially java driver)
- Network Protocol driver (fully java driver) Thin driver (fully java driver)
211) What is JDBC-ODBC bridge driver?
The JDBC-ODBC bridge driver uses 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 thin driver.
212) What is Native-API 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.
213) What is Network Protocol driver?
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.
214) What is Thin driver?
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.
215) What are the steps to connect to the database in java?
There are 5 steps to connect any java application with the database in java using JDBC. They are as follows:
- Register the driver class
- The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class
- Syntax :
- public static void forName(String className)throws ClassNotFoundException
- Creating connection
- The getConnection() method of DriverManager class is used to establish connection with the database.
- Syntax:
- public static Connection getConnection(String url)throws SQLException
- public static Connection getConnection(String url,String name,String password)throws SQLException
- Creating statement
- The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.
- Executing 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:
- public ResultSet executeQuery(String sql)throws SQLException
- 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:
- public void close()throws SQLException
216) What are the JDBC API components?
The java.sql package contains interfaces and classes for JDBC API.
Interfaces:
- Connection
- Statement
- PreparedStatement
- ResultSet
- ResultSetMetaData
- DatabaseMetaData
- CallableStatement, etc.
Classes:
- DriverManager
- Blob
- Clob
- Types SQLException, etc.
217) What are the JDBC statements?
There are 3 JDBC statements.
- Statement
- PreparedStatement
- CallableStatement
218) What is the difference between Statement and PreparedStatement interface?
In case of Statement, query is complied each time whereas in case of PreparedStatement, query is complied only once. So performance of PreparedStatement is better than Statement.
219) What is a PreparedStatement interface?
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
Let’s see the example of parameterized query:
String sql=”insert into emp values(?,?,?)”;
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement.
220) How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
221) Methods of PreparedStatement interface
public void setInt(int paramIndex, int value) | sets the integer value to the given parameter index. |
public void setString(int paramIndex, String value) | sets the String value to the given parameter index. |
public void setFloat(int paramIndex, float value) | sets the float value to the given parameter index. |
public void setDouble(int paramIndex, double value) | sets the double value to the given parameter index. |
public int executeUpdate() | executes the query. It is used for create, drop, insert, update, delete etc. |
public ResultSet executeQuery() | executes the select query. It returns an instance of ResultSet. |
222) How can we execute stored procedures and functions?
By using Callable statement interface, we can execute procedures and functions.
223) What is the role of JDBC DriverManager class?
The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.
224) What is 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().
225) Commonly used methods of DriverManager class
public static void registerDriver(Driver driver): | is used to register the given driver with DriverManager. |
public static void deregisterDriver(Driver driver): | is used to deregister the given driver (drop the driver from the list) with DriverManager. |
public static Connection getConnection(String url): | is used to establish the connection with the specified url. |
public static Connection getConnection(String url,String userName,String password): | is used to establish the connection with the specified url, username and password. |
226) What does 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 returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.
227) 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.
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row. By default, ResultSet object can be moved forward only and it is not updatable. But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
228) What are the commonly used methods of ResultSet interface?
public boolean next() | is used to move the cursor to the one row next from the current position. |
public boolean previous() | is used to move the cursor to the one row previous from the current position. |
public boolean first() | is used to move the cursor to the first row in result set object. |
public boolean last() | is used to move the cursor to the last row in result set object. |
public boolean absolute(int row) | is used to move the cursor to the specified row number in the ResultSet object. |
public boolean relative(int row) | is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative. |
public int getInt(int columnIndex) | is used to return the data of specified column index of the current row as int. |
public int getInt(String columnName) | is used to return the data of specified column name of the current row as int. |
public String getString(int columnIndex) | is used to return the data of specified column index of the current row as String. |
public String getString(String columnName) | is used to return the data of specified column name of the current row as String. |
229) What does the JDBC ResultSetMetaData interface do?
The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.
230) What are the commonly used methods of ResultSetMetaData interface?
public int getColumnCount()throws SQLException | it returns the total number of columns in the ResultSet object. |
public String getColumnName(int index)throws SQLException | it returns the column name of the specified column index. |
public String getColumnTypeName(int index)throws SQLException | it returns the column type name for the specified index. |
public String getTableName(int index)throws SQLException | it returns the table name for the specified column index. |
231) What does the JDBC DatabaseMetaData interface do?
The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.
232) Which interface is responsible for transaction management in JDBC?
The Connection interface provides methods for transaction management such as commit(), rollback() etc.
Methods | Description |
---|---|
void setAutoCommit(boolean status) | It is true bydefault means each transaction is committed bydefault. |
void commit() | commits the transaction. |
void rollback() | cancels the transaction. |
233) What is batch processing and how to perform batch processing in JDBC?
Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance fast. The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.
Method | Description |
---|---|
void addBatch(String query) | It adds query into batch. |
int[] executeBatch() | It executes the batch of queries. |
234) How can we store and retrieve images from the database?
You can store images in the database in java by the help of PreparedStatement interface. The setBinaryStream() method of PreparedStatement is used to set Binary information into the parameterIndex.
More Article:
What’s new in Springboot 5.3?
Top Open Source Software Development Tools