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 is super in java?
“The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.
class Animal{
Animal(){System.out.println(“”animal is created””);}
}
class Dog extends Animal{
Dog(){
System.out.println(“”dog is created””);
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}
} “
How can constructor chaining be done by using the super keyword?
“class Person
{
String name,address;
int age;
public Person(int age, String name, String address)
{
this.age = age;
this.name = name;
this.address = address;
}
}
class Employee extends Person
{
float salary;
public Employee(int age, String name, String address, float salary)
{
super(age,name,address);
this.salary = salary;
}
}
public class Test
{
public static void main (String args[])
{
Employee e = new Employee(22, “”Mukesh””, “”Delhi””, 90000);
System.out.println(“”Name: “”+e.name+”” Salary: “”+e.salary+”” Age: “”+e.age+”” Address: “”+e.address);
}
} “
Java Interview Questions
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.”
What is the output of the following Java program?
“class Person
{
public Person()
{
System.out.println(“”Person class constructor called””);
}
}
public class Employee extends Person
{
public Employee()
{
System.out.println(“”Employee class constructor called””);
}
public static void main (String args[])
{
Employee e = new Employee();
}
} “
Advance Java Interview Questions
Can you use this() and super() both in a constructor?
“No, because this() and super() must be the first statement in the class constructor.
Example:
public class Test{
Test()
{
super();
this();
System.out.println(“”Test class object is created””);
}
public static void main(String []args){
Test t = new Test();
}
} “
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 Clone Not Supported Exception.
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.”
Java Interview Questions
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.
public class Animal
{
void consume(int a)
{
System.out.println(a+”” consumed!!””);
}
static void consume(int a)
{
System.out.println(“”consumed static “”+a);
}
public static void main (String args[])
{
Animal a = new Animal();
a.consume(10);
Animal.consume(20);
}
} “
What is the output of the following Java program?
“class OverloadingCalculation3{
void sum(int a,long b){System.out.println(“”a method invoked””);}
void sum(long a,int b){System.out.println(“”b method invoked””);}
public static void main(String args[]){
OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}
Output
OverloadingCalculation3.java:7: error: reference to sum is ambiguous
obj.sum(20,20);//now ambiguity
^
both method sum(int,long) in OverloadingCalculation3
and method sum(long,int) in OverloadingCalculation3 match
1 errorplanation
There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.”
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.”
Advance Java Interview Questions
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.
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.”
What is the output of the following Java program?
“class Base
{
void method(int a)
{
System.out.println(“”Base class method called with integer a = “”+a);
}
void method(double d)
{
System.out.println(""Base class method called with double d =""+d);
}
}
class Derived extends Base
{
@Override
void method(double d)
{
System.out.println(“”Derived class method called with double d =””+d);
}
}
public class Main
{
public static void main(String[] args)
{
new Derived().method(10);
}
}
Output
Base class method called with integer a = 10
Explanation
The method() is overloaded in class Base whereas it is derived in class Derived with the double type as the parameter. In the method call, the integer is passed.”
Java Interview Questions
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. The covariant return type specifies that the return type may vary in the same direction as the subclass.
class A{
A get(){return this;}
}
class B1 extends A{
B1 get(){return this;}
void message(){System.out.println(“”welcome to covariant return type””);}
public static void main(String args[]){
new B1().get().message();
}
} “
What is the output of the following Java program?
“class Base
{
public void baseMethod()
{
System.out.println(“”BaseMethod called …””);
}
}
class Derived extends Base
{
public void baseMethod()
{
System.out.println(“”Derived method called …””);
}
}
public class Test
{
public static void main (String args[])
{
Base b = new Derived();
b.baseMethod();
}
} “
What is the final method?
“If we change any method to a final method, we can’t override it. More Details.
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();
}
} “
Advance Java Interview Questions
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:
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
…
} “
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.
What is the output of the following Java program?
“class Main {
public static void main(String args[]){
final int i;
i = 20;
System.out.println(i);
}
} “
Java Interview Questions
Can we declare a constructor as final?
The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.
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.
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.
class Bike{
void run(){System.out.println(“”running””);}
}
class Splendor extends Bike{
void run(){System.out.println(“”running safely with 60km””);}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
} “
Advance Java Interview Questions
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.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
} “
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
class Dog{
private void eat(){System.out.println(“”dog is eating…””);}
public static void main(String args[]){
Dog d1=new Dog();
d1.eat();
}
}
Dynamic Binding
class Animal{
void eat(){System.out.println(“”animal is eating…””);}
}
class Dog extends Animal{
void eat(){System.out.println(“”dog is eating…””);}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}
} “
What is the output of the following Java program?
“class BaseTest
{
void print()
{
System.out.println(“”BaseTest:print() called””);
}
}
public class Test extends BaseTest
{
void print()
{
System.out.println(“”Test:print() called””);
}
public static void main (String args[])
{
BaseTest b = new Test();
b.print();
}
}
Output
Test:print() called
Explanation
It is an example of Dynamic method dispatch. The type of reference variable b is determined at runtime. At compile-time, it is checked whether that method is present in the Base class. In this case, it is overridden in the child class, therefore, at runtime the derived class method is called.”
Java Interview Questions
What is Java instance Of operator?
“The instance of in Java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instance of operator with any variable that has a null value, it returns false. Consider the following example.
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Test it Now
Output
true
An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog can be referred by either Dog or Animal class.”
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.
Abstract Class
Interface”
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.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println(“”running safely””);}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
} “
Advance Java Interview Questions
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.
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.
public interface Serializable{
} “
How to make a read-only class in Java?
“A class can be made read-only by making all of the fields private. The read-only class will have only getter methods which return the private property of the class to the main method. We cannot modify this property because there is no setter method available in the class. Consider the following example.
//A Java class which has only getter methods.
public class Student{
//private data member
private String college=””AKG””;
//getter method for college
public String getCollege(){
return college;
}
} “
Java Interview Questions
How to make a write-only class in Java?
“A class can be made write-only by making all of the fields private. The write-only class will have only setter methods which set the value passed from the main method to the private fields. We cannot read the properties of the class because there is no getter method in this class. Consider the following example.
//A Java class which has only setter methods.
public class Student{
//private data member
private String college;
//getter method for college
public void setCollege(String college){
this.college=college;
}
} “
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.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println(“”Welcome to package””);
}
} “
Advance Java Interview Questions
What are the advantages of defining packages in Java?
“By defining packages, we can avoid the name conflicts between the same class names defined in different packages. Packages also enable the developer to organize the similar classes more effectively. For example, one can clearly understand that the classes present in java.io package are used to perform io related operations.
How to create packages in Java?
“If you are using the programming IDEs like Eclipse, NetBeans, My Eclipse, etc. click on file->new->project and eclipse will ask you to enter the name of the package. It will create the project package containing various directories such as src, etc. If you are using an editor like notepad for java programming, use the following steps to create the package.
Define a package package_name. Create the class with the name class_name and save this file with your_class_name.java.
Now compile the file by running the following command on the terminal.
javac -d . your_class_name.java
The above command creates the package with the name package_name in the present working directory.
Now, run the class file by using the absolute class file name, like following.
java package_name.class_name “
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 sub package.
Java Interview Questions
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, SQL Exception, Class Not Found Exception, etc.
Unchecked Exception: Unchecked exceptions are the one which are handled at runtime because they can not be checked at compile-time. For example, Arithmetic Exception, Null Pointer Exception, Array Index Out Of Bounds Exception, etc.
Error: Error cause the program to exit since they are not recoverable. For Example, Out Of Memory Error, Assertion Error, etc.”
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.
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.
public class Main{
public static void main(String []args){
try{
int a = 1;
System.out.println(a/0);
}
finally
{
System.out.println(“”rest of the code…””);
}
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code…”
Java Interview Questions
What is the output of the following Java program?
“public class ExceptionHandlingExample {
public static void main(String args[])
{
try
{
int a = 1/0;
System.out.println(“”a = “”+a);
}
catch(Exception e){System.out.println(e);}
catch(ArithmeticException ex){System.out.println(ex);}
}
}
Output
ExceptionHandlingExample.java:10: error: exception ArithmeticException has already been caught
catch(ArithmeticException ex){System.out.println(ex);}
^
1 error
Explanation
Arithmetic Exception is the subclass of Exception. Therefore, it can not be used after Exception. Since Exception is the base class for all the exceptions, therefore, it must be used at last to handle the exception. No class can be used after this.”
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).
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.
Advance Java Interview Questions
What is the output of the following Java program?
“class Calculation extends Exception
{
public Calculation()
{
System.out.println(“”Calculation class is instantiated””);
}
public void add(int a, int b)
{
System.out.println(“”The sum is “”+(a+b));
}
}
public class Main{
public static void main(String []args){
try
{
throw new Calculation();
}
catch(Calculation c){
c.add(10,20);
}
}
}
Output
Calculation class is instantiated
The sum is 30
Explanation
The object of Calculation is thrown from the try block which is caught in the catch block. The add() of Calculation class is called with the integer values 10 and 20 by using the object of this class. Therefore there sum 30 is printed. The object of the Main class can only be thrown in the case when the type of the object is throwable. To do so, we need to extend the throwable class.”
What is exception propagation?
“An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This procedure is called exception propagation. By default, checked exceptions are not propagated.
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println(“”exception handled””);}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println(“”normal flow…””);
}
} “
How can we create an immutable class in Java?
“We can create an immutable class by defining a final class having all of its members as final. Consider the following example.
public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
} “
Java Interview Questions
What is the purpose of to String() 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.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){//overriding the toString() method
return rollno+”” “”+name+”” “”+city;
}
public static void main(String args[]){
Student s1=new Student(101,””Raj””,””lucknow””);
Student s2=new Student(102,””Vijay””,””ghaziabad””);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
} “
Why Char Array() is preferred over String to store the password?
String stays in the string pool until the garbage is collected. If we store the password into a string, it stays in the memory for a longer period, and anyone having the memory-dump can extract the password as clear text. On the other hand, Using Char Array allows us to set it to blank whenever we are done with the password. It avoids the security threat with the string by enabling us to control the memory.
Write a Java program to count the number of words present in a string?
“Program:
public class Test
{
public static void main (String args[])
{
String s = “”Sharma is a good player and he is so punctual””;
String words[] = s.split(“” “”);
System.out.println(“”The Number of words present in the string are : “”+words.length);
}
}
Output
The Number of words present in the string are : 10″
Advance Java Interview Questions
What is a servlet?
- Java Servlet is server-side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
- The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
- All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
- Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.

What is Request Dispatcher?
Request Dispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response.
There are two methods defined in this interface:
1.void forward()
2.void include()
What is the life-cycle of a servlet?

There are 5 stages in the lifecycle of a servlet:
- Servlet is loaded
- Servlet is instantiated
- Servlet is initialized
- Service the request
- Servlet is destroyed
Java Interview Questions
How does cookies work in Servlets?
- Cookies are text data sent by server to the client and it gets saved at the client local machine.
- Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
- Http Servlet Request get Cookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
- Similarly Http Servlet Response add Cookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.
What are the differences between Servlet Context vs Servlet Config?
The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.
ServletConfig | ServletContext |
---|---|
Servlet config object represent single servlet | It represent whole web application running on particular JVM and common for all the servlet |
Its like local parameter associated with particular servlet | Its like global parameter associated with whole application |
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope | ServletContext has application wide scope so define outside of servlet tag in web.xml file. |
getServletConfig() method is used to get the config object | getServletContext() method is used to get the context object. |
for example shopping cart of a user is a specific to particular user so here we can use servlet config | To get the MIME type of a file or application session related information is stored using servlet context object. |
What are the different methods of session management in servlets?
Session is a conversational state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.
Some of the common ways of session management in servlets are:
- User Authentication
- HTML Hidden Field
- Cookies
- URL Rewriting
- Session Management API
Advance Java Interview Questions
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)
What are the steps to connect to a database in java?
- Registering the driver class
- Creating connection
- Creating statement
- Executing queries
- Closing connection
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:
- Driver Manager
- Blob
- Clob
- Types
- SQL Exception etc.
Java Interview Questions
What is the role of JDBC Driver Manager class?
The Driver Manager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.
What is 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, Prepared Statement, Callable Statement and Database Meta Data.
What is the purpose of JDBC Result Set interface?
The Result Set object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.
Advance Java Interview Questions
What is JDBC ResultSetMetaData interface?
The Result Set Meta Data interface returns the information of table such as total number of columns, column name, column type etc.
What is JDBC Database Metadata interface?
The Database Metadata interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.
Write a program to find the Second Highest number in an ArrayList
The following program can be used to find the second biggest number in an array list.
package simplilearnJava;
public class NextHighest {
public static void main(String[] args)
{
int array[] = { 1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32};
int high = 0;
int nextHigh = 0;
System.out.println(“The given array is:”);
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + “\t”);
}
for (int i = 0; i < array.length; i++)
{
if (array[i] > high)
{
nextHigh = high;
high = array[i];
}
else if (array[i] > nextHigh)
{
nextHigh = array[i];
}
}
System.out.println(“\nSecond Highest is:” + nextHigh);
System.out.println(“Highest Number is: ” +high);
}
}
Expected Output:
The given array is:
1 2 3 4 11 12 13 14 21 22 23 24 31 32
Second Highest is:31
The highest number is: 32
Java Interview Questions
What is the difference between System.out, System.err, and System.in?
System.out and System.err represent the monitor by default and thus can be used to send data or results to the monitor. System.out is used to display normal messages and results. System.eerr is used to display error messages. System.in represents InputStream object which by default represents standard input device, i.e., keyboard.
Could you provide some implementation of a Dictionary having a large number of words?
The simplest implementation that can be given is that of a List wherein one can place ordered words and perform a Binary search. The other implementation with a better search performance is Hash Map where the key is used as the first character of the word and the value as a Linked List.
Up another level, there are Hash Maps like:
hash map {
a (key) -> hashmap (key-aa , value (hashmap(key-aaa,value)
b (key) -> hashmap (key-ba , value (hashmap(key-baa,value)
z (key) -> hashmap (key-za , value (hashmap(key-zaa,value)
}
Up to n levels where n is the average size of the word in the dictionary.
Explain JPA in Java.
The Java Persistence API enables us to create the persistence layer for desktop and web applications. Java Persistence deals in the following:
- Java Persistence API
- Query Language
- Java Persistence Criteria API
- Object Mapping Metadata
Advance Java Interview Questions
What is JCA in Java?
Java Cryptography Architecture gives a platform and provides architecture and application programming interfaces that enable decryption and encryption.
Developers use Java Cryptography Architecture to combine the application with the security applications. Java Cryptography Architecture helps in implementing third party security rules and regulations.
Java Cryptography Architecture uses the hash table, encryption message digest, etc. to implement the security.
Why is Java is Dynamic?
Java is designed to adapt to an evolving environment. Java programs include a large amount of runtime information that is used to resolve access to objects in real-time.
What is the Daemon Thread?
The Daemon thread can be defined as a thread with the least priority. This Daemon thread is designed to run in the background during the Garbage Collection in Java.
The set Daemon() method creates a Daemon thread in Java.
Java Interview Questions
Why are generics used in Java Programming?
Compile-time type safety is provided by using generics. Compile-time type safety allows users to catch unnecessary invalid types at compile time. Generic methods and classes help programmers specify a single method declaration, a set of related methods, or related types with an available class declaration.
Brief the life cycle of an applet.
The life cycle of an applet involves the following.
- Initialization
- Start
- Stop
- Destroy
- Paint
Give a briefing on the life cycle of a thread.
The life cycle of a thread includes five stages, as mentioned below.
- New Born State
- Runnable State
- Running State
- Blocked State
- Dead State
Advance Java Interview Questions
Why is the delete function faster in the linked list than an array?
Delete Function is faster in linked lists as the user needs to make a minor update to the pointer value so that the node can point to the next successor in the list
Define Dynamic Method Dispatch.
The Dynamic method dispatch is a process where the method call is executed during the runtime. A reference variable is used to call the super-class. This process is also known as Run-Time Polymorphism.
Define Late Binding.
Binding is a process of unifying the method call with the method’s code segment. Late binding happens when the method’s code segment is unknown until it is called during the runtime.
Java Interview Questions
Can we overload a static method?
No, Java does not support the Overloading of a static method. The process would throw an error reading “static method cannot be referenced.”
Explain ‘super’ keyword in Java.
The term “super” is a particular keyword designated as a reference keyword. The “super” keyword refers to the immediate parent class object.
Explain ‘this’ keyword in Java.
The term “this” is a particular keyword designated as a reference keyword. The “this” keyword is used to refer to the current class properties like method, instance, variable, and constructors.
Advance Java Interview Questions
What are Brief Access Specifiers and Types of Access Specifiers?
Access Specifiers are predefined keywords used to help JVM understand the scope of a variable, method, and class. We have four access specifiers.
- Public Access Specifier
- Private Access Specifier
- Protected Access Specifier
- Default Access Specifier
What is an Exception?
An Exception in Java is considered an unexpected event that can disrupt the program’s normal flow. These events can be fixed through the process of Exception Handling.
Explain Java String Pool.
A collection of strings in Java’s Heap memory is referred to as Java String Pool. In case you try to create a new string object, JVM first checks for the presence of the object in the pool. If available, the same object reference is shared with the variable, else a new object is created.
Java Interview Questions
Differentiate between instance and local variables.
For instance, variables are declared inside a class, and the scope is limited to only a specific object.
A local variable can be anywhere inside a method or a specific block of code. Also, the scope is limited to the code segment where the variable is declared.
Can you implement pointers in a Java Program?
Java Virtual Machine takes care of memory management implicitly. Java’s primary motto was to keep programming simple. So, accessing memory directly through pointers is not a recommended action. Hence, pointers are eliminated in Java.
Define package in Java.
The package is a collective bundle of classes and interfaces and the necessary libraries and JAR files. The use of packages helps in code reusability.
Advance Java Interview Questions
Define Singleton Classes in Java.
In Java, when you make the constructor of a class private, that particular class can generate only one object. This type of class is popularly known as a Singleton Class.
Define Wrapper Classes in Java.
In Java, when you declare primitive datatypes, then Wrapper classes are responsible for converting them into objects(Reference types).
Why is Java not completely object-oriented?
Java is not considered as a 100% object-oriented programming language because it still makes use of eight or more primitive data types like int, float double, etc.
Java Interview Questions
Write a program in java to remove all vowels from a string.
import java.util.Scanner;
public class star {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String n=sc.nextLine();
String n1=n.replaceAll("[AEIOUaeiou]", "");
System.out.println(n1);
}
}
Write a program in java to check for palindromes.
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
What is the underlying mechanism in java’s built-in sort?
Java’s built-in sort function utilizes the two pivot quicksort mechanism. Quicksort works best in most real-life scenarios and has no extra space requirements.
Advance Java Interview Questions
What is the use of super?
super() is used to invoke the superclass constructor by the subclass constructor. In this way, we do not have to create different objects for super and subclasses.
How is encapsulation achieved in Java?
Encapsulation is achieved by wrapping up data and code into simple wrappers called classes. Objects instantiate the class to get a copy of the class data.
What is generics in java?
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
Java Interview Questions
How to find the length of an array in java?
class ArrayLengthFinder {
public static void main(String[] arr) {
// declare an array
int[] array = new int[10];
array[0] = 12;
array[1] = -4;
array[2] = 1;
// get the length of array
int length = array.length;
System.out.println(""Length of array is: "" + length);
}
}
How to iterate hash map in java?
import java.util.Map;
import java.util.HashMap;
class IterationDemo
{
public static void main(String[] arg)
{
Map<String,String> g = new HashMap<String,String>();
// enter name/url pair
g.put(""1"":""One"");
g.put(""2"":""Two"");
// using for-each loop for iteration over Map.entrySet()
for (Map.Entry<String,String> entry : g.entrySet())
System.out.println(""Key = "" + entry.getKey() +
"", Value = "" + entry.getValue());
}
}
How to split a string in java?
public class JavaExample{
public static void main(String args[]){
String s = "" ,ab;gh,bc;pq#kk$bb"";
String[] str = s.split(""[,;#$]"");
//Total how many substrings? The array length
System.out.println(""Number of substrings: ""+str.length);
for (int i=0; i < str.length; i++) {
System.out.println(""Str[""+i+""]:""+str[i]);
}
}
}
Advance Java Interview Questions
How to sort array in java?
public class InsertSort {
public static void main (String [] args) {
int [] array = {10,20,30,60,70,80,2,3,1};
int temp;
for (int i = 1; i < array.length; i++) {
for (int j = i; j > 0; j--) {
if (array[j] < array [j - 1]) {
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Why main method is static in java?
Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class. In any Java program, the main() method is the starting point from where compiler starts program execution. So, the compiler needs to call the main() method.