Java Questions
Java Questions
There is a list of 30 servlet interview questions for beginners and professionals. If you
know any servlet interview question that has not been included here, kindly post your
question in the Ask Question section.
Description
It is invoked only once when first
request comes for the servlet. It
is used to initialize the servlet.
request,ServletResponse)throws
ServletException,IOException
more details...
Post
URL bar.
URL bar.
3) Can be bookmarked
Cannot be bookmarked
4) Idempotent
Non-Idempotent
more details...
RequestDispacher interface
1.
2.
copy to clipboard
RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");
rd.forward(request,response);
RequestDispatcher rd=request.
rd.forw ard(request,response);
sendRedirect() method
server side.
3) forward() method works
the server.
18) How can we perform any action at the time of deploying the
project?
By the help of ServletContextListener interface.
20) How can we upload the file to the server using servlet?
One of the way is by MultipartRequest class provided by third party.
more details...
1.
copy to clipboard
jar -cvf abc.war *
jar -cvf abc.w ar *
Now all the files of current directory will be converted into abc.war file.
http://www.tutorialspoint.com/servlets/servlets-life-cycle.htm
http://www.javatpoint.com/servletinterview
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM.
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools.
more details...
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.
The Java platform differs from most other platforms in the sense that it's a softwarebased platform that runs on top of other hardware-based platforms.It has two
components:
1. Runtime Environment
2. 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.
1.
2.
3.
4.
5.
6.
7.
8.
copy to clipboard
//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
11) What if I write static public void instead of public static void?
Program compiles and runs properly.
There is given more than 50 OOPs (Object-Oriented Programming and System) interview
questions. But they have been categorized in many sections such as constructor
interview questions, static interview questions, Inheritance Interview questions,
Abstraction interview question, Polymorphism interview questions etc. for better
understanding.
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.
more details...
The default constructor provides the default values to the objects. The java
compiler creates a default constructor only if there is no constructor in the
class.more details...
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.
static variable gets memory only once in class area at the time of class loading.
more details...
A static method 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.
more details...
more details...
instance method
static method.
instance methods.
n*n*n;}
{...}.
28)What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behaviour
of another object of another class. It represents IS-A relationship. It is used for Code
Resusability and Method Overriding.
more details...
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java in case of class.more details...
Method Overriding
1) Method overloading
program.
2) method overlaoding is
IS-A relationship.
must be different.
more details...
60) 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.
Interface
abstract methods).
methods.
71) 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.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at
compile-time.
more details...
Yes, by try block. finally must be followed by either try or catch.more details...
throws keyword
throw an exception.
2)checked exceptions can not
instance.
4)throw is used within the
method.
5)You cannot throw multiple
exception
method()throws IOException,SQLException.
more details...
copy to clipboard
String s1="Welcome";
2.
3.
String s2="Welcome";
String s3="Welcome";
String s1="Welcome";
String s2="Welcome";
String s3="Welcome";
copy to clipboard
String s = new String("Welcome");
String s = new String("Welcome
96) 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.
more details...
prev next
just before the object is garbage collected.The finalize() method can be used to perform
any cleanup processing.
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.
more details...
130)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.
Debugger
134) Can you access the private method from outside the
class?
Yes, by changing the runtime behaviour of a class if the class is not secured.
more details...
Next TopicJava Miscellaneous interview Questions
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.
159)What is an applet?
An applet is a small java program that runs inside the browser and generates dynamic
contents.
161)What is Locale?
A Locale object represents a specific geographical, political, or cultural region.
163)What is a 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.
1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main
advantage is:
Thread is lightweight.
more details...
2) 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.
more details...
sleep()
class.
class.
lock.
The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down.
So we can use it perform clean up resource.
more details...
more details...
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.
17)What is deadlock?
Deadlock is a situation when two threads are waiting on each other to release a resource.
Each thread waiting for a resource which is held by the other waiting thread.
more details...
Next TopicJava Collections interview Questions
ArrayList
Vector
1)
Vector is synchronized.
2)
3)
ArrayList
LinkedList
2)
3)
manipulation.
LinkedList is better to
manipulate data.
No.
1)
2)
Iterator
ListIterator
and Queue.
Iterator
Enumeration
1)
legacy elements.
legacy elements.
2)
Iterator is fail-fast.
3)
HashMap
Hashtable
1)
Hashtable is synchronized.
2)
Comparable
Comparator
sequence.
sort of sequences.
compareTo().
compare().
3)
4)
2)
1) 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.
more details...
Creating connection
Creating statement
Executing queries
Closing connection
more details...
Connection
Statement
PreparedStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
CallableStatement etc.
Classes:
DriverManager
Blob
Clob
Types
SQLException etc.
15) How can we store and retrieve images from the database?
By using PreparedStatement interface, we can store and retrieve images
2) What is normalization?
In RDBMS, the process of organizing data to minimize redundancy is called
normalization. In normalization database is divided in two or more tables and a
relationship is defined among the tables.
3) What is De-Normalization?
It is a process of attempting to optimize the performance of a database by adding
redundant data. Actually redundancy is introduced intentionally in a table to improve
performance and it is called de-normalization.
Functions take one mandatory input parameter while stored procedures may take 0 to n
input parameter.
Exceptions can be handled by try-catch block in stored procedure while you can't use trycatch in functions.
Case sensitivity
Accent sensitivity
Kana sensitivity
Width sensitivity
Cold standby:Cold standby is the method of redundancy in which the secondary server
is only called when the primary server fails. Cold standby systems are used in cases
where data is changed infrequently or for nor critical applications.
You can watch the trace results when the trace runs.
You can store the trace results in a table.
If it is necessary, you can start, stop, pause and modify the trace results.
DBCC CHECKFILEGROUP:
It checks all table file group for any damage.
14) Can SQL Server be linked with other Servers like Oracle?
Yes, it can be linked to any Sever. It has OLE-DB provider from Microsoft which allow
linking.
The session object is used to maintain the session of each user. If a user enters into an
application, he gets session id and when he leaves application then the session id is
deleted. If he enters again in to the application he gets a different session id but for
application object once ad id is generated it maintains whole application.
17)Is there any difference between primary key and unique with
NOT NULL condition?
There is no difference between primary key and unique key with not null.
1) What is hibernate?
Hibernate is an open-source and lightweight ORM tool that is used to store, manipulate
and retrieve data from the database.
more details...
2) What is ORM?
ORM is an acronym for Object/Relational mapping. It is a programming strategy to map
object with the data stored in the database. It simplifies data creation, data manipulation
and data access.
more details...
Configuration
SessionFactory
Session
Query
Criteria
Transaction
5) What is SessionFactory?
SessionFactory provides the instance of Session. It is a factory of Session. It holds the
data of second level cache that is not enabled by default.
more details...
7) What is Session?
It maintains a connection between hibernate application and database.
It provides methods to store, update, delete or fetch data from the database such as
persist(), update(), delete(), load(), get() etc.
It is a factory of Query, Criteria and Transaction i.e. it provides factory methods to return
these instances.
more details...
No.
1)
2)
save()
persist()
the instance.
type is void.
No.
1)
get()
load()
Throws ObjectNotFoundException if
object is not found.
2)
database.
3)
4)
instance exists.
instance.
No.
1)
update() method
Update means to edit something.
merge() method
Merge means to combine
something.
2)
1.
2.
3.
4.
5.
copy to clipboard
...
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();
After closing session1, e1 is in detached state. It will not be in session1 cache. So if you
call update() method, it will throw an error.
Then, we opened another session and loaded the same Employee instance. If we call
merge in session2, changes of e1 will be merged in e2.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
copy to clipboard
...
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();
Transaction tx=session2.beginTransaction();
Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));
e1.setSalary(70000);
tx.commit();
11.
session1.close();
...
SessionFactory factory = cfg.b
Session session1 = factory.ope
Transaction tx=session2.beginT
Here, after getting employee instance e1 and we are changing the state of e1.
After changing the state, we are committing the transaction. In such case, state will be
updated automatically. This is known as dirty checking in hibernate.
Since Hibernate 3, lazy loading is enabled by default, you don't need to do lazy="true". It
means not to load the child objects when parent is loaded.
20) What is the difference between first level cache and second
level cache?
No.
1)
2)
with Session.
SessionFactory.
It is enabled by default.
1) What is Spring?
1.
2.
3.
4.
5.
6.
copy to clipboard
public class Employee{
Address address;
Employee(){
address=new Address();//creating instance
}
}
public class Employee{
Address address;
Employee(){
address=new Address();//crea
}
Now, there is dependency between Employee and Address because Employee is forced to
use the same address instance.
Let's write the IOC or DI code.
1.
2.
3.
4.
5.
6.
copy to clipboard
public class Employee{
Address address;
Employee(Address address){
this.address=address;//not creating instance
}
}
public class Employee{
Address address;
Employee(Address address){
this.address=address;//not crea
}
Now, there is no dependency between Employee and Address because Employee is not
forced to use the same address instance. It can use any address instance.
More details...
Constructor Injection
Setter Injection
1)
No Partial Injection
Partial Injection
2)
property
are defined.
modification occurs
3)
4)
More details...
1.
copy to clipboard
<bean id="emp" class="com.javatpoint.Employee" autowire="byName" />
<bean id="emp" class="com.jav
No.
Mode
Description
1)
no
2)
byName
3)
byType
4)
constructor
No.
1)
Scope
singleton
Description
The bean instance will be only once and same instance will be
returned by the IOC container. It is the default scope.
2)
prototype
3)
request
4)
session
5)
globalsession
More details...
JoinPoint
Advice
Pointcut
Aspect
Introduction
Target Object
Interceptor
AOP Proxy
Weaving
More details...
2. After Advice
3. After Returning Advice
4. Throws Advice
5. Around Advice
1) What is PL/SQL?
PL/SQL stands for procedural language extension to SQL. It supports procedural features
of programming language and SQL both. It was developed by Oracle Corporation in early
of 90's to enhance the capabilities of SQL.
BEFORE INSERT
1.
copy to clipboard
EXECUTE or [EXEC] procedure_name;
EXECUTE or [EXEC] procedure_
1.
copy to clipboard
procedure_name;
procedure_name;
%FOUND: it checks whether cursor has fetched any row. If yes - TRUE.
%NOTFOUND: it checks whether cursor has fetched any row. If no - TRUE.
Tablespaces
3) What is a tablespace?
A database contains Logical Storage Unit called tablespaces. A tablespace is a set of
related logical structures. Actually a tablespace groups related logical structures together.
10) What is the difference between hot backup and cold backup
in Oracle? Tell about their benefits also.
Hot backup (Online Backup): A hot backup is also known as online backup because it
is done while the database is active. Some sites can not shut down their database while
making a backup copy, they are used for 24 hour a day, 7 days a week.
Cold backup (Offline Backup): A cold backup is also known as offline backup because
it is done while the database has been shutdown using the SHUTDOWN normal
command. If the database is suddenly shutdown with a uncertain condition it should be
restarted with RESTRICT mode and then shutdown with NORMAL option.
For a complete cold backup the following files must be backed up.
All datafiles, All control files, All online redo log files(optional) and the init.ora file (you
can recreate it manually).
11) How many memory layers are in the Oracle shared pool?
A pre-query trigger fire before the query executes and fire once while you try to query.
With the help of this trigger you can modify the where clause part dynamically.
Pre-select query fires during the execute query and count query processing after Oracle
forms construct the select statement to be issued, but before the statement is actually
issued.
Pre-query trigger fires before Pre-select trigger.
1.
copy to clipboard
SELECT to_char ( to_date ('12-12-2012', 'DD-MM-YYYY') , 'YYYY-MM-DD') FROM du
al;
SELECT to_char ( to_date ('12-1
Or,
1.
copy to clipboard
SELECT to_char ( to_date ('12-12-2012', 'DD-MM-YYYY') , 'DD-MM-YYYY') FROM du
al;
SELECT to_char ( to_date ('12-1
Oracle reports are use to make business enable with the facility to provide information of
all level within or outside in a secure way. Oracle report uses REP files and RDF file
extensions.
1.
copy to clipboard
to_date ('2012-12-12', 'YYYY/MM/DD')
to_date ('2012-12-12', 'YYYY/M
1.
copy to clipboard
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Current_Date" FROM DU
AL;
SELECT TO_CHAR (SYSDATE,
20) What will be the syntax to find current date and time in
format "YYYY-MM-DD"?
copy to clipboard
SELECT TO_CHAR (SYSDATE, 'YYYY-MM-DD HH24:MI:SS') "Current_Date" FROM DUAL;
1)What is JSP?
Java Server Pages technology (JSP) is used to create dynamic web page. It is an
extension to the servlet technology. A JSP page is internally converted into servlet.
more details...
Description
It is invoked only once,
same as init method of
servlet.
It is invoked at each
request,ServletResponse)throws
ServletException,IOException
method of servlet.
Object
Type
1) out
JspWriter
2) request
HttpServletRequest
3) response
HttpServletResponse
4) config
ServletConfig
5) session
HttpSession
6) application
ServletContext
7) pageContext
PageContext
8) page
Object
9) exception
Throwable
more details...
include action
request time.
copy to clipboard
<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setHeader ("Expires", "0"); //prevents caching at the proxy server
%>
<%
response.setHeader("Cache-Co
response.setHeader("Pragma","
response.setHeader ("Expires",
%>
10) What are the two ways to include the result of another page.
?
There are two ways to include the result of another page:
By include directive
By include action
11) How can we forward the request from jsp page to the
servlet ?
Yes ofcourse! With the help of forward action tag, but we need to give the url-pattern of
the servlet.
forward action tag
12) Can we use the exception implicit object in any jsp page ?
No. The exception implicit object can only be used in the error page which defines it with
the isErrorPage attribute of page directive.
more details...
15) What are the different scope values for the <jsp:useBean>
tag?
There are 4 values:
1. page
2. request
3. session
4. application
more details...
Custom tags require quite a bit more work to set up than do beans.
Custom tags are available only in JSP 1.1 and later, but beans can be used in all
JSP 1.x versions.
2. jsp:setProperty
3. jsp:getProperty
more details...
1) What is SQL?
SQL stands for structured query language. It is a database language used for database
creation, deletion, fetching rows and modifying rows etc. sometimes it is pronounced as
se-qwell.
2) clustered index determines how data is stored physically in table. Actually clustered
index stores data in cluster, related data is stored together so it makes simple to retrieve
data.
3) reading from a clustered index is much faster than reading from non clustered index
from the same table.
4) clustered index sort and store data rows in the table or view based on their key value,
while non cluster have a structure separate from the data row.
14) What is self join and what is the requirement of self join?
Self join is often very useful to convert a hierarchical structure to a flat structure. It is
used to join a table to itself as like if that is the second table.
copy to clipboard
SELECT * FROM Employees WHERE EmpName like 'A%'
SELECT * FROM Employees WH
copy to clipboard
SELECT TOP 1 salary
2.
3.
4.
5.
6.
FROM (
SELECT TOP 3 salary
FROM employee_table
ORDER BY salary DESC ) AS emp
ORDER BY salary ASC;
SELECT TOP 1 salary
FROM (
SELECT TOP 3 salary
FROM employee_table
ORDER BY salary DESC ) AS em
No.
DELETE
TRUNCATE
1)
2)
DELETE command.
TRUNCATE
statement.
DELETE statement.
DELETE statement.
3)
4)
5)
Flexible structure
High performance
1.
copy to clipboard
SELECT CURRENT_DATE();
1.
copy to clipboard
select distinct(salary) from employee order by salary desc limit n-1,1
if you want to find 3rd largest salary:
1.
copy to clipboard
select distinct(salary) from employee order by salary desc limit 2,1
copy to clipboard
SELECT * FROM table_name LIMIT 0,20;
1.
2.
3.
copy to clipboard
SELECT NOW();
If you want to display current date only, use SELECT CURRENT_DATE();
1) What is Android?
Android is an open-source, linux-based operating system that is used in mobiles, tablets,
televisions etc.
Activity
View
Intent
Service
Content Provider
Fragment etc.
More details...
7) What is activity?
Activity is like a frame or window in java that represents GUI. It represents one screen of
android.
4. onPause()
5. onStop()
6. onRestart()
7. onDestroy()
More details...
9) What is intent?
It is a kind of message or information that is passed to the components. It is used to
launch an activity, display a web page, send sms, send email etc. There are two types of
intents in android:
1. Implicit Intent
2. Explicit Intent
copy to clipboard
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
2.
3.
4.
5.
There are 5 steps to connect any java application with the database in java using JDBC.
They are as follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection
copy to clipboard
public static void forName(String className)throws ClassNotFoundException
public static void forName(String
copy to clipboard
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("oracle.jdbc.driv
copy to clipboard
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
1) public static Connection getC
2) public static Connection getC
throw s SQLException
copy to clipboard
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Connection con=DriverManager
"jdbc:oracle:thin:@localhost:152
copy to clipboard
public Statement createStatement()throws SQLException
public Statement createStateme
1.
copy to clipboard
Statement stmt=con.createStatement();
Statement stmt=con.createState
copy to clipboard
public ResultSet executeQuery(String sql)throws SQLException
public ResultSet executeQuery(
copy to clipboard
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
ResultSet rs=stmt.executeQuer
w hile(rs.next()){
System.out.println(rs.getInt(1)+"
}
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
copy to clipboard
public void close()throws SQLException
public void close()throw s SQLE