Sei sulla pagina 1di 19

1. What are the java features?

1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The confusing
and ambiguous concepts of C++ are either left out in Java or they have been re-implemented in
a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C++
2) Object Oriented
In java everything is Object which has some data and behaviour. Java can be easily extended
as it is based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time
error checking and runtime checking. But the main areas which Java improved were Memory
Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent
and can be run on any machine, plus this bytecode format also provide security. Any machine
with Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable us
to develop virus free, temper free system. Java program always runs in Java runtime
environment with almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or
C++. But, Java enables high performance with the use of just-in-time compiler.
2.Why java is named as java only? Elaborate (Expected details from History)?
Java, initially, was called OAK but they couldn't use the name as it was already a trademark by
OAK technologies. Then they started brainstorming sessions. People were suggesting different
names. The end result was that about ten possible names were chosen. They were then
submitted to the legal department. Three of them came back clean: Java, DNA, and Silk. No
one remembers who first came up with the name 'Java. Java coffee, said to be consumed in
large quantities by the language's creators.

3.What was previous name and extension of java?


Earlier name oak and previous extension was also java

4. The main(String[] args) method is compulsory in java? Java


Compiler(JVM) has a predefined syntax which differentiates public static void main (String[]
args) from other main(). The JVM looks for the exact match and compiles the java program,
hence String args is mandatory to use to match it with its syntax. The significance of this String
args[] is that it accepts command line arguments and store it in the array of strings.

5.What is static block?


n a Java class, a static block is a set of instructions that is run only once when a class is
loaded into memory. A static block is also called a static initialization block. This is because it
is an option for initializing or setting up the class at run-time. The keyword 'static' indicates that it
spans all instances of the class. It is like a mini-global set of instructions. This code inside static
block is executed only once: the first time you make an object of that class or the first time you
access a static member of that class

6. Can we overload main() method? How?


Yes, you can overload main method in Java. But the program doesn't execute the overloaded
main method when you run your program, you have to call the overloaded main method from
the actual main method. that means main method acts as an entry point for the java interpreter
to start the execute of the application. where as a loaded main need to be called from main.

class Simple{

public static void main(int a){

System.out.println(a);

public static void main(String args[])

System.out.println("main() method invoked");

main(10);

}
7. Who will load .class file in JVM?
The classloader subsystem is an essential core of the Java Virtual machine and is used for
loading/reading the .class files and saving the bytecode in the JVM method area.

8. We have default constructor in sub class and super class. When we create sub class object
in single inheritance. Which constructor is called? Why?
Base class constructors are always called in the derived class constructors. Whenever you
create derived class object, first the base class default constructor is executed and then the
derived class's constructor finishes execution.
It happens due to the super(); call in the constructor.

9. How JVM will call to main method?


Internally, JVM invokes main() by "MainClass.main()".

10. Can we store primitive data type variables in heap memory?


When a method is called, certain data is placed on the stack. When the method finishes, data is
removed from the stack. At other points in a program's execution, data is added to the stack, or
removed from it.
Therefore, if you have a variable which is intended to outlive the execution of the method that
created it, it needs to be on the heap.
This applies both to any objects that you create, and any primitives that are stored within those
objects.However, if a variable is intended to go out of scope shortly after its creation - say, at the
end of the method in which it's created, or even earlier, then it's appropriate for that variable to
be created on the stack. Local variables and method arguments fit this criterion; if they are
primitives, the actual value will be on the stack, and if they are objects, a reference to the object
(but not the object itself) will be on the stack.

11. How JVM will Destroy the objects?


Java (and JVM in particular) uses automatic garbage collection. To put it simply, whenever
new objects are created, the memory is automatically allocated for them. Consequently,
whenever the objects are not referenced anymore, they are destroyed and their memory is
reclaimed.

12. What are criteria to select object for garbage collection?


An object is eligible to be garbage collected if its reference variable is lost from the program
during execution.Sometimes they are also called unreachable objects.
Object created inside a method : When a method is called it goes inside the stack frame.
When the method is popped from the stack, all its members dies and if some objects were
created inside it then these objects becomes unreachable or anonymous after method
execution and thus becomes eligible for garbage collection.
Reassigning the reference variable: When reference id of one object is referenced to
reference id of some other object then the previous object has no any longer reference to it and
becomes unreachable and thus becomes eligible for garbage collection.
Nullifying the reference variable : When all the reference variables of an object are changed
to NULL, it becomes unreachable and thus becomes eligible for garbage collection.

13. Which data structure is used by JVM to deal with methods (example calling) in java?
JVM uses stack for invoking and returning from methods.
14. What is difference between JRE JDK and JVM?

JDK

Java Development Kit is the core component of Java Environment and provides all the tools,
executables and binaries required to compile, debug and execute a Java Program. JDK is a
platform specific software and thats why we have separate installers for Windows, Mac and
Unix systems. We can say that JDK is superset of JRE since it contains JRE with Java
compiler, debugger and core classes. Current version of JDK is 1.7 also known as Java 7.

JVM

JVM is the heart of java programming language. When we run a program, JVM is responsible to
converting Byte code to the machine specific code. JVM is also platform dependent and
provides core java functions like memory management, garbage collection, security etc. JVM is
customizable and we can use java options to customize it, for example allocating minimum and
maximum memory to JVM. JVM is called virtual because it provides a interface that does not
depend on the underlying operating system and machine hardware. This independence from
hardware and operating system is what makes java program write-once run-anywhere.

JRE

JRE is the implementation of JVM, it provides platform to execute java programs. JRE consists
of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t
contain any development tools like java compiler, debugger etc. If you want to execute any java
program, you should have JRE installed but we don’t need JDK for running any java program.

JDK vs JRE vs JVM

Let’s look at some of the important difference between JDK, JRE and JVM.

1. JDK is for development purpose whereas JRE is for running the java programs.
2. JDK and JRE both contains JVM so that we can run our java program.
3. JVM is the heart of java programming language and provides platform independence.

15.What is JIT compiler?


Just-in-time Compiler (JIT)

Sometimes we heard this term and being it a part of JVM it confuses us. JIT is part of JVM that
optimise byte code to machine specific language compilation by compiling similar byte codes at
same time, hence reducing overall time taken for compilation of byte code to machine specific
language.
16. What is native interface?
The Java Native Interface (JNI) is a programming framework that enables Java code running in
a Java Virtual Machine (JVM) to call and be called bynative applications (programs specific to a
hardware and operating system platform) and libraries written in other languages such as C,
C++ and assembly.

17. When to select interface and abstract class for implementation? Explain with real time
example of your choices?

Abstract Class
Consider using abstract classes if any of these statements apply to your situation:

1. You want to share code among several closely related classes.


2. You expect that classes that extend your abstract class have many common methods or
fields or require access modifiers other than public (such as protected and private).
3. You want to declare non-static or non-final fields. This enables you to define methods
that can access and modify the state of the object to which they belong.

Interface
An interface is just the declaration of methods of an Object, it’s not the implementation. In
interface, we define what kind of operation an object can perform. These operations are defined
by the classes that implement interface. Interfaces form a contract between the class and the
outside world, and this contract is enforced at build time by the compiler.
Consider using interfaces if any of these statements apply to your situation:

1. You expect that unrelated classes would implement your interface. For example, the
interfaces Comparable and Cloneable are implemented by many unrelated classes.
2. You want to specify the behavior of a particular data type, but not concerned about who
implements its behavior.
3. You want to take advantage of multiple inheritances.

18. Why to use interfaces even we have abstract class?


In Java we can extend only one Class but can implement multiple interfaces.And this is really
implement for example if you want to create a background Thread in your Class and your
extending some Class for reusability,then how ill you extend Thread Class? In this case
Runnable comes to rescue which is an interface.

19. What is marker interface? Any examples of your choice?

Marker interface in Java


It is an empty interface (no field or methods). Examples of marker interface are Serializable,
Clonnable and Remote interface. All these interfaces are empty interfaces.
Serializable interface : Serializable interface is present in java.io package. It is used to make
an object eligible for saving its state into a file. This is called Serialization.
20.What is early binding?
When a method is called in Java it's bonded to the actual code either at compile time or runtime,
when the program is actually started and objects are created. As the name suggest, static
binding is more of static nature hence it occurs at compile time i.e. your code knows which
method to call once you compiled your Java source file into a class file. Since it happens early
in program's life cycle it is also known as early binding in Java.

21. What dynamic binding?


On the other hand, dynamic binding occurs at runtime, when JVM starts your program. This
time which method to call is figured out by an actual object, which information was not available
at compile time because objects are created at runtime. Since it happens late in the program life
cycle, it is also known as late binding in Java.

22. What is difference between set, map and list?


. List in Java provides ordered and indexed collection which may contain duplicates.
The Set interface provides an unordered collection of unique objects, i.e. Set doesn't allow
duplicates,
while Map provides a data structure based on key-value pair and hashing.

Duplicate Objects
The main difference between List and Set interface in Java is that List allows
duplicates while Set doesn't allow duplicates. All implementation of Set honor this contract.
While a Map holds two objects per Entry e.g. a key and a value and It may contain duplicate
values but keys are always unique. See here for more difference between List and Set data
structure in Java.

Order
Another key difference between List and Set is that List is an ordered collection, List's contract
maintains insertion order or element. Set is an unordered collection, you get no guarantee on
which order element will be stored.

Null elements
The list allows null elements and you can have many null objects in a List because it also
allowed duplicates. Set just allow one null element as there is no duplicate permitted while in
Map you can have null values and at most one null key.
23. What is difference between concurrent collection and simple collection?
We all know about about Traditional Collections ( i.e. List, Set, Queue and its implemented
Classes) and Concurrent Collection (i.e. ConcurrentMap interface, ConcurrentHashMap class,
CopyOnWriteArrayList class etc). In these two Collections, there are few differences like:
 Most of the Classes which are present in Traditional Collections
(i.e ArrayList, LinkedList, HashMap etc)are non-synchronized in nature and Hence there
is no thread-safety. But All the classes present in Concurrent Collections are synchronized
in nature. Therefore In Concurrent classes, we dont have to take care about Thread-safety.
 While Traditional Collections also have some classes (like Vector, Stack etc) which are
synchronized in nature and Traditional Collections also have SynchronizedSet,
SynchronizedList, SynchronizedMapmethods through which we can get Synchronized
version of non-synchronized objects. But these above Synchronized classes are not good
in terms of performance because of wide-locking mechanism .Whereas Concurrent
Collections classes performance are relatively high than Traditional Collections classes.

24. Explain public static void main()

Let's split it and understand one by one.


1. public- Here public is an access specifier which allows thhe main method to be accessble
everywhere.
2. static- static helps main method to get loaded without getting alled by any instance/object.
3. void- void clarifies that the main method will not return any value.
4. main- It's the name of the method.
5. String[] args- Here we are defining a String array to pass arguments at command line. args is
the variable name of the String array. It can be changed to anything such as String [] a.

25. What is class and object ?

Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state that
the object of its type support.

26. What is package in java ?


A package is a namespace that organizes a set of related classes and interfaces. Conceptually
you can think of packages as being similar to different folders on your computer. You might
keep HTML pages in one folder, images in another, and scripts or applications in yet another.
Because software written in the Java programming language can be composed of hundreds
or thousands of individual classes, it makes sense to keep things organized by placing related
classes and interfaces into packages.
27. Why java is called object oriented programming language ?

Object-oreineted programming is a programming model which is based on representing things


as "objects" which can have associated data and functions to operate on the data.

28. What is the difference between ArrayList and Vector?

Differences
 Vectors are synchronized, ArrayLists are not.
 Data Growth Methods
Use ArrayLists if there is no specific requirement to use Vectors.

Synchronization
If multiple threads access an ArrayList concurrently then we must externally synchronize the
block of code which modifies the list either structurally or simply modifies an element. Structural
modification means addition or deletion of element(s) from the list. Setting the value of an
existing element is not a structural modification.

Collections.synchronizedList is normally used at the time of creation of the list to avoid any
accidental unsynchronized access to the list.
Reference
Data growth
Internally, both the ArrayList and Vector hold onto their contents using an Array. When an
element is inserted into an ArrayList or a Vector, the object will need to expand its internal array
if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList
increases its array size by 50 percent

29. What is the difference between ArrayList and LinkedList?

ArrayList LinkedList

1) ArrayList internally uses dynamic LinkedList internally uses doubly


array to store the elements. linked list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedList


is slow because it internally uses array. is faster than ArrayList because it uses
If any element is removed from the doubly linked list so no bit shifting is
array, all the bits are shifted in memory. required in memory.

3) ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List
and Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for


accessing data. manipulating data.
30. What is the difference between Iterator and Enumeration?

Enumeration Iterator

Using Enumeration, you can only


traverse the collection. You can’t do
any modifications to collection while Using Iterator, you can remove an element of the
traversing it. collection while traversing it.

Enumeration is introduced in JDK 1.0 Iterator is introduced from JDK 1.2

Enumeration is used to traverse the Iterator is used to iterate most of the classes in
legacy classes the collection framework
like Vector, Stackand HashTable. like ArrayList, HashSet, HashMap, LinkedList etc.

Methods
: hasMoreElements() and nextElement() Methods : hasNext(), next() and remove()

Enumeration is fail-safe in nature. Iterator is fail-fast in nature.

Enumeration is not safe and secured


due to it’s fail-safe nature. Iterator is safer and secured than Enumeration.

31. What is the difference between List and Set?

List
1. Is an Ordered grouping of elements.
2. List is used to collection of elements with duplicates.
3. New methods are defined inside List interface.
Set
1. Is an Unordered grouping of elements.
2. Set is used to collection of elements without duplicates.
3. No new methods are defined inside Set interface, so we have to use Collection interface
methods only with Set subclasses.
32. What is the difference between Collection and Collections?

The differences between the Collection and Collections are given below.

o The Collection is an interface whereas Collections is a class.


o The Collection interface provides the standard functionality of data structure to List, Set,
and Queue. However, Collections class is to sort and synchronize the collection
elements.
o The Collection interface provides the methods that can be used for data structure
whereas Collections class provides the static methods which can be used for various
operation on a collection.

33. Advantages of collections?

 Reduces programming effort: By providing useful data structures and algorithms, the
Collections Framework frees you to concentrate on the important parts of your program
rather than on the low-level "plumbing" required to make it work. By facilitating
interoperability among unrelated APIs, the Java Collections Framework frees you from
writing adapter objects or conversion code to connect APIs.
 Increases program speed and quality: This Collections Framework provides high-
performance, high-quality implementations of useful data structures and algorithms. The
various implementations of each interface are interchangeable, so programs can be
easily tuned by switching collection implementations. Because you're freed from the
drudgery of writing your own data structures, you'll have more time to devote to
improving programs' quality and performance.
 Allows interoperability among unrelated APIs: The collection interfaces are the
vernacular by which APIs pass collections back and forth. If my network administration
API furnishes a collection of node names and if your GUI toolkit expects a collection of
column headings, our APIs will interoperate seamlessly, even though they were written
independently.
 Reduces effort to learn and to use new APIs: Many APIs naturally take collections on
input and furnish them as output. In the past, each such API had a small sub-API
devoted to manipulating its collections. There was little consistency among these ad hoc
collections sub-APIs, so you had to learn each one from scratch, and it was easy to
make mistakes when using them. With the advent of standard collection interfaces, the
problem went away.
 Reduces effort to design new APIs: This is the flip side of the previous advantage.
Designers and implementers don't have to reinvent the wheel each time they create an
API that relies on collections; instead, they can use standard collection interfaces.
 Fosters software reuse: New data structures that conform to the standard collection
interfaces are by nature reusable. The same goes for new algorithms that operate on
objects that implement these interfaces.

34. What is the advantage of generic collection?

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store
other objects.

2) Type casting is not required: There is no need to typecast the object

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.

35. What is the difference between Array and ArrayList?

SN Array ArrayList

1 The Array is of fixed size, means we ArrayList is not of the fixed size we can
cannot resize the array as per need. change the size dynamically.

2 Arrays are of the static type. ArrayList is of dynamic size.

3 Arrays can store primitive data types ArrayList cannot store the primitive data
as well as objects. types it can only store the objects.

36. What is the difference between length of Array and size of ArrayList?
The length of an array can be obtained using the property of length whereas ArrayList does not
support length property, but we can use size() method to get the number of objects in the list.
37. What is the difference between Comparable and Comparator?
No. Comparable Comparator

1) Comparable provides only The Comparator


one sort of sequence. provides multiple
sorts of sequences.

2) It provides one method It provides one


named compareTo(). method named
compare().

3) It is found in java.lang It is located in java.util


package. package.

4) If we implement the The actual class is


Comparable interface, The not changed.
actual class is modified.

38. What does the hashCode() method?

The hashCode() method returns a hash code value (an integer number).

The hashCode() method returns the same integer number if two keys (by calling equals()
method) are identical.

However, it is possible that two hash code numbers can have different or the same keys.

If two objects do not produce an equal result by using the equals() method, then the hashcode()
method will provide the different integer result for both the objects.
39. Why we override equals() method?

The equals method is used to check whether two objects are the same or not. It needs to be
overridden if we want to check the objects based on the property.

For example, Employee is a class that has 3 data members: id, name, and salary. However, we
want to check the equality of employee object by the salary. Then, we need to override the
equals() method.

40. What is JDBC?

JDBC is a Java API that is used to connect and execute the query to the database. JDBC API
uses JDBC drivers to connect to the database. JDBC API can be used to access tabular data
stored into any relational database.

41.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:

1. JDBC-ODBC bridge driver: The JDBC-ODBC bridge driver uses the ODBC driver to
connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls
into the ODBC function calls. This is now discouraged because of the thin driver. It is
easy to use and can be easily connected to any database.
2. Native-API driver (partially java driver): The Native API driver uses the client-side
libraries of the database. The driver converts JDBC method calls into native calls of the
database API. It is not written entirely in Java. Its performance is better than JDBC-
ODBC bridge driver. However, the native driver must be installed on each client
machine.
3. Network Protocol driver (fully java driver): The Network Protocol driver uses
middleware (application server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is entirely written in Java. There is no requirement
of the client-side library because of the application server that can perform many tasks
like auditing, load balancing, logging, etc.
4. Thin driver (fully java driver): The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is known as the thin driver. It is entirely
written in Java language. Its performance is better than all other drivers however these
drivers depend upon the database.
42.What are the steps to connect to the database in java?

public void createConnection()

//2.Creating Connection

String url="jdbc:mysql://localhost:3306/mysdb?useSSL=false";

String user="root";

String password="xyz";

//1.Loading Driver

try

Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection(url, user, password);

catch (ClassNotFoundException e)

e.printStackTrace();

catch (SQLException e)

{
e.printStackTrace();

System.out.println("Database Connected...");

}
43.What are the JDBC API components?

The java.sql package contains following interfaces and classes for JDBC API.

Interfaces:

o Connection: The Connection object is created by using getConnection() method of


DriverManager class. DriverManager is the factory for connection.

o Statement: The Statement object is created by using createStatement() method of


Connection class. The Connection interface is the factory for Statement.

o PreparedStatement: The PrepareStatement object is created by using


prepareStatement() method of Connection class. It is used to execute the parameterized
query.

o ResultSet: The object of ResultSet maintains a cursor pointing to a row of a table.


Initially, cursor points before the first row. The executeQuery() method of Statement
interface returns the ResultSet object.

o ResultSetMetaData: The object of ResultSetMetaData interface cotains the information


about the data (table) such as numer of columns, column name, column type, etc. The
getMetaData() method of ResultSet returns the object of ResultSetMetaData.

o DatabaseMetaData: DatabaseMetaData interface provides methods to get metadata of


a database such as the database product name, database product version, driver name,
name of the total number of tables, the name of the total number of views, etc. The
getMetaData() method of Connection interface returns the object of DatabaseMetaData.

o CallableStatement: CallableStatement interface is used to call the stored procedures


and functions. We can have business logic on the database through the use of stored
procedures and functions that will make the performance better because these are
precompiled. The prepareCall() method of Connection interface returns the instance of
CallableStatement.
Classes:

o DriverManager: The DriverManager class acts as an interface between the user and
drivers. It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. It contains several methods
to keep the interaction between the user and drivers.

o Blob: Blob stands for the binary large object. It represents a collection of binary data
stored as a single entity in the database management system.

o Clob: Clob stands for Character large object. It is a data type that is used by various
database management systems to store character files. It is similar to Blob except for
the difference that BLOB represent binary data such as images, audio and video files,
etc. whereas Clob represents character stream data such as character files, etc.

o SQLException It is an Exception class which provides information on database access


errors.

44.What are the JDBC statements?

In JDBC, Statements are used to send SQL commands to the database and receive data from
the database. There are various methods provided by JDBC statements such as execute(),
executeUpdate(), executeQuery, etc. which helps you to interact with the database.

Statements Explanation

Statement Statement is the factory for resultset. It is used for general


purpose access to the database. It executes a static SQL
query at runtime.

PreparedStatement The PreparedStatement is used when we need to provide


input parameters to the query at runtime.

CallableStatement CallableStatement is used when we need to access the


database stored procedures. It can also accept runtime
parameters.
45.What is the difference between Statement and PreparedStatement interface?

Statement PreparedStatement

The Statement interface provides The PreparedStatement interface is


methods to execute queries with the a subinterface of Statement. It is
database. The statement interface is a used to execute the parameterized
factory of ResultSet; i.e., it provides the query.
factory method to get the object of
ResultSet.

In the case of Statement, the query is In the case of PreparedStatement,


compiled each time we run the the query is compiled only once.
program.

The Statement is mainly used in the PreparedStatement is used when


case when we need to run the static we need to provide input
query at runtime. parameters to the query at runtime.

46.What is the role of JDBC DriverManager class?

he DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().

47.What does the JDBC Connection interface?

The Connection interface maintains a session with the database. It can be used for
transaction management. It provides factory methods that return the instance of Statement,
PreparedStatement, CallableStatement, and DatabaseMetaData.

48.What does the JDBC ResultSet interface?

The ResultSet object represents a row of a table. It can be used to change the cursor pointer
and get the information from the database. By default, ResultSet object can move in the forward
direction only and is not updatable. However, we can make this object to move the forward and
backward direction by passing either TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE in createStatement(int, int) method.
49. What are the benefits of PreparedStatement over Statement?

The benefits of using PreparedStatement over Statement interface is given below.

o The PreparedStatement performs faster as compare to Statement because the


Statement needs to be compiled everytime we run the code whereas the
PreparedStatement compiled once and then execute only on runtime.
o PreparedStatement can execute Parameterized query whereas Statement can only run
static queries.
o The query used in PreparedStatement is appeared to be similar every time. Therefore,
the database can reuse the previous access plan whereas, Statement inline the
parameters into the String, therefore, the query doesn't appear to be same everytime
which prevents cache reusage.

50. What is the return type of Class.forName() method?

The Class.forName() method returns the object of java.lang.Class object.

51. What are the differences between execute, executeQuery, and executeUpdate?
execute executeQuery executeUpdate

The execute method can be The executeQuery The executeUpdate method


used for any SQL method can be used can be used to
statements(Select and Update only with the select update/delete/insert
both). statement. operations in the database.

The execute method returns a The executeQuery() The executeUpdate() method


boolean type value where true method returns a returns an integer value
indicates that the ResultSet s ResultSet object which representing the number of
returned which can later be contains the data records affected where 0
extracted and false indicates retrieved by the select indicates that query returns
that the integer or void value is statement. nothing.
returned.

Potrebbero piacerti anche