Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Monday, 1 July 2013

Core Java : General Questions


Q: Explain OOPs concepts.

Abstraction
An essential element of Object Oriented Programming is “Abstraction”. Humans manage complexity through abstraction. A powerful way to manage abstraction is through the use of hierarchical classifications. This allows us to layer the semantics of complex systems, breaking them into more manageable pieces.
For example, we do not think of a car as a set of tens of thousands of parts. We think of it as a well-defined object with its unique behaviour. “This abstraction allows us to use the car to drive to a grocery store without being overwhelmed by the complexity of the parts that form the car.”

Example of hierarchical classification:
From outside, the car is a single object. Once inside the car, we see that
the car consists of several subsystems: steering, brakes, sound system and
so on. In turn, each of these subsystems is made up of more sophisticated
units.
The point is that we manage the complexity of the car (or many other complex
systems) through the use of hierarchical classifications.

Encapsulation
Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse.
One way to think about encapsulation is a protective wrapper that
prevents the code and data from being arbitrarily accessed by other code
defined outside the wrapper.
Access to the code and data inside the wrapper is tightly controlled
through a well defined interface.
e.g. in a car, we have accelerator, the complex implementation that
actually accelerates the car is not visible to the driver. The driver has access
to this protective wrapper through the well-defined interface i.e. accelerator in
this case.

Inheritance
Inheritance is the process by which one object acquires the properties of
another object. It is a parent child relationship. This is important because it
supports hierarchical classification.

Polymorphism
It is the property by which methods with same name can have different forms.
Poly = many, Moprhism = forms.
Polymorphism is of two types:(i) Compile time Polymorphism: It is also called early binding. It is achieved
through method overloading.
(ii) Run time Polymorphism: It is also called late binding. It is achieved
through method overriding.

Data Hiding
Data hiding is the feature through which we protect the access to the data.
We may have public, default, protected or private access to the data
members.
public data members are visible to all the data and methods
default access (also called package access) data members are visible to all
the data and methods within the same package
protected data members are visible to data and methods of subclasses of
the class in which they are defined.
private data members are only visible to data and methods in the same
class.

Q: What is the difference between encapsulation and data hiding?

Data Hiding is a concept of making all the data (fields) privete e.g. not
accessible from the other objects, classes, APIs in the system. The only
class/object/API have to know about the data and how to operate them.
Private fields with accessors is a good example.

As for the Info Hiding - this more about the methods. Now, you are trying to
hide e.g. make private the implementation of methods, to hide the design
decisions. For example, you API should return Interface Object reference but
not Class Object reference and then another client API wouldn't know how
you API is implemented. For example, if you are getting cash in ATM you
should just type your pin a get your money and you don't really know how
they are transferred to you from you balance.

Encapsulation is logical integration of the data and/or the function within one
entity (class, object, package, library, API etc) with or without hiding them
from another entities

3) What is System.out.println() ?

System   : class
Out         : variable of type PrintStream of class System
Println() :method of class PrintStream

Q: What is public static void main(String args[]){} ?

public access specifier, it is kept public because this method is to be called
by JVM.
static by specifying this method as static, we are making sure that this
method can be called without any objects.
void void means this method does not return any value.
main name of method.
String args[] input string argument array.

Q: What is Composition, aggregation, and association etc ?

Composition: Holding the reference of the other class within some class is
known as composition.
e.g.
1. Open a new Document name it as test.txt
2. Write this sentence in iside this document "This is a composition".
3. Save the document.
4. Now, delete this document.

This is what is called composition, you can't move the sentence "This is a
composition" from the document because its lifecycle is linked to the parent
(the document)

Aggregation: Aggregation is a special type of composition. If we expose all
the methods of a composite class and route the method call to the composite
method through its reference, then it is called aggregation.

e.g.
1. Create a file called file.txt
2. make a simple application to open the file.txt (rw), but don't program it
close the connection.
3. Run an instance of this application (it should work ok and can open the file
for rw)
4. Keep the first instance, and run another instance of this application (In
theory it should complain that it can't open the file in rw mode because it is
already used by other application).
5. Close the 2 instances (make sure you close the connection).

From the above application, we knew that the Application and the file has a
separate lifecycles, however this file can be opened only by one application
simuletanously (there is only one parent at the same time, however, this
parent can move the child to another parent or can make it orphan).

Association: Association defines a relationship between classes of objects
which allows one object instance to cause another to perform an action on its
behalf.

e.g
1. Create a folder called "Links"
2. create a shortcut inside this folder and link it to www.yahoo.com
3. create another shortcut instide this folder and link it to www.google.com
4. Ask your friend to do the same on another machine using same links
(www.yahoo.com and www.google.com)
5. Delete the "Links" folder, and open your browser to check if
www.yahoo.com and www.google.com still exist or not ;)

Briefly, Association is a relationship where all the objects have different
lifecycles. There is no owner.

Q: What is the difference between Abstract class and Interface ? Which one should be used when ?
An Interface only contains method declarations. It is a contract that is used to define hierarchies for all subclasses. A class can implement more than one interfaces.
An Abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from).
The advantage is that it enforces certain hierarchies for all the subclasses.
The selection criteria depends upon your requirement. This is actually a design issue. We should use an interface if we want to attach a behaviour to a class. Whereas we should use an Abstract class if there is a common behavior that is supposed to be shared.

Q: What is the difference between finally, final, and finalize ?

finally: finally is an exception handler.
The finally block will be executed whether or not an exception is thrown. Any time a method is about to return to the caller from inside a try/catch block, because of an uncaught exception or explicit return statement, the finally block is executed before the method returns.

final: final is a keyword used in three different ways:
(i) With variables: final variables behave as constants, their value is once initialized and cannot be changed after that.
(ii) With method declarations: Method declarations preceding with final keyword means that this method cannot be overridden. However we can overload a final method.
(iii)With class names: “final” keyword with class declaration means that this class cannot be extended.

finalize(): Java run-time calls this method whenever it is about to recycle an object of
the class in which this method is defined. Inside the finalize() method, we should specify those actions that must be performed before an object is destroyed.

Q: What is the difference between method overloading and overriding ?
  • In overloading,there is a relation ship between methods available in the same class where as in overridding,there is relationship between a super class method and subclass method.
  • In overloading,seperate methods share the same name where as in overridding,subclass methods replaces the superclass.
  • Overloading must have different method signatures where as overriding must have same signature.
  • In overloading, we may have different return types. But in overriding, we must have same return type.
  • Through overloading, we can achieve compile time polymorphism (i.e. early binding). Whereas, through overriding, we can achieve run-time polymorphism (i.e. late-binding).


Q:What are checked and unchecked exceptions?

Unchecked Exceptions: Exceptions derived from the class
RuntimeException are automatically available to the class, and
need not be included in any method’s throws list. These are called
unchecked exceptions

Checked Exceptions: Exceptions defined by java.lang that must
be included in a methods throws list if that method can generate one
of these exceptions and does not handle them itself (using try catch).
These are called Checked Exceptions.

What is the use of the super keyword?

The super keyword gives a class explicit access to the
constructors, methods, and variables of its superclass.

What is garbage-collector ? How does it function?

Garbage Collector is a demon thread run by the JVM to clean up
any unused objects and reclaim memory.

9

14)

It works like this: when no references to an object exists, that object
is assumed to be no longer needed, and the memory occupied by
the object can be reclaimed.
Garbage Collector runs periodically to recycle unused objects.
However, we can run the garbage collector on demand by calling
the gc() method.
Runtime r = Runtime.getRuntime();
r.gc();

What are inner classes?

Inner classes nest within other classes. A normal class is a direct
member of a package, a top-level class. Inner classes, which
became available with Java 1.1, come in four flavors:

* Static member classes
* Member classes
* Local classes
* Anonymous classes

Let's take a quick look at each in turn.

Briefly, a static member class is a static member of a class. Like
any other static method, a static member class has access to all
static methods of the parent, or top-level, class.

Like a static member class, a member class is also defined as a
member of a class. Unlike the static variety, the member class
is instance specific and has access to any and all methods and
members, even the parent's this reference.

Local classes are declared within a block of code and are visible
only within that block, just as any other method variable.

Finally, an anonymous class is a local class that has no name.

15)

What are Marker interfaces and what is their use?

A marker interface is a java interface which doesn’t actually define
any methods. It is just used to “mark” Java classes which support
a certain capability – the class marks itself as implementing the
interface.
For example, java.lang.Cloneable, SingleThreadModel, Serializable
etc.

10

16)
A class which calls the clone() method must implement
the interface Cloneable. But this is a marker interface i.e. it
contains no methods, then where is the definition of clone()
method provided?

In the Object class.
If overriding clone() method relies on the the clone() method in
the Object class, then the subclass must implement the Cloneable
marker interface to indicate that its objects can be safely cloned.
Otherwise, the clone() method in the Object class will throw a
checked “CloneNotSupportedException”.

17)

A native method is the Java interface to non-Java code. It is Java's link to
the "outside world." More specifically, a native method is a Java method
whose implementation is provided by non-Java code, most likely C.
The keyword native informs the compiler that the method has been
used in a non-java platform, and this keyword can be used only with the
methods.

18)

Many times you are not able to tell exactly which class will be instantiated, until
the runtime. In these situations you want to be able to create an object through
some identifier such as the name of the class. This is one of the abilities that
Reflection API of Java provides.

Consider a system that does custom processing on packets of data. What
processing will be done on the data depends upon the value of the header field
of the packet. What will you do if the processing requirements are dynamic in
nature and values that the header-field can have keep changing depending upon
customer requirements etc?

The above problem can be conveniently solved using Reflection. Reflection API
enables you to create an instance of a class whose name is not known until
runtime. You can just plug-in the custom processing classes into the system,
without having to recompile the code again.

All the processing classes will be derived from the same base
class 'MessageProcessor'.

public abstract class MessageProcessor
{
public abstract void runProcessing(Object message);
}

What are native methods?

What is Reflection API in Java?

public class ProcessingOne extends MessageProcessor

11

{

public void runProcessing(Object message)
{
System.out.println("Processing type one");
}

}

The system that is processing the packets, reads the packet header and calls the
required processing as shown below:

{

:
String processName;
MessageProcessor messageProcessor;
:
:
processName = message.header;
//Assuming the header is of String type and
//gives the full name of the class
Class class = Class.forName(processName);
messageProcessor =
(MessageProcessor).class.newInstance();
messageProcessor.runProcessing(message);

}

For Details: http://www.asingh.net/technical/reflection.html

19)

“Design patterns are recurring solutions to design problems.”

Patterns: According to commonly known practices, there are 23 design
patterns in Java. These patterns are grouped under three heads:
1. Creational Patterns

Do you know any java design patterns ?

2. Structural Patterns

3. Behavioral Patterns

1.
2.
3.
4.
5.

Factory Pattern
Abstract Factory Pattern
Builder Pattern
Prototype Pattern
Singleton Pattern

1.
2.
3.
4.
5.
6.
7.

Adapter Pattern
Bridge Pattern
Composite Pattern
Decorator Pattern
Facade Pattern
Flyweight Pattern
Proxy Pattern

1. Chain of Resposibility Pattern
2. Command Pattern

12

3. Interpreter Pattern
4. Iterator Pattern
5. Mediator Pattern
6. Momento Pattern
7. Observer Pattern
8. State Pattern
9. Strategy Pattern
10. Template Pattern
11. Visitor Pattern

Collections

20)

What is the Difference between ArrayList and Vector ?

http://www.javaworld.com/javaworld/javaqa/2001-06/03-qa-0622-vector.html

Sometimes Vector is better; sometimes ArrayList is better; sometimes you
don't want to use either. I hope you weren't looking for an easy answer
because the answer depends upon what you are doing. There are four
factors to consider:

* API
* Synchronization
* Data growth
* Usage patterns

Let's explore each in turn.
API

In The Java Programming Language (Addison-Wesley, June 2000) Ken
Arnold, James Gosling, and David Holmes describe the Vector as an
analog to the ArrayList. So, from an API perspective, the two classes are
very similar. However, there are still some major differences between the
two classes.

Synchronization

Vectors are synchronized. Any method that touches the Vector's contents
is thread safe. ArrayList, on the other hand, is unsynchronized, making
them, therefore, not thread safe. With that difference in mind, using
synchronization will incur a performance hit. So if you don't need a thread-
safe collection, use the ArrayList. Why pay the price of synchronization
unnecessarily?

Data growth

13

Internally, both the ArrayList and Vector hold onto their contents using
an Array. You need to keep this fact in mind while using either in your
programs. When you insert an element 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. Depending on how you use these classes, you
could end up taking a large performance hit while adding new elements.
It's always best to set the object's initial capacity to the largest capacity
that your program will need. By carefully setting the capacity, you can
avoid paying the penalty needed to resize the internal array later. If you
don't know how much data you'll have, but you do know the rate at which
it grows, Vector does possess a slight advantage since you can set the
increment value.

Usage patterns

Both the ArrayList and Vector are good for retrieving elements from a
specific position in the container or for adding and removing elements
from the end of the container. All of these operations can be performed in
constant time -- O(1). However, adding and removing elements from any
other position proves more expensive -- linear to be exact: O(n-i), where
n is the number of elements and i is the index of the element added or
removed. These operations are more expensive because you have to shift
all elements at index i and higher over by one element. So what does this
all mean?

It means that if you want to index elements or add and remove elements
at the end of the array, use either a Vector or an ArrayList. If you want to
do anything else to the contents, go find yourself another container class.
For example, the LinkedList can add or remove an element at any position
in constant time -- O(1). However, indexing an element is a bit slower -
- O(i) where i is the index of the element. Traversing an ArrayList is also
easier since you can simply use an index instead of having to create an
iterator. The LinkedList also creates an internal object for each element
inserted. So you have to be aware of the extra garbage being created.

21)
What is the difference between HashMap and
HashTable ?

Synchronization:

14

Hashtable is synchronized.
HashMap is not synchronized.

Null key/values
HashTable does not allow null keys/values.
HashMap allows null keys/values.

hashCode implementation
HashMap has a more complex hashing algorithm then Hashtable.
It takes the hash value from the key and then hashes it again
(double hashing). This can improve the distribution of the keys
and hence the performance of the Map. It does take more time
to compute though. This is a useful feature as many hashCode
implementations are not very good.

22)
Explain Correct and incorrect implementations of equals()
and hashCode() methods.

http://www.jchq.net/essentials/d0e2046.htm
http://www.geocities.com/technofundo/tech/java/equalhash.html

The hashcode value of an object gives a number which can be
used to in effect to 'index' objects in a collection. A collection class
can group its objects by their hashcodes, and if you called e.g.
contains() (or get() in case of a Map), it can first find the group
based on the hashcode, then search that group. This avoids the
need to check every object in the collection.

The requirements of a hashCode() implementation are that if
two objects are equal as determined the equals() method, their
hashcodes should be the same. This is why wherever you override
the equals() method, you should override hashCode() aswell.

The reverse is not required i.e. it is permitted for two objects that
are not equal to have the same hashcode. This makes sense,
as it is not always possible to ensure unique hashCodes. The
method returns an int and there are only an finite number of int
values to use. However, where possible, it is desirable to have
the hashcodes be distinct as this can improve performance. If the
hashcodes can be well distributed (i.e. scattered throughtout the int
range) as well, all the better.

JDBC

15

23)

What are the four types of JDBC Connections ?

JDBC Driver Types

JDBC drivers are divided into four types or levels. The different
types of jdbc drivers are:

Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

4 types of jdbc drivers are elaborated in detail as shown below:

Type 1 JDBC Driver

JDBC-ODBC Bridge driver

The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the
ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended
only for experimental use or when no other alternative is available.

Type 1: JDBC-ODBC Bridge

Advantage

16

The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available.

Disadvantages

1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC
driver, then to the database, and this applies even in the reverse process. They are the
slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

Type 2 JDBC Driver

Native-API/partly Java driver

The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC
calls into database-specific calls i.e. this driver is specific to a particular database. Some
distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will
have oracle native api.

Type 2: Native api/ Partly Java Driver

Advantage

The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better
performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less
than that of Type
1 and also it uses Native api which is Database specific.

17

Disadvantage

1. Native API must be installed in the Client System and hence type 2 drivers cannot be
used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a
database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3 JDBC Driver

All Java/Net-protocol driver

Type 3 database requests are passed through the network to the middle-tier server. The
middle-tier then translates the request to the database. If the middle-tier server can in turn
use Type1, Type 2 or Type 4 drivers.

Type 3: All Java/ Net-Protocol Driver

Advantage

1. This driver is server-based, so there is no need for any vendor database library to be
present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to
load.
5. The type 3 driver typically provides support for features such as caching (connections,
query results, and so on), load balancing, and advanced

18

system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantage

It requires another server application to install and maintain. Traversing the recordset
may take longer, since the data comes through the backend server.

Type 4 JDBC Driver

Native-protocol/all-Java driver

The Type 4 uses java networking libraries to communicate directly with the database
server.

Type 4: Native-protocol/all-Java driver

Advantage

1. The major benefit of using a type 4 jdbc drivers are that they are completely written in
Java to achieve platform independence and eliminate deployment administration issues. It
is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to
translate database requests to ODBC or a native connectivity interface or to pass the
request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers
can be downloaded dynamically.

Disadvantage

With type 4 drivers, the user needs a different driver for each database.

19

24)

Can you write code for steps of JDBC Connection?

Connecting to a database using JDBC type 4 driver includes the
following steps:
Step1: Loading the driver.
Class.forName(“oracle.jdbc.driver.OracleDriver”);

Step2: Connecting the driver to the DBMS usong DSN or URL.
String url = “jdbc:oracle:thin:@localhost:1521:orcl”;
Connection con = DriverManager.getConnection(url, “scott”, “tiger”);

Step3: Creating a statement or preparedStatement object
Statement st = con.createStatement();

Step4: The SQl query is passed to the database and the result is
collected in an appropriate object or variable

ResultSet rs = st.executeQuery()
// above is used for select queries
int i = st.executeUpdate()
// above is used for update. Returns 1 – on success and 0 –
on failure.
Boolean bool = st.execute()
// above is used for preparedStatement, store procedure or
any type of query. Returns true- on success and false – on
failure.

(i)

(ii)

(iii)

25)
Which JDBC Connection do you use in your application?
Why? Can you write its code?

Type 4 JDBC driver. Refer to above question for its code.

Reasons for using Type 4 JDBC driver:
1. The major benefit of using a type 4 jdbc drivers are that they are
completely written in Java to achieve platform independence and
eliminate deployment administration issues. It is most suitable for
the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers
don't have to translate database requests to ODBC or a native
connectivity interface or to pass the request on to another server,
performance is typically quite good.
3. We don’t need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.

20

26)
What is the difference between a Statement and a
PreparedStatement ?

http://jguru.com/faq/view.jsp?EID=693

1. The PreparedStatement is a slightly more powerful version of a
Statement, and should always be at least as quick and easy to handle as
a Statement.
2. The PreparedStatement may be parametrized.

Longer answer: Most relational databases handles a JDBC / SQL query in
four steps:

Step1. Parse the incoming SQL query
Step 2. Compile the SQL query
Step 3. Plan/optimize the data acquisition path
Step 4. Execute the optimized query / acquire and return data

A Statement will always proceed through the four steps above for each
SQL query sent to the database. A PreparedStatement pre-executes
steps (1) - (3) in the execution process above. Thus, when creating a
PreparedStatement some pre-optimization is performed immediately. The
effect is to lessen the load on the database engine at execution time.

27)

What is a CallableStatement?

http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/callablestatement.html

Callable statement is the one of the SQL statement.
It is used to execute stored procedures
using prepareCall() method.

28)
In our program, we are inserting data into three tables
in the database. If we want that either data enters in all three
tables successfully or not in any table at all. How can you
achive this? Please write code for this.

Actually, this is a typical example where we want the process to be
transaction secure.
For this, we need to do the following:

Con.setAutoCommit(false);

21

Int i = st.executeUpdate(s1);
Int j = st.executeUpdate(s2);
Int k = st.executeUpdate(s3);

if((i==0)|| (j==0)|| (k==0)) //i.e if any of the updates //
failed
{
con.rollBack();
}
else
// all the updates were successful

{

con.commit()

}

Multithreading

29)

Different states of a thread are:

What is a thread’s lifecycle?

http://www.roseindia.net/java/thread/life-cycle-of-threads.shtml

22

1. New state – After the creations of Thread instance the thread is in this state but
before the start() method invocation. At this point, the thread is considered not
alive.

2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A
thread first enters runnable state after the invoking of start() method but a thread
can return to this state after either running, waiting, sleeping or coming back from
blocked state also. On this state a thread is waiting for a turn on the processor.

3. Running state – A thread is in running state that means the thread is currently
executing. There are several ways to enter in Runnable state but there is only one
way to enter in Running state: the scheduler select a thread from runnable pool.

4. Dead state – A thread can be considered dead when its run() method completes.
If any thread comes on this state that means it cannot ever run again.

5. Blocked - A thread can enter in this state because of waiting the resources that are
hold by another thread.

30)
What is the difference between extending Thread class
and implementing Runnable interface? Which one do you
prefer to use and why?

23

Extending the Thread class will make your class unable to extend other
classes, because of the single inheritence feature in JAVA. However, this
will give you a simpler code structure. If you implement runnable, you can
gain better object-oriented design and consistency and also avoid the
single inheritance problems.

Another point is that implementing Runnable does not create a Thread
object, it only defines an entry point for threads in your object (it allows
you to pass the object to the Thread(Runnable) constructor).

31)

What is a “Race” condition ? How would you solve it?

A race condition is a situation in which two or more threads or
processes are reading or writing some shared data, and the final
result depends on the timing of how the threads are scheduled.
Race conditions can lead to unpredictable results and subtle
program bugs. A thread can prevent this from happening by locking
an object. When an object is locked by one thread and another
thread tries to call a synchronized method on the same object, the
second thread will block until the object is unlocked.

Serialization
32)
What is serialization and deserialization?

Serialization is the process by which a java object can be saved in
its present state to a file or network stream.
The object can be re-constructed through the process of
deserialization.
For achieving serialization, we need to implement the Serializable
interface. It is a marker interface, i.e. it does not contain any
methods.

Transient and static variables are NOT SAVED by serialization.
Transient variables must be recreated during deserialization.
Examples of transient variables are file or socket references.

Reason for keeping these variables as transient

Restoring a variable that represented a file reference would likely
be inconsistent (or may not even apply to the machine that is executing
deserialization) and should be re-constructed from scratch – usually
by invoking the same method that originally populated it.

24

33)
Are transient and static variables saved during
serialization?

34)

No, transient and static variables are NOT saved during
serialization

Can you write code for File Input and Output?

It can be explained in the three steps as explained below:

Step1: Creating a file

FileOutputStream fos = new FileOutputStream("c://f.dat",
true);

Step2: Writing into the file

char c = 'm';
fos.write(c);

Step3: Reading from the file

FileInputStream fis = new FileInputStream("c://f.dat",
true);
while(fis.read() != -1)
{
int i = fis.read();
char ch = (char)i;
System.out.println(ch);
}

35)

Can you write code for serialization and deserialization?

Serialization:
It can be explained in the three steps as explained below:

Step1: Creating a file

FileOutputStream fos = new FileOutputStream("c://f.dat",
true);

Step2 Creating the ObjectOutputStream to be able to write the
object ob into the file “f.dat”

ObjectOutputStream oos = new ObjectOutputStream(fos);
// actually writing the data of the object ob into the file
oos.write(ob);

Step3: Closing the ObjectOutputStream

25

oos.close();

// close the ObjectOutputStream

De-serialization:
It can be explained in the steps as explained below:

Step1: Creating a FileInputStream

FileInputStream fis = new FileInputStream ("f.dat");

Step2 Creating the ObjectInputStream to be able to read the object
from the file “f.dat” through fis

ObjectInputStream oos = new ObjectInputStream (fis);
// actually reading the data of the object ob from the file
objSerial obj = (objSerial)ois.readObject(ob);

Database

36)
What is a stored procedure? Can you write a sample
stored procedure?

A stored procedure is a set of SQL commands that has been
compiled and stored on the database server.

Benefits of Stored Procedures
Why should you use stored procedures? Let's take a look at the key
benefits of this technology:

* Precompiled execution. SQL Server compiles each stored
procedure once and then reutilizes the execution plan. This results
in tremendous performance boosts when stored procedures are
called repeatedly.
* Reduced client/server traffic. If network bandwidth is a
concern in your environment, you'll be happy to learn that stored
procedures can reduce long SQL queries to a single line that is
transmitted over the wire.
* Efficient reuse of code and programming abstraction.
Stored procedures can be used by multiple users and client
programs. If you utilize them in a planned manner, you'll find the
development cycle takes less time.
* Enhanced security controls. You can grant users permission
to execute a stored procedure independently of underlying table
permissions.


No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...