Você está na página 1de 30

Spring:

IOC/Dependency Injection:
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that
you do not create your objects but describe how they should be created. You don't directly
connect your components and services together in code but describe which services are needed
by which components in a configuration file. A container (in the case of the Spring framework, the
IOC container) is then responsible for hooking it all up.

Final Class:

A final class can not be extended. A final method can not be overridden. Main() method in java is
public, static and final, so that it can not be overridden and JVM can call it without creating any
instance of the class.
Since the final class can not be extended so there is always a compiler error if we define an
abstract method in it.

All classes in Java implicitly extend Object class.

The code
int i = 0;
i = i++;
System.out.println(i);
produces the output "0" instead of "1". Why?

Let's take a close look at what the line "i = i++;" does:

1. "i++" is evaluated. The value of "i++" is the value of i before the increment
happens.
2. As part of the evaluation of "i++", i is incremented by one. Now i has the
value of 1;
3. The assignment is executed. i is assigned the value of "i++", which is the
value of i before the increment - that is, 0.

That is, "i = i++" roughly translates to

int oldValue = i;
i = i + 1;
i = oldValue;

With other words, it is a common misconception that the increment is happening


last. The increment is executed immediately when the expression gets evaluated,
and the value before the increment is remembered for future use inside the same
statement.

Solution:
You don't need the assignment at all, just use

i++;

Hi nikki,
this is what is happening:
i=2; //you are assigning the variable i to the value of 2
i=i++; //you are assigning i to i, which is 2 so i = 2,
//increment here, but the incremented value did not get assigned to anything so i=2,

See also

• http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.
14.2
• http://www.coderanch.com/t/244938/java-programmer-
SCJP/certification/post-increment-confusion
• http://radio.javaranch.com/corey/2004/06/03/1086277171000.html

public class Test1 {


static int i;
public static void main(String args[]){
//i=2;
for(int x=0;x<3;x++){
//i++;
i=x++; // 0,
System.out.println("::"+i);
}
int count=0;
int j=0;
while(j<4) {
count += j++;
System.out.println(count);
}
// System.out.println("Count is: "+count);
}

}
In this case the output is always: 2 2 2
If we open the a section then the result is : 3 4 5
Value of count is 6 here.

Connection Pooling:
A connection pooling is a pool of open connections.
The connection objects are used when required and released after they are done.
Thus the overhead of creating a connection object and establishing the connection
with the database is greatly reduced.

There is one problem with connection pooling. A web application has to explicitly
close ResultSet's, Statement's, and Connection's. Failure of a web application to
close these resources can result in them never being available again for reuse, a db
connection pool "leak". This can eventually result in your web application db
connections failing if there are no more available connections.

the class.forName creates a instance of the driver and registers it with


DriverManager Class. While the driver is loaded it creates a connection to the db.

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the
jdbc calls into vendor specific protocol calls and it directly interacts with the
database.

Use of the JDBC Data Sources JNDI Resource Factory requires that you make an
appropriate JDBC driver available to both Tomcat internal classes and to your web
application. This is most easily accomplished by installing the driver's JAR file(s) into
the$CATALINA_HOME/common/lib directory, which makes the driver available both
to the resource factory and to your application.

New Updates in JDBC 2.0

Creating a scrollable ResultSet:

Statement stmt = con.createStatement(


ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME,
PRICE FROM COFFEES");
This code is similar to what you have used earlier, except that it adds two arguments to the
method createStatement. The first new argument must be one of the three constants added to
the ResultSet interface to indicate the type of
a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE,
or TYPE_SCROLL_SENSITIVE. The second new argument must be one of the
two ResultSet constants for specifying whether a result set is read-only or
updatable: CONCUR_READ_ONLY or CONCUR_UPDATABLE.
Specifying the constant TYPE_FORWARD_ONLY creates a non scrollable result set, that is, one in which
the cursor moves only forward. If you do not specify any constants for the type and updatability, you will
automatically get the default, which is a ResultSet object that
is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY (as has always been the case).
Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made
while it is still open, and one that is TYPE_SCROLL_SENSITIVE does.
Previous, next, afterlast, first, last, beforeFirst are the methods in scrollable
ResultSets.

srs.absolute(4); // cursor is on the fourth row


The method getRow lets you check the number of the row where the cursor is currently positioned.
int rowNum = srs.getRow(); // rowNum should be 4

Four additional methods let you verify whether the cursor is at a particular position. The position is stated in
the method names: isFirst, isLast, isBeforeFirst, isAfterLast. These methods all return
a boolean and can therefore be used in a conditional statement.

The method absolute will move the cursor to the row number indicated in the argument passed to it.
For example, suppose you have iterated through some rows in a result set and want to print two columns
from the current row. To be sure that the cursor has not gone beyond the last row, you could use code such
as the following, in which srs is a scrollable ResultSet object.
if (!srs.isAfterLast()) {
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}
Before you can make updates to a ResultSet object, you need to create one that is updatable. In order to
do this, you supply the ResultSet constant CONCUR_UPDATABLE to thecreateStatement method.
The Statement object that is created will produce an updatable ResultSet object each time it
executes a query. The following code fragment illustrates creating the updatable ResultSet object uprs

Connection con = DriverManager.getConnection(


"jdbc:mySubprotocol:mySubName");
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT COF_NAME,
PRICE FROM COFFEES");

uprs.last();
uprs.updateFloat("PRICE", 10.99f);
Update operations in the JDBC 2.0 API affect column values in the row where the cursor is positioned, so in
the first line, the ResultSet uprs calls the method last to move its cursor to the last row (the row
where the column COF_NAME has the value 'French_Roast_Decaf' ). Once the cursor is on the last
row, all of the update methods you call will operate on that row until you move the cursor to another row.
The second line changes the value in the PRICE column to 10.99 by calling the method updateFloat.
This method is used because the column value we want to update is a floatin the Java programming
language.

Making a Batch Updates:

JDBC auto-commit mode


By default, JDBC uses an operation mode called auto-commit. This means that every
update to the database is immediately made permanent.

Any situation where a logical unit of work requires more than one update to the
database cannot be done safely in auto-commit mode. If something happens to the
application or the system after one update is made and before any other updates are
made, the first change cannot be undone when running in auto-commit mode.

Because changes are instantly made permanent in auto-commit mode, there is no


need for the application to call the commit method or the rollback method. This
makes applications easier to write.

Auto-commit mode can be enabled and disabled dynamically during a connection's


existence. Auto-commit is enabled in the following way, assuming that data source
already exists:

Connection connection = dataSource.getConnection();

Connection.setAutoCommit(false); // Disables auto-commit.


Batch update is a set of multiple update statements that is submitted to the database for processing as a
batch. Sending batch updates can, in some situations, be much more efficient than sending update
statements separately. This ability to send updates as a unit, referred to as the batch update facility, is one
of the new features provided with the JDBC 2.0 core API.
con.setAutoCommit(false);
Statement stmt = con.createStatement();

stmt.addBatch("INSERT INTO COFFEES " +


"VALUES('Amaretto', 49, 9.99, 0, 0)");
stmt.addBatch("INSERT INTO COFFEES " +
"VALUES('Hazelnut', 49, 9.99, 0, 0)");
stmt.addBatch("INSERT INTO COFFEES " +
"VALUES('Amaretto_decaf', 49,
10.99, 0, 0)");
stmt.addBatch("INSERT INTO COFFEES " +
"VALUES('Hazelnut_decaf', 49,
10.99, 0, 0)");

int [] updateCounts = stmt.executeBatch();


con.commit();
con.setAutoCommit(true);

You should not add a query (a SELECT statement) to a batch of SQL commands because the
method executeBatch, which returns an array of update counts, expects an update count from each
SQL command that executes successfully. This means that only commands that return an update count
(commands such as INSERT INTO, UPDATE, DELETE) or that return 0 (such as CREATE
TABLE, DROP TABLE, ALTER TABLE) can be successfully executed as a batch with
the executeBatch method.
BatchUpdateException is derived from SQLException. This means that you can use all of the
methods available to an SQLException object with it. The following code fragment prints all of
theSQLException information plus the update counts contained in
a BatchUpdateException object.
Because BatchUpdateException.getUpdateCounts returns an array of int, the code uses
afor loop to print each of the update counts.

try {
// make some updates
} catch(BatchUpdateException b) {
System.err.println("----BatchUpdateException----");
System.err.println("SQLState: " + b.getSQLState());
System.err.println("Message: " + b.getMessage());
System.err.println("Vendor: " + b.getErrorCode());
System.err.print("Update counts: ");
int [] updateCounts = b.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++) {
System.err.print(updateCounts[i] + " ");
}
System.err.println("");
}

Context initCtx = new InitialContext();


Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");

Connection conn = ds.getConnection();


... use this connection to access the database ...
conn.close();
RowSet:
A RowSet object contains a set of rows from a result set or some other source of tabular data.
Rowsets may have many different implementations to fill different needs. These implementations fall into
two broad categories, rowsets that are connected and those that are disconnected. A disconnected rowset
gets a connection to a data source in order to fill itself with data or to propagate changes in data back to the
data source, but most of the time it does not have a connection open. While it is disconnected, it does not
need a JDBC driver or the full JDBC API, so its footprint is very small. Thus a rowset is an ideal format for
sending data over a network to a thin client

1. There are _____ types of Comments in Java


Answer: Three
2. Java is Architectural _____________
Answer: Neutral
3. Java provides a Firewall between a networked application and your computer.
Answer: True
4. Java is Not designed for the distributed environment of the Internet
Answer: True
6. Inheritance interacts with encapsulation also.
Answer: True
7. Which of the following will change to the next directory above the current
directory?
Answer: none of the above
8. _________ are light-weight components
Answer: Swings
9. _________ is used to destroy the objects created by the constructor methods.
Answer: finalize()
10. Thread class is defined in the package ______
Answer: java.lang

ArrayList and LinkList:

If your program frequently provides random access to the data of the list, the
ArrayList class offers quick access to individual elements of the list. This quick access
comes at a cost of slower operations for adding and removing in the middle of the
list.
If this latter behavior is what you desire, than the LinkedList class offers a better
alternative. It provides quick sequential access, additions, and deletes, at a cost of
slower random access.

// Demonstrate iterators.
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {

Object element = itr.next();


System.out.print(element + " ");

}
System.out.println();
// modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext()) {

Object element = litr.next();


litr.set(element + "+");

}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {

Object element = itr.next();


System.out.print(element + " ");

}
System.out.println();
// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {

Object element = litr.previous();


System.out.print(element + " ");

}
System.out.println();
}
}

The iterators returned by this class's iterator and listIterator methods are fail-fast: if
the list is structurally modified at any time after the iterator is created, in any way
except through the Iterator's ownremove or add methods, the iterator will throw
a ConcurrentModificationException. Thus, in the face of concurrent modification, the
iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic
behavior at an undetermined time in the future.

Difference between include directive and jsp standard include action:


JSP include directive inserts the source code of the included page
during translation time.
JSP standard include action inserts the response of the included file
at runtime.

JSTL:

<c:forEach var=”item” items=”movieList”>


<c:out value=”$item”
</c:forEach>

Begin, end tags are used to bind the limits.


varStatus can be used as a counter.

Enhanced for loop:


For(Objecttype var:actual_object)
System.out.println(var);

Iterator itr = al.iterator();


while(itr.hasNext()) {

Object element = itr.next();


System.out.print(element + " ");

<c:if test=”{}”>
</c:if> does not contain a else tag.
So in such situation <c:choose> should be used.
<c:choose>
<c:when test=”{}”>
</c:when>
<c:otherwise>
</c:otherwise>
<c:choose>

<c:set>, <c:url> for encoding url, <c:redirect>

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>


<html>
<head>
<title>Import a Page</title>
</head>
<body><frame name="frame1">
<form method="POST">
<p>Enter 1 for http://www.roseindia.net<br>
Enter 2 for http://www.google.com<br>
Enter 3 for http://www.yahoo.com<br>
Enter 4 for http://www.msn.com<br>
<table >
<tr>
<td>Enter Your Choice </td>
<td>
<input type="text" name="choice" size="20"/>
</td>
<td><input type="submit" value="submit"/></td>
</tr>
</form></frame>
<c:if test="${pageContext.request.method=='POST'}">
<c:choose>
<c:when test="${param.choice=='1'}">
<c:redirect url="http://www.roseindia.net"/>
</c:when>
<c:when test="${param.choice=='2'}">
<c:redirect url="http://www.google.com"/>
</c:when>
<c:when test="${param.choice=='3'}">
<c:redirect url="http://www.yahoo.com"/>
</c:when>
<c:when test="${param.choice=='4'}">
<c:redirect url="http://www.msn.com"/>
</c:when>
<c:otherwise>
<font color="red"><b>Found wrong choice, try
again...</font></b>
</c:otherwise>
</c:choose>
</c:if>
</body>
</html>

Generics:

ArrayList<String> al=new ArrayList<String>();


Generics provides a way to communicate the type of a collection to the
compiler.

CopyOnWriteArrayList

When the iterator is first created it refers state of the arraylist which never changes
during the life time of the iterator.

Hence the iterator will not reflect any change like addition, deletion to the underlying
arraylist since the iteratore is created.

It does not throw ConcurrentModificationException

Class.forName() returns the Class object associated with the class or interface with
the given string name.

Difference between Scriptlet and expressions:

With expressions in JSP the results of evaluating the expression are converted to a string and
directly included within the output page. Typically expressions are used to display simple
values of variables or return values by invoking a bean's getter methods. JSP expressions begin
within < = ... > tags and do not include semicolons:
But scriptlet can contain any number of language statements variable or method declarations
or expressions that are valid in the page scripting language. Within scriptlet tags you can
declare variables or methods to use later in the file write expressions valid in the page
scripting language use any of the JSP implicit objects or any object declared with a .

Scopes of Attributes:

Request, session, context

<jsp:useBean id="connection" class="com.myco.myapp.Connection">


<jsp:setProperty name="connection" property="timeout"
value="33">
</jsp:useBean>
<jsp:getProperty name="user" property="name" />

${pageScope.objectName.attributeName}.

sessionScope.name} <%-- evaluates to John Doe --%>

${requestScope.objectName.attributeName}.

Expression Language:

It helps to easily access application data stored in java beans.

Exception implicit object is available to the specified jsp error page.

We can declare error page for a specific exception type and error code in Deployment Descriptor.

Default is page scope.

Module description in struts:

<init-param>
<param-name>config</param-name>
<param-value>WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>config/mod1</param-name>
<param-value>WEB-INF/mod1-config.xml</param-value>
</init-param>

Switch Action:

A standard Action that switches to a new module and then forwards control to a URI
(specified in a number of possible ways) within the new module.

Valid request parameters for this Action are:

• page - Module-relative URI (beginning with "/") to which control should be


forwarded after switching.
• prefix - The module prefix (beginning with "/") of the module to which
control should be switched. Use a zero-length string for the default module.
The appropriate ModuleConfig object will be stored as a request attribute, so
any subsequent logic will assume the new module.

EJB:

Enterprise java beans are server side software components that can be deployed in a
distributed multitier environment.

EJB server provides the following services like concurrency, security, transaction
management, persistence etc.

When a client invokes a method to a bean the server steps into the middle of each
method call and provide these services.

Entity bean is persistence in nature and represent persistence data stored in a


database.

Session bean model a business process.

Message Driven Beans are like session beans and they can be called by sending
messages to them.

They might call other enterprise bean an asynchronous in nature.

An EJB object is a request interceptor between a client and the bean. It delegates all
client requests to the bean.

EJB Home instantiates EJB objects and client code gets the reference from the home
object.

Statefull session bean: retains client state and thus service multiple request of the
same client.

Stateless session bean:

On calling create () method remote EJB Object will be created but when client will
invoke a business method then only bean will come out of pool and will server the
method. So a stateless bean instance can serve for several business methods call in
its life, without knowing for which client.

Lifecycle of the stateless session bean:

Initially a bean is in does not exist state. When container decides that a bean
instance is needed in the pool to service client request then container creates bean
instance by calling the following methods:

Class.newInstance(), setSessionContext(), ejbCreate();

Now the bean instance is in method ready state to service client request. Container
calls the ejbRemove() method if it decides that pool does not require so many beans.
Lifecycle of Statefull session bean:

Initially a Statefull bean is in doesn’t exists state. When client calls create method on
the home interface a bean instance is created and is ready to service the client
request. Client calls business method on the bean. If the client is not active then the
bean goes to passivated state and is again activated on clients method call.

The bean is destroyed when client calls remove method on the bean instance.

Asynchronous means client sends a request to the remote server and continues
doing other work.

Java messaging service:

JMS asynchronous messaging comes in two flavors:

1) Queue: Message sent to a single user.


2) Topic: Message is broadcasted to a channel and can be received by more than
one user.

Two or more client can communicate with each other asynchronously by using JMS
API.

Message Driven Bean is designed to consume asynchronous JMS message.

Entity Bean:

The existing entity bean can be find out by calling finder method that starts with
ejbFind().

Rules for finder method:

You must have one finder method called ejbFindByPrimaryKey. This method finds
one unique entity bean instance in the database.

Bean Managed Persistence (BMP) and Container Managed Persistence (CMP)

** How session bean is integrated in Enterprise application in JBoss application


server.

EJB-QL is an object-oriented SQL-like syntax for querying entity beans.


CMP entity beans can have special ejbSelect() methods.

EJB transactions:

Both declarative and programmatic transactions are handles by JTS (Java


Transaction Services)
Transaction Attributes:

The Enterprise JavaBeans model supports six different transaction rules:

• TX_BEAN_MANAGED. The TX_BEAN_MANAGED setting indicates that the


enterprise bean manually manages its own transaction control. EJB supports
manual transaction demarcation using the Java Transaction API. This is very
tricky and should not be attempted without a really good reason.

• TX_NOT_SUPPORTED. The TX_NOT_SUPPORTED setting indicates that the


enterprise bean cannot execute within the context of a transaction. If a client
(i.e., whatever called the method-either a remote client or another enterprise
bean) has a transaction when it calls the enterprise bean, the container
suspends the transaction for the duration of the method call.

• TX_SUPPORTS. The TX_SUPPORTS setting indicates that the enterprise bean


can run with or without a transaction context. If a client has a transaction
when it calls the enterprise bean, the method will join the client's transaction
context. If the client does not have a transaction, the method will run without
a transaction.

• TX_REQUIRED. The TX_REQUIRED setting indicates that the enterprise bean


must execute within the context of a transaction. If a client has a transaction
when it calls the enterprise bean, the method will join the client's transaction
context. If the client does not have a transaction, the container automatically
starts a new transaction for the method. Attributes

• TX_REQUIRES_NEW. The TX_REQUIRES_NEW setting indicates that the


enterprise bean must execute within the context of a new transaction. The
container always starts a new transaction for the method. If the client has a
transaction when it calls the enterprise bean, the container suspends the
client's transaction for the duration of the method call.

• TX_MANDATORY. The TX_MANDATORY setting indicates that the enterprise


bean must always execute within the context of the client's transaction. If the
client does not have a transaction when it calls the enterprise bean, the
container throws the Transaction Required exception and the request fails.

The JTA consists of two interfaces:


1. javax.transaction.UserTransaction
2. javax.transaction.Status

The javax.transaction.UserTransaction interface allows you to programmatically


control transactions. Here is what the javax.transaction.UserTransaction interface
looks like:
public interface javax.transaction.UserTransaction
{ public void begin();
public void commit();
public int getStatus();
public void rollback();
public void setRollbackOnly();
public void setTransactionTimeout(int);
}

Truncate and Delete:

TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is
released back to the server.
DELETE is a DML command and can be rolled back.

Java Reflection:

It supports dynamic retrieval of information about a class in runtime and


manipulates them.

It helps to find what data fields and methods are used in the class.

ThreadLocal:

This class provides thread-local variables. These variables differ from their normal
counterparts in that each thread that accesses one (via its get or set method) has its
own, independently initialized copy of the variable. ThreadLocal instances are
typically private static fields in classes that wish to associate state with a thread
(e.g., a user ID or Transaction ID).

For example, in the class below, the private static ThreadLocal instance (serialNum)
maintains a "serial number" for each thread that invokes the class's
static SerialNum.get() method, which returns the current thread's serial number. (A
thread's serial number is assigned the first time it invokes SerialNum.get(), and
remains unchanged on subsequent calls.)

public class MainClass {


public static void main(String[] args) {
Ball b = new Ball() {
public void hit() {
System.out.println("You hit it!");
}
};
b.hit();
}

interface Ball {
void hit();
}
}

Garbage collection is an automatic memory management in Java. With the help of this
methodology JVM destroys all the objects which are no longer in used and allocate
memory space.
The finalize method is used to close all the non java resources before the object is
garbage collected.
Immutable Class:

Declare the class final; declare the variable private final, only getter method.

JVM is the java byte code interpreter and JRE does not include any development
environment. JRE includes JVM.

Wrapper Class:

In the Java language, the eight primitive types


--- boolean, byte, char, short, int, long, float, double --- are not objects. However, in
certain situations, objects are required. For example, collection classes such
as Map and Set only work with objects. This issue is addressed by wrapping a primitive type
in a wrapper object. There is a wrapper object for each primitive type.
This example demonstrates how to wrap the value of a primitive type in a wrapper object and
then subsequently retrieve the value of the primitive type.

HashCode:

If the String class did not implement its own version of the equals method
comparing two Strings would compare the memory address rather than the
character sequence. This is rarely what you would want, and for this reason the
String class implements it's own version of the equals method that makes a
character by character comparison.

Objects that are equal according to the equals method must return the same
hashCode value
If two objects are not equal according to equals, they are not required to
return different hashCode values.

The String class has its own implementation of the hashCode method. If it did not it
would have inherited the hashCode method from Object which simply returns the
memory address of the class instance.
Be careful of any quesiton that uses the word always. The default inmplementation
of hashCode for the Object class is to return the memory address of the object. A
little knowledge of how Java works will tell you that there is no guarantee that an
object will have the same memory address from one execution to another. A
hashCode method must return the same value during the same run of a program but
not necessarily from one program run to another. If you do a test on the hashCode
of an instance of object you may find it seems to return the same memory address
during multiple program runs, but there is no guarantee of this.

Native method in Java:

Singleton Class:

Singleton class creates only one instance of a class.


The instance reference variable of the class must be defined as private, static
The constructor should be private
The global accessor method of the class instance should be public static.
Lazy initiatialization of singleton class:
If(singtoninstce==null){

sintoninstce=new Singleton();
}

Else return sintoninstce;

But this is not thread safe and we need to make the accessor method synchronized
for thread safe.

For early initialization always create the instance of the singleton class when it loads.
The accessor method will return the instance.

Sorting Using Comparator and Comparable interface:

Comparator – compare(Object o1, Object o2)


Comparable – compareTo(Object o1);

Hashing:

The answer is that the array will not hold the keys. From the key object, a number will be derived
that will index into the array. This number is the hash code, produced by the hashCode( ) method
(in computer science parlance, this is the hash function) defined in Object and presumably
overridden by your class. To solve the problem of the fixed-size array, more than one key may
produce the same index. That is, there may be collisions. Because of this, it doesn’t matter how
big the array is because each key object will land somewhere in that array. So the process of
looking up a value starts by computing the hash code and using it to index into the array. If you
could guarantee that there were no collisions (which could be possible if you have a fixed number
of values) then you’d have a perfect hashing function, but that’s a special case. In all other cases,
collisions are handled by external chaining: the array points not directly to a value, but instead to
a list of values. These values are searched in a linear fashion using the equals( ) method. Of
course, this aspect of the search is much slower, but if the hash function is good there will only be
a few values in each slot, at the most. So instead of searching through the entire list, you quickly
jump to a slot where you have to compare a few entries to find the value. This is much faster,
which is why the HashMap is so quick.

protected void finalize() throws Throwable {}


• every class inherits the finalize() method from java.lang.Object
• the method is called by the garbage collector when it determines no
more references to the object exist
• the Object finalize method performs no actions but it may be overridden
by any class
• normally it should be overridden to clean-up non-Java resources ie
closing a file
• if overridding finalize() it is good programming practice to use a try-
catch-finally statement and to always call super.finalize() (JPL pg 47-48).
This is a saftey measure to ensure you do not inadvertently miss closing a
resource used by the objects calling class
protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize();
}
}
• any exception thrown by finalize() during garbage collection halts the
finalization but is otherwise ignored
• finalize() is never run more than once on any object

calling finalize method


system.gc();

Runtime.getRuntime().gc();

when creating your own classes to add to a HashSet remember to override hashCode().
The TreeSet implementation is useful when you need to extract elements from a collection in
a sorted manner. In order to work property, elements added to a TreeSet must be sortable.
The Collections Framework adds support for Comparable elements and will be covered in
detail later. For now, just assume a tree knows how to keep elements of
the java.lang wrapper classes sorted. It is generally faster to add elements to a HashSet,
then convert the collection to a TreeSet for sorted traversal.

Use of TreeSet:

We can create a collection of duplicate objects. But if we put add them to a HashSet, there will
not be any duplicate object.
But if we create a TreeSet with the hashset then the objects will be automatically sorted by
natural order.
If the objects are of a class defined by us then we have to override the hashcode method and
then implement the comparable interface to sort them using hashset.

import java.util.*;

public class SetExample {


public static void main(String args[]) {
Set set = new HashSet();
set.add("Bernadine");
set.add("Elizabeth");
set.add("Gene");
set.add("Elizabeth");
set.add("Clara");
System.out.println(set);
Set sortedSet = new TreeSet(set);
System.out.println(sortedSet);
}
}

For retrieving an object by name hashmap is best solution. It is not synchronized like
hashtable and hence performace is better. For treemap the elements must be sortable.
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative.

Know about special arrayList


SynchronizedList
Thread
Hibernet

Data Manipulation Language (DML) statements are used for managing data within schema
objects.
iBATIS:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
<settings useStatementNamespaces="true"/>
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL"
value="jdbc:mysql://192.168.10.112:3306/vin"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value="root"/>
</dataSource>
</transactionManager>
<sqlMap resource="Contact.xml"/>
</sqlMapConfig>

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="Contact">
<!--- Inserting data in table -->

<insert id="insert" parameterClass="Contact">


insert into contact (firstName,lastName,email)
values (#firstName#, #lastName#, #email#)
<selectKey resultClass="int" keyProperty="id">
select last_insert_id() as id
</selectKey>
</insert>
<!--- Showing all data of table -->
<select id="getAll" resultClass="Contact">
select * from contact
</select>
</sqlMap>

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisInsertion{


public static void main(String[] args) throws IOException,SQLExceptio
n{
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reade
r);
//Inserting one record in contacts
System.out.println(

"*-------------- Inserting information in Contact Table -----------*");


Contact contact=new Contact("Amit","Kumar","amit@roseindia.net");
sqlMap.insert("Contact.insert",contact);
System.out.println("|Record Inserted Successfully ");
System.out.println("All Contacts");
List<Contact> contacts = (List<Contact>)
sqlMap.queryForList("Contact.getAll",null);
Contact contactall = new Contact();
for (Contact c : contacts) {
System.out.print(" " + c.getId());
System.out.print(" " + c.getFirstName());
System.out.print(" " + c.getLastName());
System.out.print(" " + c.getEmail());
contact = c;
System.out.println("");
}
System.out.println("=============================================
==");
}
}

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="Contact">
<!--- Delete data from Contact table -->
<delete id="deleteAll" parameterClass="Contact">
delete from Contact
</delete>
<!--- Showing all data of table -->
<select id="getAll" resultClass="Contact">
select * from contact
</select>
</sqlMap>
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisDeletion{


public static void main(String[] args)
throws IOException,SQLException{
Reader reader = Resources.getResourceAsReader("Sq
lMapConfig.xml");
SqlMapClient sqlMap =
SqlMapClientBuilder.buildSqlMapClient(reader);
//Deleting all records from contacts
System.out.println("*-- Deleting informations fro
m Contact------*");
Contact contct=new Contact();
sqlMap.delete("Contact.deleteAll",contct);
System.out.println("|Deleted Record Successfully
");
System.out.println("All Contacts");
List<Contact> contacts = (List<Contact>)
sqlMap.queryForList("Contact.getAll",null);
Contact contact = null;
for (Contact c : contacts) {
System.out.print(" " + c.getId());
System.out.print(" " + c.getFirstName());
System.out.print(" " + c.getLastName());
System.out.print(" " + c.getEmail());
contact = c;
System.out.println("");
}
System.out.println("=============================
===============");
}
}

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="Contact">
<!--- Showing all data of table -->
<select id="getAll" resultClass="Contact">
select * from contact
</select>
<!--- Update data of Contact table -->
<update id="updateById" parameterClass="long">
update Contact
set
lastName = 'Raghuwanshi'
where
id=#id#
</update>
</sqlMap>

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisUpdate{


public static void main(String[] args)
throws IOException,SQLException{
Reader reader = Resources.getResourceAsReader(
"SqlMapConfig.xml"
);
SqlMapClient sqlMap = SqlMapClientBuilder.buildSq
lMapClient(reader);
//Updating one record of contact
System.out.println("*---- Updating informations o
f Contact -----*");
Contact contct=new Contact();
long contactId=1;
sqlMap.update("Contact.updateById",contactId);
System.out.println("|Updated Record Successfull
y ");
System.out.println("All Contacts");
List<Contact> contacts = (List<Contact>)
sqlMap.queryForList("Contact.getAll",null);
Contact contact = null;
for (Contact c : contacts) {
System.out.print(" " + c.getId());
System.out.print(" " + c.getFirstName());
System.out.print(" " + c.getLastName());
System.out.print(" " + c.getEmail());
contact = c;
System.out.println("");
}
System.out.println("=============================
===============");
}
}
f you are working with iBatis Result Map then you must know that iBatis result
maps are used to provide mapping between the result of database query and
object properties of it. And it is the most common and important feature of
iBatis.This section of iBatis tutorial is just an simple introduction
to ResultMap. This will familiarize you that how you can execute an query
with ResultMap.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="Contact">
<!--- Showing data by ID -->
<resultMap id="result" class="Contact">
<result property="id" column="id"/>
<result property="firstName" column="firstName"/>
<result property="lastName" column="lastName"/>
<result property="email" column="email"/>
</resultMap>
<select id="getById" resultMap="result">
select * from contact where id=#id#
</select>
</sqlMap>
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class IbatisResultMap{


public static void main(String[] args)
throws IOException,SQLException{
Reader reader = Resources.getResourceAsReader("Sq
lMapConfig.xml");
SqlMapClient sqlMap =
SqlMapClientBuilder.buildSqlMapClient(reader);
//Output all contacts
System.out.println("*------Information by Contact
Id--------*");
Contact contact =

(Contact)sqlMap.queryForObject("Contact.getById",new
Integer(1));
System.out.println("|Id = " + contact.ge
tId());
System.out.println("|First Name = " + contact.ge
tFirstName());
System.out.println("|Last Name = " + contact.ge
tLastName());
System.out.println("|Email Id = " + contact.ge
tEmail());
System.out.println("=============================
=============");
}
}

Triggers, Cursors & View

If there is frequent update in the table rows then indexing is not a good choice to
optimize query performance.
What is an Index?

An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry
for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes.

CREATE INDEX supplier_idx


ON supplier (supplier_name, city);

TimeStamp and DATE in oracle:

Timestamp includes fractional seconds also whether in DATE difference between fractional events is difficult
to calculate.
T0_Char function is used to format dates in Oracle.
Blob – used to store 4GB of binary data
Clob – used to store 4GB of character data.

A cursor is a mechanism by which you can assign a name to a "select statement" and manipulate the
information within that SQL statement.

For every SQL statement execution certain area in memory is allocated. PL/SQL
allow you to name this area. This private SQL area is called context area or cursor. A
cursor acts as a handle or pointer into the context area. A PL/SQL program controls
the context area using the cursor. Cursor represents a structure in memory and is
different from cursor variable.

When you declare a cursor, you get a pointer variable, which does not point any
thing. When the cursor is opened, memory is allocated and the cursor structure is
created. The cursor variable now points the cursor. When the cursor is closed the
memory allocated for the cursor is released.

For example, you could define a cursor called c1 as below.

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

The result set of this cursor is all course_numbers whose course_name matches the variable called
name_in.

While dealing with cursors, you may need to determine the status of your cursor. The following is a list of the
cursor attributes that you can use.

Attribute Explanation

%ISOPEN - Returns TRUE if the cursor is open, FALSE if the cursor is closed.

%FOUND - Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.
- Returns NULL if cursor is open, but fetch has not been executed.

- Returns TRUE if a successful fetch has been executed.

- Returns FALSE if no row was returned.

%NOTFOUND - Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.

- Return NULL if cursor is open, but fetch has not been executed.

- Returns FALSE if a successful fetch has been executed.

- Returns TRUE if no row was returned.

%ROWCOUNT - Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.

- Returns the number of rows fetched.

- The ROWCOUNT attribute doesn't give the real row count until you have iterated through the entire
cursor. In other words, you shouldn't rely on this attribute to tell you how many rows are in a cursor after
it is opened.

http://www.exforsys.com/tutorials/oracle-9i/oracle-cursors.html

Difference between join and view

In case of view number of request to the server reduces to one.

In general, indexes are used as described in the following discussion. Characteristics specific
to hash indexes (as used in MEMORY tables) are described at the end of this section.

• To quickly find the rows that match a WHERE clause.


• To eliminate rows from consideration. If there is a choice between multiple indexes,
MySQL normally uses the index that finds the smallest number of rows.
• To retrieve rows from other tables when performing joins.

Dependency Injection:

Java components / classes should be as independent as possible of other Java


classes. This increases the possibility to reuse these classes and to test them
independently of other classes(Unit Testing). To decouple Java components from
other Java components the dependency to a certain other class should get
injected into them rather that the class itself creates / finds this object.

A class A has a dependency to class B if class uses class B as a variable.


If dependency injection is used then the class B is given to class A via

• the constructor of the class A - this is then called construction injection


• a setter - this is then called setter injection

The general concept between dependency injection is called Inversion of Control.


A class should not configure itself but should be configured from outside.

A design based on independent classes / components increases the re-usability


and possibility to test the software. For example if a class A expects a Dao (Data
Access object) for receiving the data from a database you can easily create
another test object which mocks the database connection and inject this object
into A to test A without having an actual database connection.

A software design based on dependency injection is possible with standard Java.

Spring just add some simplifications in using dependency injection by providing a


standard way of providing the configuration and by managing the reference to the
created objects.

Scope
This article presents a high level overview of Dependency Injection (DI). It aims to present the
overall concept of Dependency Injection to the junior developer within the context of how it could
be used in a variety of DI containers.

Dependency Injection (DI) or Inversion of Control (IOC) ?

A lot of current literature often refers to the same design pattern as either Dependency Injection
or Inversion of Control. I prefer Dependency Injection from my belief that it is a more specific
name. I can imagine many scenarios where one would find evidence of Inversion of Control,
though the resultant pattern is unlikely to be focusing on resolving dependencies (e.g. moving
from a console application to a Windows Event Loop) . However should you prefer IOC, you can
pretty much read the remainder of the article by replacing DI with IOC. Within IOC there are
various types (creatively called as type 1, type 2, type 3). The differences within these types are
not particularly relevant to the scope of this article and thus not entered into.

Also note that I have used the term Service extensively through this article. This should not be
confused with Service Oriented Architectures. It simply became a lot easier to clarify the roles by
identifying “Clients” and “Services” as opposed to “Client Component” and “Server Component or
Supplier Component”

Simple Introduction to Dependency Injection


A simple introduction
Scenario 1
You work in an organization where you and your colleagues tend to travel a lot. Generally you
travel by air and every time you need to catch a flight, you arrange for a pickup by a cab. You are
aware of the airline agency who does the flight bookings, and the cab agency which arranges for
the cab to drop you off at the airport. You know the phone numbers of the agencies, you are
aware of the typical conversational activities to conduct the necessary bookings.

Thus your typical travel planning routine might look like the following :

• Decide the destination, and desired arrival date and time


• Call up the airline agency and convey the necessary information to obtain a flight
booking.
• Call up the cab agency, request for a cab to be able to catch a particular flight from say
your residence (the cab agency in turn might need to communicate with the airline agency
to obtain the flight departure schedule, the airport, compute the distance between your
residence and the airport and compute the appropriate time at which to have the cab reach
your residence)
• Pickup the tickets, catch the cab and be on your way

Now if your company suddenly changed the preferred agencies and their contact mechanisms,
you would be subject to the following relearning scenarios

• The new agencies, and their new contact mechanisms (say the new agencies offer
internet based services and the way to do the bookings is over the internet instead of over
the phone)
• The typical conversational sequence through which the necessary bookings get done
(Data instead of voice).

Its not just you, but probably many of your colleagues would need to adjust themselves to the
new scenario. This could lead to a substantial amount of time getting spent in the readjustment
process.

Scenario 2

Now lets say the protocol is a little bit different. You have an administration department.
Whenever you needed to travel an administration department interactive telephony system simply
calls you up (which in turn is hooked up to the agencies). Over the phone you simply state the
destination, desired arrival date and time by responding to a programmed set of questions. The
flight reservations are made for you, the cab gets scheduled for the appropriate time, and the
tickets get delivered to you.

Now if the preferred agencies were changed, the administration department would become aware
of a change, would perhaps readjust its workflow to be able to communicate with the agencies.
The interactive telephony system could be reprogrammed to communicate with the agencies over
the internet. However you and your colleagues would have no relearning required. You still
continue to follow exactly the same protocol as earlier (since the administration department did all
the necessary adaptation in a manner that you do not need to do anything differently).

Dependency Injection ?

In both the scenarios, you are the client and you are dependent upon the services provided by
the agencies. However Scenario 2 has a few differences.

• You don't need to know the contact numbers / contact points of the agencies – the
administration department calls you when necessary.
• You don't need to know the exact conversational sequence by which they conduct their
activities (Voice / Data etc.) (though you are aware of a particular standardized
conversational sequence with the administration department)
• The services you are dependent upon are provided to you in a manner that you do not
need to readjust should the service providers change.

Thats dependency injection in “real life”. This may not seem like a lot since you imagine a cost to
yourself as a single person – but if you imagine a large organization the savings are likely to be
substantial.

Dependency Injection in a Software Context

Software components (Clients), are often a part of a set of collaborating components which
depend upon other components (Services) to successfully complete their intended purpose. In
many scenarios, they need to know “which” components to communicate with, “where” to locate
them, and “how” to communicate with them. When the way such services can be accessed is
changed, such changes can potentially require the source of lot of clients to be changed.

One way of structuring the code is to let the clients embed the logic of locating and/or
instantiating the services as a part of their usual logic. Another way to structure the code is to
have the clients declare their dependency on services, and have some "external" piece of code
assume the responsibility of locating and/or instantiating the services and simply supplying the
relevant service references to the clients when needed. In the latter method, client code typically
is not required to be changed when the way to locate an external dependency changes. This type
of implementation is considered to be an implementation of Dependency Injection and the
"external" piece of code referred to earlier is likely to be either hand coded or implemented using
one of a variety of DI frameworks.

Those attempting to map the above scenario to design idioms will notice that the analogy could
be applied to three different design idioms – Dependency Injection, Factory and Program to an
Interface and not an Implementation. As in this analogy these three idioms are often but not
necessarily used together.

The conventional approach till a few years ago was to separate the interface from the
implementation. The factory pattern even allowed for hiding the complexity of instantiation.
However the mechanism to “locate” the services was often left to the clients. Moreover some
parts of the software also needed to be aware of the dependencies between the various services
themselves and thus implicitly had to work out the appropriate sequencing of such component
initialization, and had to track and manage their life cycles.

### Dependency injection is basically giving an object what it needs instead of letting this object
get it by itself.

By applying Dependency Injection in your projects, you’ll find that your code will become
significantly simpler, easier to understand, and easier to test.

When applying Dependency injection(DI), objects are given their dependencies at creation time
by some external entity that coordinates each object in the system. In other words, dependencies
are injected into objects. So, DI means an inversion of responsibility with regard to how an object
obtains references to collaborating objects.

http://www.vogella.de/articles/SpringDependencyInjection/article.html#usagexml
Abstraction:

Means showing essential features without showing internal details.

Encapsulation:
Hiding the data within the class and make them available only through method.

Inheritance:
In inheritance the subclass inherit the fields and methods of the super class. Inheritance helps
us to reuse our code.

String is immutable:

Once a string is created it can not be changed. The reference variable can be made to point to
a different string object. But the original string remains same and if no reference is there then
goes to string constant pool.

String str1=new String (“Hello”);


String str2=new String (“Dhruba”);

Str1=str2;

Here str1 and str2 both are referencing the String “Dhruba” but “Hello” string will still be there
and goes to string constant pool.

Abstract class constructor:

It can have constructor but it can not be instantiated. The subclass calls the constructor of the
abstract class.

JDBC statements:

DDL: DDL is used to define the database structure.


DML: DML is used to managing data in the database.

To execute a query, call an execute method from Statement such as the following:

execute: Returns true if the first object that the query returns is a ResultSet object. Use this
method if the query could return one or more ResultSet objects. Retrieve
the ResultSet objects returned from the query by repeatedly calling Statement.getResutSet.
Use this for DDL (create, drop, rename which are used to define database structure)

executeQuery: Returns one ResultSet object. Use when you expect a resultset object from
the query.

executeUpdate: Returns an integer representing the number of rows affected by the SQL
statement. Use this method if you are using INSERT,DELETE, or UPDATE SQL statements.

SQL JOINS:

Inner Join or Simple Join:

Select Suppliers.supplier_id, Suppliers.supplier_name, Orders.order_date from Supplier inner


join on Orders where Suppliers.supplier_id=Orders.supplier_id.

Outer join:
Select Supplier.supplier_id, Supplier.supplier_name, Orders.order_date from Supplier, Orders
where Supplier.supplier_id(+)=Orders.supplier_id

Select Supplier.supplier_id, Supplier.supplier_name, Orders.order_date from Supplier, Orders


where Supplier.supplier_id=Orders.supplier_id(+)

Você também pode gostar