Durga JAVA Interview Cre+adv+framework
Durga JAVA Interview Cre+adv+framework
These are fixed in size ie once we created an array object there is no chance
of increasing or decreasing size based on our requirement. Hence If we
don’t know size in advance , arrays are not recommended to use
Arrays can hold only homogeneous elements.
There is no underlying data structure for arrays and hence no readymade
method support for arrays. Hence for every requirement programmer has to
code explicitly
Collections
Arrays
1. Arrays r fixed in size and 1. Collections are growable in
hence once we created an array nature and hence based on our
we are not allowed to increase or requirement we can increase or
decrease the size based on our decrease the size.
requirement.
2. Memory point of view arrays 2. Memory point of view
are not recommended to use collections are recommended to
use.
3. Performance point of view 3. Performance point of view
arrays are recommended to use collections are not recommended
to use.
4. Arrays can hold only 4. Collections can hold both
homogeneous elements homogeneous and heterogeneous
elements.
5. Arrays can hold both 5. Collections can hold only
primitives as well as objects objects.
6. For any requirement, there is 6. For every requirement ready
no ready method support made method support is
compulsory programmer has to available. Being a programmer
code explicitly. we have to know how to use
those methods and we are not
responsible to implement those.
It defines set of classes and interfaces which can be used for representing a group
of objects as single entity
It defines set of classes and inter faces which can be used for representing a group
of objects as single entity
All the objects are arranged in some sorting order (Can be natural sorting
order or customizede).
Duplicates are not allowed.
It is child interface of SortedSet and provides several utility methods for navigation
purposes
If we want to represent a group of objects as key value pairs where all the
entries are arranged according some sorting order of keys then we should go
for SortedMap.
It is child interface of Map.
It has introduced in 1.2 version
Vector
ArrayList
1. No method is synchronized in 1. All methods in Vector are
the ArrayList class synchronized.
2. ArrayList object is not thread 2. Vector is thread safe.
safe.
3. Relatively performance is high 3. Relatively performance is low
4. Introduced in 1.2 version and it 4. Introduced in 1.0 version and it
is non legacy is legacy
EX
ArrayList l= new ArrayList();
List l2=Collections.synchronizedList(l);
Similarly we can get synchronized versions of Set and Map objects by the
following methods.
ArrayList LinkedList
1. The underlying data structure 1. The underlying data structure
is resizable or growable array. is Double Linked List.
2. This is Best choice if frequent 2. This is Best choice if frequent
operation is retrieval and worst operation is insertion or deletion
choice if frequent operation is in the middle and worst choice if
insertion or deletion in the frequent operation is retrieval .
middle.
3. This class implements 3. This class implements
Serializable , Cloneable and Serializable , Cloneable but
RandomAccess interfaces. not RandomAccess interface.
Q25. What are legacy classes and interfaces present in Collections framework
?
Enumeration ---Interface
Dictonary ------Abstract class
Hashtable -----Concrete class
Properties -----Concrete class
Vector -----Concrete class
Stack -----Concrete class
Enumeration Iterator
1. It is legacy interface and 1 It is non-legacy and introduced
introduced in 1.0 version in 1.2 version
2Applicable only for legacy 2Applicable for any Collection
classes and it is not universal implemented class object.
cursor
3While iterating the elements we 3While iterating we can perform
are not allowed to remove the removal also in addition to read
objects just we can perform only operation.
read operation
4By using elements() method we 4. By using iterator() method we
can get Enumeration object can get Iterator
object
An enum can be used to define a group of named constants .It has introduced in
1.5 version
Ex
Class Beer{
KO,KF,RC,FO
}
Q32. If we are trying to insert duplicate values in Set what will happen?
If we are trying to insert duplicate objects to the HashSet , we wont get any
compile time or run time errors just the add(Object o) returns false and it doesn’t
add that object.
In the case of HashSet insertion order is not preserved , but in the case of
LinkedHashSet insertion will be preserved.
HashSet LinkedHashSet
1The Underlying datastructure is 1The underlying datastructure is
Hashtable combination of LinkedList and
Hashtable
2Insertion Order is not preserved 2 Insertion order is preserved.
3Introduced in 1.2 version 3 Introduced in 1.4 version
Q35. What are major enhancements in 1.4 version of collection frame work?
LinkedHashSet
LinkedHashMap
IdentityHashMap
Q36. Explain about TreeSet?
List Set
1Insertion Order is preserved 1Insertion Order is not preserved
2Duplicate Objects are allowed 2 Duplicate Objects are not
allowed
3The implemented classes are 3 The implemented classes are
ArrayList,LinkedList , Vector HashSet, LinkedHashSet
and Stack classes and Tree
This interface can be used for defining natural sorting order of the objects.
It is present in java.lang package
It contains a method public int compareTo(Object obj1)
Comparable Comparator
1This can be used for natural 1This can be used for
sorting order implementing customized sorting
2This interface present in 2 This is present in java.util
java.lang package package
3Contains only one method: 3 It contains two methods.
public int compare(Object
public int compareTo(Object ,Object)
obj1) public Boolean equals(Object)
4 It is marker interface 4 It is not a marker interface.
HashSet TreeSet
1The underlying data structure is 1The underlying data structure is
Hashtable balanced tree
2Heterogeneous objects are 2 Heterogeneous objects are
allowed not allowed bydefalut
3Insertion order is not preserved 3 Insertion order is not
and it is based on hashcode of the preserved and all the objects are
objects inserted according to some
sorting order.
4null insertion is possible 4 As the first element only null
insertion is possible and in all
other cases we will get
NullPointerException
interface Map{
//more code here
interface Entry{
Object getKey()
Object getValue()
Object setValue(Object new)
}
}
In the case of HashMap the insertion order is not preserved but in the case of
LinkedHashMap insertion order is preserved. Introduced in 1.4 version
HashMap LinkedHashMap
1.The underlying data structure is 1.The underlying data structure is
Hashtable a combination of Hashtable and
linkedlist
2.Insertion order is not preserved 2 Insertion order is preserved
and it is based on hashcode of
keys
3.Introduced in 1.2 version 3 Introduced in 1.4 version.
HashMap Hashtable
1.The underlying data structure is 1.The underlying data structure
Hashtable of Hashtable
2.No method is synchronized and 2 .All methods are synchronized
hence HashMap object is not and hence it is thread safe
thread safe
3.Performance is high 3. Performance is low
4.null insertion is possible for 4. null insertion is not possible
both keys and values for both key and value violation
leads to NullPointerException
5.Introduced in 1.2 version and it 5. Introduced in 1.0 version and
is non legacy it is legacy
In the HashMap JVM uses equals() method to identify duplicate keys but in
the case of IdentityHashMap JVM uses == operator for this.
TreeMap can be used to store a group of objects as key-value pairs where all the
entries are arranged according to some sorting order of keys.
Hashtable is a legacy Map and can be used to store objects as key value pairs.
All methods present in the Vector are synchronized and hence any method can be
executed by only one thread at a time. It slows down the execution.
INNER CLASSES……………….
Some times we can declare a class inside another class such type of classes are
called inner classes
Example
Class Car{
Class Engine{
Without existing Car object there is no chance of existing Engine object, hence
Engine class has declared inside Car class.
Sometimes we can declare a class inside a method such type of classes are
called method local
inner classes
The main purpose of method local inner classes is to define method specific
functionality
The scope of method local inner classes is the scope of the method where it
is declared.
Example
class Test{
class Inner {
System.out.println(i+J);
}//sum
}//inner
i.sum(10,20);
I.sum(100,303);
//more code here
i.sum(102,84);
}//m1()
New Test().m1();
Some times we can declare a inner class without name such type of inner
classes are called
Example
Class popcorn{
System.out.println(“it is salty”);
}
//more code here
Class Test{
System.out.println(“it is sweet”);
example
class Test{
System.out.printin(“child thread”);
};
t.start();
for(int i=0;i<10;i++){
System.out.printin(“main thread”);
Don’t become fool that here we are creating object of interface Runnable.Here
we are actually
Example
Class Test{
for(int i=0;i<10;i++){
System.out.printin(“child thread”);
}).start();
for(int i=0;i<10;i++){
System.out.printin(“main thread”);
}//main
}//Test
5. With out having name of class how we can create an object and utilize the
functionality of Anonymous inner class?
anonymous inner class can extend a class or can implement an interface one
at a time but not
both simultaneously.
7. What is difference between normal inner class and static nested class?
8. What is static nested class ? Why the term nested instead of inner in static
nested class?
Some times we can declare inner class with static modifier such type of
inner class are called static
Nested classes. The term nested instead of static because without existing
outer class object inner
Example
Class outer {
Java Outer
O/P
Java Outer$Nested
O/P
No it is not possible to declare main () inside inner class but in static nested
class it is possible for
===========================================================
============================================
EXCEPTION=================================================
=====
Q1.What is an Exception?
Ans. An unwanted, unexpected event that disturbs normal flow of the program is
called Exception. Example: FileNotFondException.
Ans.
Description
Q10.If an exception rised inside catch block then what will happen?
Ans. If an exception raised inside catch block and it is not part of any try block
then it is always abnormal termination.
Q17. If return statement present inside try is finally block will be executed?
Ans. Yes, if return statement present inside try, then also finally block will be
executed. finally block will dominate return statement also.
Example2:
Class Test{
Public static void main(String[] args){
Throw new ArithmeticException(“/by Zero”);
}
}
In this case creation of an exception object and handover to the JVM
explicitly by the programmer.
Q32. Which class act as root for entire java Exception hierarchy?
Ans. Throwable class act as root for entire java Exception hierarchy.
Q33. What is the difference between Error and Exception?
Ans. Throwable class contain two child classes.
Exception:- These are mostly caused by our program and are recoverable.
Error:- These are not caused by our program, mostly caused by lake of
system resources. These are non recoverable.
Ans. In the case of t.start () method, a new thread will be created which is
responsible for the execution of run () method.
But in the case of t.run () method no new thread will be created main
thread executes run () method just like a normal method call.
Q8. Explain about Thread Scheduler?
Ans. If multiple threads are waiting for getting the chance for executing then
which thread will get chance first decided by Thread Scheduler. It is the part of
JVM and its behavior is vendor dependent and we can’t expect exact output.
Whenever the situation comes to multithreading the guarantee behavior is very-
very low.
Ans. Once we create a Thread object then the Thread is said to be in New/Born
state once we call t.start() method now the Thread will be entered into
ready/Runnable state that is Thread is ready to execute. If Thread Scheduler
allocates CPU now the Thread will entered into the Running state and start
execution of run() method. After completing run() method the Thread entered into
Dead State.
Q23. If we are trying to set priority of a Thread as 100 what will happen?
Ans. If we are trying to set priority of a Thread as 100 then we will not get any
compile time error but at the runtime we will get Runtime exception
IllegalArgumentException. Because the valid range of the Thread priority is (1-10)
only.
Q24. If two threads having same priority then which thread will get chance
first for execution?
Ans. If two threads having same priority then which thread will get the chance
first for execution decided by Thread Scheduler. It is the part of JVM and its
behavior is vendor dependent and we can’t expect exact output.
Q25. If two threads having different priority then which thread will get
chance first for execution?
Ans. If two threads having different priority then the Thread which is having
highest priority will get chance first for execution.
1. Yield()
2. Join()
3. Sleep()
There is no relationship between object lock and class level lock, both
are independent.
Q35. While a thread executing any synchronized method on the given object is
it possible to execute remaining synchronized method of the same object
simultaneously by any other thread?
Ans. No, it is no possible.
Q36. What is the difference between synchronized method and static
synchronized method?
Ans. If a Thread wants to execute a synchronized method first it has to get
the lock of the object. Once a Thread got the lock then it is allow to execute
any synchronized method on that object. If a Thread wants to execute static
synchronized method that Thread has to get class level lock once a Thread got
class level lock then only it is allow to execute static synchronized method.
Q39. How we can declare synchronized block to get class level lock?
Ans. To get the class level lock we can declare synchronized block as follows:
synchronized(Display.class)
{
}
Q43.If a waiting thread got notification then it will entered into which state?
Ans. It will entered into another waiting state to get lock.
Q44.In which method threads can release the lock?
Ans. Once a Thread calls wait() method it immediately releases the lock of that
object and then entered into waiting state similarly after calling notify() method
Thread releases the lock but may not immediately. Except these three methods(
wait(), notify(), notifyAll() ) method Thread never releases the lock anywhere else.
Q47. Once a Thread got the notification then which waiting thread will get
chance?
Ans. It is depends on the Thread Scheduler.
Query Tokenization: This phase will take SQL query as an input and divide
into stream of tokens.
Query Parsing: This phase will take stream of tokens as an input, with them
it tried to construct a query tree. If query parser constructs query tree
successfully then it was an indication that no grammatical mistakes in the
taken SQL query. Otherwise there are some syntactical errors in the taken
SQL query.
Query Optimization: This phase will take query tree as an input and
performs number of query optimization mechanisms to reduce execution
time and memory utilization.
Query Execution: This phase will take optimized query as an input and
executes that SQL query by using interpreters internally as a result we will
get some output on the SQL prompt.
3: What is Driver? How many Drivers are available in JDBC? What are the
types?
Driver:
Types of Drivers:
There are 180+ number of Drivers in the market. But all these Drivers
could be classified into the following 4 types.
Type 1 Driver
Type 2 Driver
Type 3 Driver
Type 4 Driver
Type 1 Driver:
Advantages:
This Driver is already available with java software that’s why no need to
bother about how to get the Driver implementation explicitily.
Allmost all the databases could support this Driver.
Dis advantages:
This Driver internally depends on Odbc Driver that’s why it is not suitable
for internet or web applications or network applications.
This Driver is a slower Driver, why because Jdbc-Odbc Driver will convert
java calls to Odbc calls. Then Odbc Driver has to convert Odbc calls to
query language calls.
This driver is not portable Driver why because it was not complete the java
implementations in Jdbc-Odbc Driver.
It we want to use Jdbc-Odbc Driver in our jdbc applications then we must
require to install Odbc-Native Library.
Type 2 Driver:
Type 2 Driver is also called as “part java part native Driver”. i.e., this
Driver was designed by using some part of the java implementations and some
other part of the database vendor provided native implementations. This Driver is
also called as “native driver”.
Advantages:
When compared to Type 1 driver it is efficient driver why because Type 2
driver directly will convert java api calls to database vendor api calls.
Dis advantages:
Type 3 Driver:
Advantages:
Dis advantages:
Type 4 Driver:
o This driver is also called as pure java driver i.e, this driver was
completely implemented by using java technology.
o When compared to Type1, Type2 and Type3 drivers.. Type4 driver is
portable driver.
o Type4 driver can be used for any kind of applications.
o Type4 driver is a cheapest driver when compared to all the drivers
that’s why it is frequently used driver.
4: What is JDBC and What are the steps to write a JDBC application?
The process of interacting with the database from a java application is called as
JDBC(Java Database Connectivity)
To interact with the database from a java application we will use the following
five steps.
o In general sun Microsystems has provided Driver interface for this all
the database vendors has provided their own implementation.
o If we want to use the database vendor provided Driver implementation
to our jdbc application, first we need to make the availability of the
respective Driver’s .class file to JVM, for this we need to set class
path environment variable to the location where we have the driver
implementation.
o Sun Microsystems is also provided an implementation to the Driver
interface in the form of JdbcOdbcDriver class as part of the java
software.
o If we want to use JdbcOdbcDriver in our jdbc applications no need to
set class path environment variable. Why because it was already
available in the java software’s pre-defined library.
o JdbcOdbcDriver internally depends on the mocrosoft product Odbc
driver. If we want to use the JdbcOdbcDriver in our jdbc applications
first we must configure Odbc driver, for this we will use the following
path.
To load the driver’s class byte code to the memory we will use the following
method.
Eg: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Where forName() is a static method, which can be used to load the respective
driver class byte code to the memory.
Each and every driver class has already a static block at the time of loading
the respective driver class byte code to the memory automatically the
available static block could be executed, by
this DriverManager.registerDriver(….) method will be executed as part of
the static block.
By the execution of the registerDriver(….) method automatically the
specified driver will be register to the jdbc application.
If you want to design any jdbc application, we need to use some pre-defined
library, which was provided by the Jdbc API in the form of java.sql package,
that’s why we need to import java.sql package in our jdbc application.
Connection con=
DriverManager.getConnection(“jdbc:odbc:nag”,”nag”,”system”,”manager”);
Note:- Anonymous inner class is a nameless inner class, which can be sued to
provide an implementation either for the interfaces or for abstract classes.
Eg: interface I
{
void m1();
}
Class Outer
{
I i = new I(){
public void m1()
{
}
public void m2()
{
}
}
}
Outer o = new Outer();
o.i.m1(); à correct
o.i.m2(); à wrong
getConnection(_) is a static method from DriverManager class,
which will call internally connect() method, this connect() will establish a virtual
socket connection in between the java application and the database.
8: What is the requirement to use Statement object?
To execute the sql queries we will use the following methods from Statement
object.
st.executeQuery(…)
st.executeUpdate(…)
st.execute(…)
where execute() can be used to execute either selection group sql queries or
updation group queries.
When we use selection group sql query with the execute() then we will get
ResultSet object at heap memory with the fetched data. But execute() will return
“true” as a Boolean value.
When we use updation group sql query with execute() then we will get “
records updated count value” at jdbc application. But execute() will return “false”
as a Boolean value.
//import section
import java.sql.*;
import java.io.*;
import java.sql.*;
import java.io.*;
public class InsertTableEx
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection
con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:x
e”,”system”,”durga”);
Statement st = con.createStatement();
while(true)
{
System.out.println(“Enter emp number”);
Int eno = Integer.parseInt(br.readLine());
System.out.println(“Enter emp name”);
String ename = br.readLine();
System.out.println(“Enter emp sal”);
Float esal = Float.parseFloat(br.readLine());
System.out.println(“Enter emp address”);
String eaddr = br.readLine();
st.executeUpdate(“insert into emp1
values(“+eno+”,’”+ename+”’,”+esal+”,’”+eaddr+”’)”);
System.out.println(“read successfully inserted”);
System.out.println(“one more record[y/n]);
String option = br.readLine();
If(option.equals(“n”))
break;
}
}
}
import java.sql.*;
public class UpdateTableEx
{
public static void main(String[] args)throws Exception
{
//load n register the driver in alternative way to Class.forName
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con =
DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xee”,”system”,”
durga”);
Statement st = con.createStatement();
int updateCount = st.executeUpdate(“update emp1 set esal = esal+500 where
esal<9000”);
System.out.println(“records updated……..”+updateCount);
con.close();
}
}
Connection con =
DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”d
urga”);
Statement st = con.createStatement();
int updateCount = sst.executeUpdate(“delete from emp3 where
esal>=7000”);
System.out.println(“records deleted………”+updateCount);
con.close();
}
}
15:What is ment by ResultSet object and How to Fetch the Data from Database?.
ResultSet:-
ResultSet is an Object which can be used to maintain the fetched data from
database in the JDBC applications
When we execute a selection group sql query, either with executeQuety() or with
execute() automatically a ResultSet object will be created at heap memory with the
fetched data from database.
After getting ResultSet cursor to a record position then we need to get the
data from respective fields of the particular record, for this we will use
following method.
Eg: while(rs.next())
{
System.out.println(rs.getInt(1)+” ”+rs.getString(2)+” ”+rs.getFloat(3)+” ”+rs.g
etString(4));
}
The following example demonstrates how to fetch the data from database
through ResultSet object.
import java.sql.*;
public class FetchEx
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(“select * from emp1”);
System.out.println(“ENO ENAME ESAL EADDR”);
System.out.println(“********************************”);
while(rs.next())
{
System.out.println(rs.getInt(1)+””+rs.getString(2)+” ”+rs.getFloat(
3)+” ”+rs.getString(4));
}
}
}
Execute() can be used to execute both selection group sql query and
updation group sql query.
If we use execute() to execute a selection group sql query then
DBE(Database engine) will execute that sql query and send back the
fetched data from database to java application. Now java application will
prepare a ResultSet object with the fetched data but execute() will return
“true” as a Boolean value.
At this situation to get the reference of the ResultSet object explicitily, we
will use the following method from Statement object.
Execute() can be used to execute both selection group sql queries and
updation group sql queries.
If we use execute() to execute an updation group sql query then DBE will
execute it and send back the records updated count value to the java
application. But execute() will return “false” as a Boolean value. At this
instance, to get the records updated count value explicitly we will use the
following method from Statement object.
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
Statement st = con.createStatement();
boolean b = st.execute(“update emp1 set esal=esal+500 where esal<9000”);
System.out.println(b);
int updateCount = st.getUpdateCount();j
System.out.println(updateCount);
}
}
If we handle the above exception properly then we will get ResultSet abject and we
will get the data from Database
import java.sql.*;
class Test
{
public static void main(String[] args)
{
Statement st=null;
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
st = con.createStatement();
boolean b = st.executeUpdate(“select * from emp1”);
}
catch(Exception e)
{
ResultSet rs=st.getResultSet();
System.out.println(“ENO ENAME ESAL EADDR”);
System.out.println(“********************************”);
while(rs.next())
{
System.out.println(rs.getInt(1)+””+rs.getString(2)+” ”+rs.getFloat(
3)+” ”+rs.getString(4));
}
e.printStackTrace();
}
import java.sql.*;
class Test
{
public static void main(String[] args)
{
Statement st=null;
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
st = con.createStatement();
boolean b = st.executeQuery(“update emp1 set esal=esal+1000 where esal
<10000”);
}
catch(Exception e)
{
int count=st.getUpdateCount();
System.out.println(count);
e.printStackTrace();
}
20: What is ment by ResultSet and What are the types of ResultSets are available
in JDBC application?
Read only ResultSet:- It is a ResultSet, which will allow the users to read
the data only. To refer this ResultSet, we will use the following constant from
ResultSet interface.
Forward only ResultSet:- It is a ResultSet object, which will allow the users to
iterate the data in any forward direction. To refer this ResultSet object we will use
the following constant from ResultSet interface.
Scrollable ResultSet:- These are the ResultSet objects, which will allow the users
to iterate the data in both forward and backward directions.
There are 2 types of Scrollable ResultSets.
Scroll insensitive ResultSet is a ResultSet object, which will not allow later
updations from database after creating it. To refer this ResultSet we will use the
following constant from ResultSet interface.
22:What is the default ResultSet type in JDBC application and How it is possible
to create a specific type of ResultSet object?
The default ResultSet type in the jdbc applications is Read only and forward
only.
In jdbc applications we are able to specify the following types of the
ResultSet combination to any particular ResultSet.
to iterate the data in forward direction from a ResultSet object we will use
the following 2 methods.
The following example demonstrates how to iterate the data in both forward
and backward direction from the ResultSet object
import java.sql.*;
public class ScrollResEx
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCU
R_UPDATABLE);
ResultSet rs = st.executeQuery(“select * from emp1”);
System.out.println(“data in forward direction”);
System.out.println(“ENO ENAME ESAL EADDR”);
System.out.println(“**********************************”);
While(rs.next())
{
System.out.println(rs.getInt(1)+” ”+rs.getString(2)+” ”+rs.getFloat(3)+” ”+rs
.getString(4));
}
System.in.read();
System.out.println(“data in backward direction”);
System.out.println(“ENO ENAME ESAL EADDR”);
System.out.println(“***********************************”);
While(rs.previous())
{
System.out.println(rs.getInt(1)+” ”+rs.getString(2)+” ”+rs.getFloat(3)+” ”+rs
.getString(4));
}
}
}
24: how to generate ScrollSensitive Result Set and how to reflect the later
updations from database automatically to the ResultSet object?
import java.sql.*;
public class Test
{
Public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCU
R_UPDATABLE);
ResultSet rs = st.executeQuery(“select * from emp1”);
rs.next();
System.out.println(“old salary emp111…….”+rs.getFloat(3));
System.in.read();//application is in pause, perform database updations
Rs.refreshRow();
System.out.println(“new salary of emp111……..”+rs.getFloat(3));
}
}
Where xxx may be byte, short, int, char, double, float, long.
Step4: Make the temporary insertion as the permanent insertion in Updatable
ResultSet object as will as in database, for this we will use the following method.
public void insertRow()
The following example demonstrates how to insert no. of records onto the
database through Updatable ResultSet objects.
import java.sql.*;
import java.io.*;
public class UpdateResEx
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCU
R_UPDATABLE);
ResultSet rs = st.executeQuery(“select * from emp1”);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
rs.moveToInsertRow();
while(true)
{
System.out.println(“enter employee number”);
int eno = Integer.parseInt(br.readLine());
System.out.println(“enter employee name”);
String ename = br.readLine();
System.out.println(“enter employee salary”);
float esal = Float.parseFloat(br.readLine());
System.out.println(“enter employee address”);
String eaddr = br.readLine();
rs.updateInt(1,eno);
rs.updateString(2,ename);
rs.updateFloat(3,esal);
rs.updateString(4,eaddr);
rs.insertRow();
System.out.println(“record successfully inserted”);
System.out.println(“one more record[y/n]);
String option = br.readLine();
if(option.equals(“n”))
break;
}
}
import java.sql.*;
public class UpdateResEx1
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCU
R_UPDATABLE);
ResultSet rs = st.executeQuery(“select * from emp1”);
rs.absolute(3);
float newsal = rs.getFloat(3)+500;
rs.updateFloat(3,newsal);
rs.updateRow();
}
}
Data about the data is called as Metadata. Similarily data about the data available
in ResultSet object called as “ResultSet Metadata”.
To get the number of columns available in ResultSet object we will use the
following method from ResultSetMetaData object.
To get the name of a particular column, we will use the following method.
To get the column datatype of a particular column, we will use the following
method
To get the column display size of a particular column we will use the
following method.
import java.sql.*;
public class ResultSetMD
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(“select * from emp1”);
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
System.out.println(“number of columns......”+count);
for(int i=1;i<=count;i++)
{
System.out.println(rsmd.getColumnName(i)+” “+rsmd.getColumnTypeName(i)+”
“+rsmd.getColumnDisplaySize(i));
System.out.println()
}
}
}
28: how to display the data with the respective field names
import java.sql.*;
public class RSMD1
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCU
R_UPDATABLE);
ResultSet rs = st.executeQuery(“select * from emp1”);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println(rsmd.getColumnName(1)+” “+rsmd.getColumnName(2)+”
“+rsmd.getColumnName(3)+” “+rsmd.getColumnName(4));
System.out.println(“********************************”);
while(rs.next())
{
System.out.println(rs.getInt(1)+” “+rs.getString(2)+” “rs.getFloat(3)+” “+rs.g
etString(4));
}
}
}
When we have a requirement to execute same kind of sql query in the next
sequence then we should go for PreparedStatement over Statement object.
For the above requirement if we use Statement object, every time execution
of the same sql query DBE must perform query tokenization, query parsing,
query optimization and query execution.
This approach will increase burden to the DBE. To reduce burden to the
DBE we should go for an alternative. That is PreparedStatement over
Statement object.
For the same requirement if we use PreparedStatement object then for our
complete requirement DBE will go for only one time query parsing
(tokenization, parsing, optimization and execution);
where xxx may be byte, short, char, int, long, float, double.
Eg: pst.setInt(1,111);
pst.setString(2,”abc”);
When JVM encounters the above method then jvm will set the specified
values to the specified parameters at the PreparedStatement object, intern that
parameter values could be reflected to query plan.
If the generalized sql query belongs to selection group then we will use
following method from PreparedStatement object
If the generalized sql query belongs to updation group then we will use the
following method.
import java.sql.*;
import java.io.*;
public class PreparedInsertEx
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
PreparedStatement pst= con.prepareStatement(“insert into emp1 values(?,?,?,?)”);
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
while(true)
{
; }
}
31: how to update the database through PreparedStatement object.
import java.sql.*;
public class PreparedUpdateEx
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
PreparedStatement pst = con.prepareStatement(“update emp1 set esal = esal+?
Where esal<?”);
Pst.setInt(1,500);
Pst.setFloat(2,10000.0f);
Int count = pst.executeUpdate();
System.out.println(“no. of records updated:”+count);
}
}
import java.sql.*;
public class UpdateResEx
{
public static void main(String[] args)throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
PreparedStatement pst = con.prepareStatement(“select * from emp1 where
esal<=?”);
Pst.setFloat(1,10000.0f);
ResultSet rs = pst.executeQuery();
System.out.println(“ENO ENAME ESAL EADDR”);
System.out.println(“******************************”);
While(rs.next())
{
System.out.println(rs.getInt(1)+” “+rs.getString(2)+” “+rs.getFloat(3)+” “+r
s.getString(4));
}
}
}
Where atomicity is nothing but perform all the operations or not to perform
all the operations in a transaction. That is every transaction must be in either
success state or failure state.
As part of the jdbc applications when we establish a connection
automatically the connection should have a default nature called as “auto
commit”.
Auto commit in the sense when we send an sql query to the connection then
connection will carry that to the DBE and make the DBE to execute
provided sql query and store the results on the database permanently.
The connections default auto commit nature violates the transactions
atomicity property.
To preserve transactions atomicity property we should change the
connections auto commit nature to non-auto commit nature, for this we will
use the following method.
If we use connections non auto commit nature in our jdbc applications then
we must use either commit or rollback operations explicitily as part of the
transactions.
Public void commit()
Public void rollback()
import java.sql.*;
public class TransactionEx
{
public static void main(String[] args)throws Exception
{
Connection con = null;
try
{
Class.forName(“sun.jdbc.odbd.JdbcOdbcDriver”);
Con = DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”durga”);
con.setAutoCommit(“false”);
Statement st = con.createStatement();
st.executeUpdate(“insert into emp1 values(888,’fff’,8000,’hhh’)”);
st.executeUpdate(“update emp1 set esal = esal-500 where esal>= ‘abc’ “);
st.executeUpdate(“delete emp1 where esal<7000”);
con.commit();
}
catch(Exception e)
{
con.rollback();
System.out.println(e);
}
}
}
Save point is a concept introduced by jdbc 3.0 which can be used to block a
set of instructions execution in the transactions committing operation.
To set a save point we will use the following method.
To block a set of sql queries execution prior to the save point we will use the
following method.
public void rollback(savepoint s)
Eg:
import java.sql.*;
public class SavePointEx
{
public static void main(String[] args)throws Exception
{
Connection con = null;
try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
con =
DriverManager.getConnection(“jdbc:oracle:thin:@locajhost:1521:xe”,”system”,”d
urga”);
con.setAutoCommit(“false”);
Statement st = con.createStatement();
st.executeUpdate(“insert into emp1 values(111,’fff’,8000,’hhh’)”);
savepoint sp= con.Savepoint();
st.executeUpdate(“insert into emp1 values(222,’ggg’,7000,’iii’) “);
con.rollback(sp);
st.executeUpdate(“insert into emp1 values(333,’hhh’,9000,’jjj’)”);
con.commit();
}
catch(Exception e)
{
con.rollback();
System.out.println(e);
}
}
}
===========================================================
================================================JSP========
=========================
No
5 What are the advantages of JSP over Servlet?
Servlets JSP
1. Best suitable for 1. Best suitable for
processing logic presentation logic
2. we cannot separate 2. Separation of presentation
business and presentation and business logic is possible
logic
3. Servlet developer should 3.JSP author is not required
have strong knowledge in to have strong knowledge in
Java Java
4. For source code changes 4. For source code changes ,it
,we have to perform is not required to perform
explicitly compilation explicit compilation
5. Relatively development 5. Relatively development
time is more time is less
The big difference between both of these technologies lies with the design of the
software. JSP technology is server and platform independent whereas ASP relies
primarily on Microsoft technologies.
If the JSP is secured resource then we can place inside WEB-INF folder so that end
user is not allowed to access directly by the name. We can provide the url pattern
by configuring in web.xml
<web-app>
<servlet>
<servlet-name>Demo JSP</servlet-name>
<jsp-file>/WEB-INF/test.jsp</jsp-file>
<sevlet>
<servlet-mapping>
<servlet-name>Demo JSP</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
..
</web-app>
1. JspPage:
This interface defines the two life cycle methods jspInit() and jspDestroy().
1. HttpJspPage:
This interface defines only one life cyle method _jspService() method.
Every generated servlet for the jsps should implement either JspPage or
HttpJspPage interface either directly or indirectly.
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is
called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it
the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of
service. It is the last method called n the servlet instance.
JSP contains three life cycle methods namely jspInit( ), _jspService() and
jspDestroy(). In these, jspInit() and jspDestroy() can be overridden and we cannot
override _jspService().
To show this difference _jspService() method is prefixed with ‘_’ by the JSP
container and the other two methods jspInit() and jspDestroy() has no special
prefixes.
18. How can I override the jspInit() and jspDestroy() methods within a JSP
page?
By using JSP declation tag
<%!
public void jspInit() {
...
}
%>
<%!
public void jspDestroy() {
...
}
%>
A java server page is executed within a Java container. A Java container converts a
Java file into a servlet. Conversion happens only once when the application is
deployed onto the web server. During the process of compilation Java compiler
checks for modifications if any modifications are present it would modify and then
execute it.
20 . Why is _jspService() method starting with an '_' while other life cycle
methods do not?
_jspService() method will be written by the container hence any methods which
are not to be overridden by the end user are typically written starting with an '_'.
This is the reason why we don't override _jspService() method in any JSP page.
http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
It causes excution of JSP life cycle until jspInit() method without executing
_jspService() method.
It removes the start-up lag that occurs when a container must translate a JSP page
upon receipt of the first request.
Syntax:
<%
%>
The java code present in the scriptlet will be placed directly inside
_jspService() method .
25. What is a JSP declarative?
JSP declarations are used to declare class variables and methods (both instance and
static) in a JSP page. These declations will be placed directly at class level in the
generated servlet and these are available to the entire JSP.
Syntax:
<%!
public int add(inti,intj){
return i+j;
}
%>
27. What is the difference b/w variable declared inside a declaration and
variable declared in scriplet ?
Variable declared inside declaration part is treated as a instance variable and will
be placed directly at class level in the generated servlet.
<%
int k = 10;
%>
What is a Expression?
The expression value will become argument to the out.pritln() method in the
generated servlet
28.What are the three kinds of comments in JSP and what's the difference
between them?
1. JSP Comment:
This is also known as hidden comment and it is visible only in the JSP and in rest
of phases of JSP life cycle it is not visible.
1. HTML Comment:
This is also known as template text comment or output comment. It is visible in all
phases of JSP including source code of generated response.
1. Java Comments.
<%
// single line java comment
/* this is multiline comment */
%>
This type of comments also known as scripting comments and these are visible in
the generated servlet also.
This is also known as JSP comment and it is visible only in the JSP and in rest of
phases of JSP life cycle it is not visible.
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
Implicit objects are by default available to the JSP. Being JSP author we can use
these and not required to create it explicitly.
1. request
2. response
3. pageContext
4. session
5. application
6. out
7. config
8. page
9. exception
You can use the errorPage attribute of the page directive to have uncaught
run-time exceptions automatically forwarded to an error processing page.
For example:
<%@ page errorPage="error.jsp" %> redirects the browser to the JSP page
error.jsp if an uncaught exception is encountered during request processing.
34. How can I implement a thread-safe JSP page? What are the advantages
and Disadvantages of using it?
You can make your JSPs thread-safe by having them implement the
SingleThreadModel interface. This is done by adding the directive in the JSP.
The generated servlet can handle only one client request at time so that we can
make JSP as thread safe. We can overcome data inconsistency problems by this
approach.
1. language
2. extends
3. import
4. session
5. isThreadSafe
6. info
7. errorPage
8. isError page
9. contentType
10.isELIgnored
11.buffer
12.autoFlush
13.pageEncoding
41 . Explain about autoflush?
42. How do you restrict page errors display in the JSP page?
You first set "errorPage" attribute of PAGE directive to the name of the error page
(ie errorPage="error.jsp")in your jsp page .
Then in the error.jsp page set "isErrorpage=TRUE".
When an error occur in your jsp page, then the control will be automatically
forward to error page.
If we want to make our data available to the entire application then we have to use
application scope.
45. What are the different scope valiues for the <jsp:useBean>?
1. page
2. request
3.session
4.application
jsp:useBean action may optionally have a body. If the body is specified, its
contents will be automatically invoked when the specified bean is instantiated.
Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the
newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to
the current date when it is instantiated. Note that here, we make use of a JSP
expression within the jsp:setProperty action.
</jsp:useBean >
No problem! The use Bean action specifies the beanName attribute, which can be
used for indicating a serialized bean.
For example:
A couple of important points to note. Although you would have to name your
serialized file "filename.ser", you only indicate "filename" as the value for the
beanName attribute. Also, you will have to place your serialized file within the
WEB-INF/jspbeans directory for it to be located by the JSP engine.
We can include static files in JSP by using include directive (static include)
1. By include directive:
The content of the header.jsp will be included in the current jsp at translation
time. Hence this inclusion is also known as static include.
1. By include action:
The response of the jsp will be included in the current page response at request
processing time(run time) hence it is also known as dynamic include.
<%
pageContext.include(“/header.jsp”);
%>
<%
RequestDispatcher rd = request.getRequestDispatcher(“/header.jsp”);
Rd.incliude(request,response);
%>
50.In which situation we can use static include and dynamic include in JSPs ?
If the target resource ( included resource) won’t change frequently, then it is
recommended to use static include.
<%@ include file=”header.jsp” %>
===========================================================
=================================================SERVLET==
=======================================
Q20.By using which object we can send text data as response from the
Servlet?
Q21.By using which object we can read binary data send by the client?
Q22.By using which object we can send binary data send as response from
the Servlet?
Q24.Explain the purpose of the init() method & How many times it will be
Q25.If init() method throws any Exception i.e; if init() method fails to
constructor?
constructor?
Q29.What is the purpose of service() & How Many times it will be
Executed?
time?
loaded first?
Q55.If you are sending Get request but our Servlet doesn't contain doGet()
what happen?
Q61.By using which method we can get client &server information from
the request?
Q65.Is it possible to send multiple content type as response from the same
servlet?
simultaneously?
Q70.How many times we can call sendRedirect() method with in the same
Servlet?
Q78.If the required class file available in classes folder and lib folder jar
Q79.Is there any alternate location to place servlet .class file Other than
classes folder?
Q90.With in the servlet how we can access logical name of the servlet?
parameter?
ServletConfig interface?
disadvantages?
happen?
Q95.How many types of url patterns are possible according to Servlet
specification?
take?
Servlet?
Configuration in web.xml?
in the Servlet?
attributes?classhierarchy?
1. a) Adding an attribute?
3. c) Remove an attribute?
everywhere with in the web application, then what is the need of session
required?
FilterChain doFilter()?
Q141.Explain the cases where you used filters & wrappers in your
previous project?
Q142.What is the need of Session Management? Explain cases
<SetMaxInactiveInterval>?
approach is recommended?
cookies?
Management technique?
1. cookies
2. URL Writing
3. Session API
Q162.Explain the purpose of Listener?
specification?
ServletRequestAttributeListener?
Q166.To print hit count of the web application which listener is required to
use?
Q167.To print the no of active session objects at server side which listener
is responsible?
web.xml?
Q175.If you are configures more than one listener of the same type then in
security?