Java


Some Methods syntax needs to be remembered:
protected Object readResolve() {
return getInstance();
}


protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize (); // This is mandatory to write
}
}
//normally it should be overridden to clean-up non-Java resources ie closing a file

//in singleton classs
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
–pleae note that this method is present in Object class not in Cloneable Interface as it is marker interface

MultiThreading means: thread-safe = true.
Overloading is providing multiple methods with the same name but different arguments (and potentially return type).
Overriding is changing the behavior of a method in a subclass.




Only objects are instantiated in the Java Runtime Environment (JRE) and held in a division of the program's memory allocation called the heap. Stack memory holds primitive values and the memory addresses of objects on the heap.
New Features in JDK1.5
AutoBoxing: it is the automatic conversion of the primitives and wrapper objects.
Boxing is to place a primitive data-type within an object so that the primitive can be used like an object. For example, a List, prior to JDK 1.5, can't store primitive data types. So, to store int type data in a List, a manual boxing was required (i.e from int to integer). Similarly, to retrieve the data back, an unboxing process was required to convert Integer back to int.
The compiler automatically supplies the extra code needed to perform the type conversion.
when Java expects an object but receives a primitive type, it immediately converts that primitive type to an object.
This action is called Autoboxing, because it is boxing that is done automatically and implicitly instead of requiring the programmer to do so manually.
Unboxing is the term for treating an object type as a primitive type without any extra code.

ANOTHER EXAMPLE:
Integer intObject = new Integer(10);

· Before Java 5
· int intPrimitive = intObject.intValue();
· intPrimitive++;
· intObject = new Integer(intPrimitive);
·
· Using Java 5
·
· Integer intObject = new Integer(10);
intObject++;



http://www.javabeat.net/articles/31-autoboxing-in-java-50-1.html
Generics: Allows programmers to specify the types allowed for Collections.

Allows the compiler to enforce the type specifications.
//Before
List stringList //In JDK 1.4
List stringList; //JDK 1.5

ArrayList list = new ArrayList(); //JDK1.5
list.add("Hi");
//... add only String objects
String s = list.get(0); // no cast -- must be a String JDK1.5
String sCaps = s.toUpperCase();

Enhanced for Loop: for iterating over collections and arrays.
Introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable.
for(String s : list)
System.out.println(s);
Extracting Tokens Using Scanner:
String s = "Welcome to Java! Java is fun! Java is cool!";Scanner scanner = new Scanner(s);scanner.useDelimiter("Java");while (scanner.hasNext())System.out.println(scanner.next());
If a token is a primitive data type value, you can use the methods nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain it. For example, the following code adds all numbers in the string. Note that the delimiter is space by default.
String s = "1 2 3 4";
Scanner scanner = new Scanner(s);
int sum = 0;
while (scanner.hasNext())
sum +=scanner.nextInt();
System.out.println("Sum is " + sum)





CLONNING

SHALLOW CLONNING:
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.

DEEP CLONNING:
Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom.

Implementing Deep Copy in Java

For Deep Copy, we need to ensure that the member classes also implement the Cloneable interface otherwise calling the clone() method on the objects of those classes will result into CloneNotSupportedException. So, to implement Deep Copy, we first need to ensure that all the member classes (at all the levels - like if the member class itself has a member of some class type then that class as well... and so on) are implementing the Cloneable interface. After that we override the clone() method in all those classes (even in the classes where we have only primitive type members otherwise we would not be able to call the protected clone()method of Object class on the instances of those classes inside some other class ... a typical restriction of the protected access. We'll cover this in a separate article) and finally calling clone() method on the object members in the overriden clone() method definition.

Ramesh: that means, Implementing the shallow Copy on each and every classes in relation, would be at overall, the deep copy only.

Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
Cloneable is an Marker interface.

Though clone() provides efficient deep copy of objects, it poses a problem of maintainability. You have to write clone() for each new class you create. Some people thinks deep cloning can be avoided by Serializable

Instead, it would be much easier to maintain and relatively faster to write a utility Class which uses the ByteArray streams to serialize, copy and then de-serialize the objects.
Class T{
// serialize
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(sourceObject);
//De-serialize
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(sourceObject);
result = (T) in.readObject();

}
Disadvantages of using Serialization to achieve deep cloning –
· Serialization is more expensive than using object.clone().
· Not all objects are serializable.
· Serialization is not simple to implement for deep cloned object

What is Java Memory Model (JMM):
A memory model describes the relationship between variables in a program (instance fields, static fields, and array elements) and the low-level details of storing them to and retrieving them from memory in a real computer system.

Comparable Comparator:

How to display Employee by sorting them using the employee id, name or age .

=
There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user.
Comparable & CompareTo


Comparable & Comparator Interface

Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.lang.Comparator interface.

ava.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1

java.lang.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o2



String and String Buffer
You can create String objects in the following ways.

1. String s1 = "hello";
String s2 = "hello";

2. String s3 = new String ("hello");
String s4 = new String ("hello");

Which of the above gives better performance?

Java Virtual Machine maintains an internal list of references for interned Strings (pool of unique Strings) to avoid duplicate String objects in heap memory. Whenever the JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it does not create a new String and it uses reference to the existing String Object. JVM does this type of checking internally for String literal but not for String object, which it creates through 'new' keyword. You can explicitly force JVM to do this type of checking for String objects which are created through 'new' keyword using String.intern() method. This forces JVM to check the internal list and use the existing String object if it is already present.

So the conclusion is, JVM maintains unique String objects for String literals internally. Programmers need not bother about String literals but they should bother about String objects that are created using 'new' keyword and they should use intern() method to avoid duplicate String objects in heap memory which in turn improves java performance. see the following section for more information.

The following figure shows the creation of String Objects without using the intern() method.


You can test the above difference programmatically using == operator and String.equals() method.
x==y Operator returns true if the references (x & y) point to the same object as it does not check the contents of these two String objects; where as String.equals() method returns true if the contents of the String objects are equal.

String s1 = "ram";String s2 = "ram" if(s1==s2) => Trues1.equals(s2) => True
String obj1 = new String("ram");String obj2 = new String("ram"); if(obj1==obj2) => falseobj1.equals(obj2) => true

How do you make sure that the String objects are not duplicated?

The next topic covers this interesting interning String mechanism.
Optimize by Interning String:
In situations where String objects are duplicated unnecessarily, String.intern() method avoids duplicating String objects. The following figure shows how the String.intern() method works. The String.intern() method checks the object existence and if the object exists already, it changes point of reference to the original object rather than create a new object.

The following figure shows the creation of String literal and String Object using intern



Concating String:
String object is resolved at compile time where as StringBuffer object is resolved at run time. Run time resolution takes place when the value of the string is not known in advance where as compile time resolution happens when the value of the string is known in advance.

In general, programmers think that StringBuffer.append() is better than + operator or String.concat() method. But this assumption is not true under certain conditions.


How many objects are created here
String str =”ramesh”;
str = str + ”*”

= When the ‘+’ operator is used with String object, implicitly StringBuffer is used.
How, let us see steps:-
· A StringBuffer is set up
· str is copied to it
· The "*" is appended to the buffer
· The result is converted to a string
· The str reference is made to point at that string.
· The old string that str previously referenced is then made available for garbage collection.
But time taken to perform these operation is involved is more. To reduce it explicitly use StringBuffer.

Relation between Equals() and hashcode()

Book firstBook = new Book("0201914670"); //Swing Tutorial, 2nd edition
Book secondBook = new Book("0201914670");

if (firstBook.equals(secondBook)) {
System.out.format("objects are equal ");
} else {
System.out.format("objects are not equal");
}
This program displays objects are equal even though firstBook and secondBook reference two distinct objects. They are considered equal because the objects compared contain the same value.

The Object class has two methods for making inferences about an object's identity: equals() and hashCode().

In general, if you override one of these methods, you must override both, as there are important relationships between them that must be maintained.
The hashCode() Method
The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal (i.e derived by mapping the memory address of the object to an integer value).By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

Obj1.equals(Obj2) || will be TRUE if the value contained in both objects are similar.

The default implementation of hashCode() provided by Object is derived by mapping the memory address of the object to an integer value.

How practically we override equals() method:
public boolean equals(Object obj) {
return (obj instanceof Integer && intValue() == ((Integer) obj).intValue());
}



Polymorphism:
Polymorphism is the name given to a language's ability to choose from multiple methods of the same name and execute the appropriate method. There are two kinds of polymorphism:
1. Static polymorphism: The decision about which method to execute is made at the time the code is compiled. In PL/SQL, static polymorphism is also known as overloading.
2. Dynamic polymorphism: The decision about which method to execute is made at the time the code is executed, at runtime. This is also known as dynamic method dispatch and is available for the first time in PL/SQL with support for object-type inheritance.
Polymorphism -- which literally means many shapes -- is the ability of objects to belong to different types. For example, lets say I have a Dog class that implements both an Animal and a Pet interface. The Dog class is polymorphic. It can be an Animal, a Dog, or a Pet.
Dynamic binding is how polymorphism is "implemented" or how it works.

Static Polymorphism;
Static polymorphism is also called as overloading

Program 1

class Figure {

public void Print(){ System.out.println("Prints Figure"); }
}

class Circle{
public void Print(){ System.out.println("Prints Circle"); }
}

class Rectangle{
public void Print(){System.out.println("Prints Rectangle"); }
}

Now if you define three reference;

Figure f;
Circle c;
Rectangle r;

each reference can only assigned with the respective objects

Figure f=new Figure();
Circle c=new Circle();
Rectangle r=new Rectangle();

f always holds a Figure Object
c always holds a Circle Object
r always holds a Rectangle Object

f.print() calls Figure Print method
c.print() calls Circle Print method
r.print() calls Rectangle Print method

(Static link) This is fixed and there cannot be any change to this

Dynamic Polymorphism

interface PrintableObject {
public void Print();
}


class Figure implements PrintableObject {
public void Print(){ System.out.println("Prints Figure");}
}


class Circle implements PrintableObject {

public void Print(){System.out.println("Prints Circle");}
}


class Rectangle implements PrintableObject {
public void Print(){System.out.println("Prints Rectangle");}
}

Now if you define a reference of the PrintableObject type

PrintableObject p;

now p can refer to any of the objects Figure or Circle or Rectangle

PrintableObject p;

p=new Figure();

or
p=new Circle();

or
p=new Rectangle();

An example of Dynamic Polymorphism

public static void main(String args[])
{
PrintableObject p;
char ch;

System.out.println("Enter 1 2 3");
ch=System.in.read();
if(ch=='1'){
p=new Figure();
}
else if(ch=='2'){
p=new Circle();
}
else if(ch=='3'){
p=new Rectangle();
}

p.print();
}

In the above example, which print methods implementation is called, whether its Figure or Circle or Rectangle is not known till it is executed because it depends on, what object is assigned to the reference P.

This is called as Dynamic Polymorphism.
The same example could be implemented using class rather than interfaces.

Static Dispatch & Dynamic Dispactch?

method overloading would be an example of static polymorphism ;
whereas overriding would be an example of dynamic polymorphism.

B'Coz, in case of overloading, at compile time the compiler knows which method to link to the call. However, it is determined at runtime for dynamic polymorphism that is why it is called late binding; it occurs when a method is defined for several classes in a family, but the actual code for the method is not attached, or bound, until execution time. This gives support for overriding...

Static binding occurs when a method is defined with the same name but with different headers and implementations. The actual code for the method is attached, or bound, at compile time. Static binding is used to support overloaded methods in Java.









JDBC
Interface: Connectoin
ResultSet
Statement

Class: DriverManager
DataSource

Steps to write JDBC code?
Class.forName(jdbc-driver);
Conection con = DriverManager.getConnection(user, pwd);
Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(….) || stmt.executUpdate(…)
What is the difference between executeUpdate and execute?
execute() can be used to execute any kind of an SQL statement (i.e. SELECT, UPDATE, INSERT, DELETE) while executeUpdate() can only be used with UPDATE, INSERT or DELETE.
What is the difference between Resultset and Rowset
=A RowSet is a disconnected, serializable version of a JDBC ResultSet.

ResultSet
The ResultSet interface provides methods for retrieving and manipulating the results of executed queries, and ResultSet objects can have different functionality and characteristics.
These characteristics are
result set type,
result set concurrency, and
cursor holdability.
Types:
· TYPE_FORWARD_ONLY — the result set is not scrollable i.e. the cursor moves only forward, from before the first row to after the last row.
· TYPE_SCROLL_INSENSITIVE — the result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position.
· TYPE_SCROLL_SENSITIVE — the result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position.
Before you can take advantage of these features, however, you need to create a scrollable ResultSet object. The following line of code illustrates one way to create a scrollable ResultSet object:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(".....");

The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
Resultset methods:
When a ResultSet object is first created, the cursor is positioned before the first row. To move the cursor, you can use the following methods:
· next() - moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned after the last row.
· previous() - moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row.
· first() - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now positioned on the first row and false if the ResultSet object does not contain any rows.
· last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now positioned on the last row and false if the ResultSet object does not contain any rows.
· beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If the ResultSet object does not contain any rows, this method has no effect.
· afterLast() - positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet object does not contain any rows, this method has no effect.
· relative(int rows) - moves the cursor relative to its current position.
· absolute(int n) - positions the cursor on the n-th row of the ResultSet object.

Types of JDBC Drivers
Driver is the key player in a JDBC application; it acts as a mediator between Java application and database. It implements JDBC API interfaces for a database, for example Oracle driver for oracle database, Sybase driver for Sybase database. It maps Java language to database specific language including SQL.

JDBC defines four types of drivers to work with. Depending on your requirement you can choose one among them.
Here is a brief description of each type of driver:
Type of driver Tier Driver mechanism Description
1 Two JDBC-ODBC This driver converts JDBC calls to ODBC calls through JDBC-ODBC Bridge driver which in turn converts to database calls. Client requires ODBC libraries.Use Type 1 driver if your database doesn't support a driver. This is rare situation because almost all major databases support drivers or you will get them from third party vendors.
2 Two Native API - Partly - Java driver This driver converts JDBC calls to database specific native calls. Client requires database specific libraries. . Use Type 2 driver for two tiered applications for communication between java client and the database that gives better performance when compared to Type1 driver
3 Three JDBC - Net -All Java driver This driver passes calls to proxy server through network protocol which in turn converts to database calls and passes through database specific protocol. Client doesn't require any driver.Use Type 3 driver to communicate between client and proxy server (weblogic, websphere etc) for three tiered applications that gives better performance when compared to Type 1 & 2 drivers.
4 Two Native protocol - All - Java driver This driver directly calls database. Client doesn't require any driver.Use Type 4 driver for applet to database communication.
Type 3 & 4 drivers are faster than other drivers because Type 3 gives facility for optimization techniques provided by application server such as connection pooling, caching, load balancing etc and

Obviously the choice of choosing a driver depends on availability of driver and requirement. Generally all the databases support their own drivers or from third party vendors. If you don't have driver for your database, JDBC-ODBC driver is the only choice because all most all the vendors support ODBC. If you have tiered requirement (two tier or three tier) for your application, then you can filter down your choices, for example if your application is three tiered, then you can go for Type three driver between client and proxy server shown below. If you want to connect to database from java applet, then you have to use Type four driver because it is only the driver which supports that feature. This figure shows the overall picture of drivers from tiered perspective.

Type 4 driver need not translate database calls to ODBC or native connectivity interface. Type 1 drivers are slow because they have to convert JDBC calls to ODBC through JDBC-ODBC Bridge driver initially and then ODBC Driver converts them into database specific calls. Type 2 drivers give average performance when compared to Type 3 & 4 drivers because the database calls have to be converted into database specific calls. Type 2 drivers give better performance than Type 1 drivers.


Why DataSource is used over DriverManger:
DataSource works with JNDI, which manages connection to a database.

If you use a DataSource, which retrieves connections and its information from a JNDI directory, you have the advantage that you do not need to hardcode driver information within your application. You just need to make a connection to the directory, which provides the needed driver information.

Major advantages of a data source is the possible usage of connection pooling and distributed transactions.


Hypersonic or HSQL, is a lightweight, 100% Java SQL Database Engine.


How to control Transaction ?
Or
How to use preparedstatement ?
By default in JDBC transaction starts and commits after each statement's execution on a connection. That is, by default the AutoCommit mode is true. So, to control transaction a Programmer need not write a commit() method explicitly after each statement.
Obviously, this default mechanism gives good facility for programmers if they want to execute a single statement. But it gives poor performance when multiple statements on a connection are to be executed because commit is issued after each statement by default, that in turn reduces performance by issuing unnecessary commits. The remedy is to flip it back to AutoCommit mode as false and issue commit() method after a set of statements execute, this is called as batch transaction. Use rollback() in catch block to rollback the transaction whenever an exception occurs in your program. The following code illustrates the batch transaction approach.
try{
conn.setAutoCommit(false);
PreparedStatement ps = con.preareStatement( "UPDATE employee SET Address=? WHERE name=?");
ps.setString(1,"Austin");
ps.setString(2,"RR");
ps.executeUpdate();
PreparedStatement ps1 = con.prepareStatement( "UPDATE account SET salary=? WHERE name=?");
ps1.setDouble(1, 5000.00);
ps1.setString(2,"RR");
ps1.executeUpdate();
con.commit();
conn.setAutoCommit(true);
}catch(SQLException e){ con.rollback();}
finally{
if(ps != null){ ps.close();}
if(ps1 != null){ps1.close();}
if(connection != null){connection.close();}
}


OR another example:

con.setAutoCommit(false); // turn off autocommit
PreparedStatement stmt = con.prepareStatement("INSERT INTO employees VALUES(?, ?)");

stmt.setInt(1, 2000);
stmt.setString(2, "Kelly Kaufmann");
stmt.addBatch();

stmt.setInt(1, 3000);
stmt.setString(2, "Bill Barnes");
stmt.addBatch();

// submit the batch for execution
int[] updateCounts = stmt.executeBatch();
ExecuteBatch returns the ineteger Array.

Difference between PreparedStatemend and CallableStatement
CallableStatement is derived from PreparedStatement.
PreparedStatements over stored procedures, especially during the development.. It's a lot easier (for me) to change the sql in java code,

How to call Stored Procedure ?
Or
What is CallableStatement ?

CallableStatment cstmt = con.prepareCall( { call getEmpByID(?) } )
csmt.setString(1,”k30”)

ResultSet rs = csmt.executeQuery();


How to write ‘Stored Procedure’ in RDMS?

“create PROCEDURE getEmpByID (id integer)
AS
SELECT * FROM TBL_EMPLOYEE WHERE EMP_ID=’id’
GO

Difference between Statement and PreparedStatement ?
Preparestatment is faster because:
1. parse the incoming SQL query
2. compile the query
3. plan/optimize the data acquisition path
4. execute the query

How to use MetaData ?
ResultSet rs = stmt.executeQuery(“seelcet * ……..”);

ResultSetMetaData rsmt = rs.getMetaData();

int col = rsmt.getColumnCount();

How to get connection pooling?
=The JDBC API provides a client and a server interface for connection pooling. The client interface is javax.sql.DataSource, which is what application code will typically use to acquire a pooled database connection. The server interface is javax.sql.ConnectionPoolDataSource, which is how most application servers will interface with the PostgreSQL JDBC driver.

In an application server environment, the application server configuration will typically refer to the PostgreSQL ConnectionPoolDataSource implementation, while the application component code will typically acquire a DataSource implementation provided by the application server (not by PostgreSQL).

In Web application:-
application server does not support the ConnectionPoolDataSource.

The pooling implementations do not actually close connections when the client calls the close method, but instead return the connections to a pool of available connections for other clients to use.

This avoids any overhead of repeatedly opening and closing connections, and allows a large number of clients to share a small number of database connections.
Application code to initialize a pooling DataSource and add it to JNDI might look like this:
Jdbc3PoolingDataSource source = new Jdbc3PoolingDataSource();
source.setDataSourceName("A Data Source");
source.setServerName("localhost");
source.setDatabaseName("test");
source.setUser("testuser");
source.setPassword("testpassword");
source.setMaxConnections(10);
new InitialContext().rebind("DataSource", source);
Then code to use a connection from the pool might look like this:

Connection con = null;
try {
//use JNDI to get DataSource Object
DataSource source = (DataSource)new InitialContext().lookup("DataSource");
con = source.getConnection();
// use connection
} catch (SQLException e) {
// log error
} catch (NamingException e) {
// DataSource wasn't found in JNDI
} finally {
if (con != null) {
try { con.close(); } catch (SQLException e) {}
}
}

= Say you have a swing application, how would you use connection pooling ?

public class DBConnect {
public class DBConnect {}
public static Connection getConnection() throws SQLException {

Jdbc3PoolingDataSource source = new Jdbc3PoolingDataSource();
source.setDataSourceName("A Data Source");
source.setServerName("localhost");
source.setDatabaseName("test");
source.setUser("testuser");
source.setPassword("testpassword");
//source.setMaxConnections(10);

Connection con = null;
try {
con = source.getConnection(); // use connection
} catch (SQLException e) {

} finally { // log error
if (con != null) {
try { con.close(); } catch (SQLException e) {}
}

return con;
}
Differences Between Abstract class and Interface
= Abstract
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). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
Interface
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class.
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is the same as an interface but with the restriction that it cannot make a class inherit from it. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature Interface Abstract class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Constants Only Static final constants.Fields are public, static, final by default.Methods are public and abstract by default. Both instance and static constants are possible.
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If the various implementations only share method signatures then it is better to use Interface. If the various implementations are of the same kind and use common behavior or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast
Adding functionality If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Note that only interfaces can "extend" other interfaces. Classes can't extend interfaces, they can only implement interfaces.


ACID Transactions
In the context of database transactions, ACID is an acronym for Atomic, Consistent, Isolation, and Durable. Transactions provide a simple model of success or failure. A transaction either commits (i.e. all its actions happen), or it aborts (i.e. all its actions are undone). This all-or-nothing quality makes for a simple programming model. The attributes of an ACID transaction are:
Atomicity
A transaction allows for the grouping of one or more changes to tables and rows in the database to form an atomic or indivisible operation. That is, either all of the changes occur or none of them do. If for any reason the transaction cannot be completed, everything this transaction changed can be restored to the state it was in prior to the start of the transaction via a rollback operation.
Consistency
Transactions always operate on a consistent view of the data and when they end always leave the data in a consistent state. Data may be said to be consistent as long as it conforms to a set of invariants, such as no two rows in the customer table have the same customer id and all orders have an associated customer row. While a transaction executes these invariants may be violated, but no other transaction will be allowed to see these inconsistencies, and all such inconsistencies will have been eliminated by the time the transaction ends.
Isolation
To a given transaction, it should appear as though it is running all by itself on the database. The effects of concurrently running transactions are invisible to this transaction, and the effects of this transaction are invisible to others until the transaction is committed.
Durability
Once a transaction is committed, its effects are guaranteed to persist even in the event of subsequent system failures. Until the transaction commits, not only are any changes made by that transaction not durable, but are guaranteed not to persist in the face of a system failure, as crash recovery will rollback their effects.



Convert ‘String’ into ‘int’
String waiting = “10”;
int time = new Integer(waiting).intValue();

Singleton Pattern
=Create singleton to Provide a global point of access to the object

public class SingletonObject
{
private SingletonObject() {}

private static SingletonObject obj;

public static synchronized SingletonObject getInstance () {
if (obj == null)
obj = new SingletonObject();
}
return obj


public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

If no object holds a reference to the Singleton object, then the Singleton class may disappear, later to be reloaded when the Singleton is again needed. In that case, a new Singleton object will be created. Any static or instance fields saved for the object will be lost and reinitialized.

You can also set your VM to have no class garbage collection (-Xnoclassgc on the JRE 1.3, or -noclassgc on the IBM JVM.

Practical use of Signleton Class?

=class Singleton
{
private Singleton(){}

private static Singleton ref;

public static synchronized Singleton getInstance()
{
if (ref == null)
ref = new Singleton();

return ref;
}
...
public void doSomething()
{
...
}
}
Here, the doSomething() method can be accessed only when we have the instance of this Singleton class.
i.e. Singleton.getSingletonObject().doSomethig();

Real situation where it is used are:-
1. To create logger class.
The Singleton pattern is used in the design of logger classes. This classes are usual implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.


2. By treating configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated (or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoid reloading the values each time the configuration parameters are used.
3. Accessing resources in a share mode:-
It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classes in the application, working in an multithreading environment, they needs to operate actions on the serial port. In this case a singleton with synchronized methods has to be used to manage all the operations on the serial port.
4. Factories implemented as singleton:
Let's assume that we design an application with a factory to generate new objects (Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstarct Factory or Factory Method and Singleton design patterns is a common practice.

Problems in Signleton: OR When a Signleton class is not a singleton ?

1. Lazy instantiation using Double Locking Mechanism:
The standard implementation shown in the code above is a thread safe implementation, but it's not the best thread-safe implementation beacuse synchronization is very expensive when we are talking about the performance. Double-Checked Locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment.
In this case case the Singleton instance is created when the getInstance() method is called for the first time. This is called lazy instantiation and it ensures that the Singleton instance is created only when it is needed.
The method getInstance() with double locking mechanism:-
2.
public static SingleTon getInstance()
{
if (instance == null)
{
synchronized (SingleTon.class)
{
if( instance == null )
instance = new SingleTon();

}
}
return instance;
}
Description of above code:
Thread 1: Gets the lock on SingleTon.class and creating an instance.
Thread 2: Has passed the outer if(instance == null) and waiting for the lock. Once the lock is released by the first thread it goes inside. If we do not re-check if(instance == null) we may create a new instance. The thread 1 has already created an instance.

3. Protected constructor: IF you make the constructor as protected not private, then subclass construtor may be of type public, which lead multiple instatnce creation of the singleton class.
4. Serialization:
If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more than once, there will be multiple instances of Singleton created.

5. Abstract Factory and Factory Methods implemented as singletons.
There are certain situations when a factory should be unique. Having 2 factories might have undesired effects when objects are created. To ensure that a factory is unique it should be implemented as a singleton. By doing so we also avoid to instantiate the class before using it.
6. Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
Can we use singleton class as base class ?
= No, reason see above point 2.
How to avoid the serializable issue on a Singleton class?
= In order to avoid this the readResolve method should be implemented. See Serializable () and readResolve Method () in javadocs.

public class Singleton implements Serializable {
...

// This method is called immediately after an object of this class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return getInstance();
}
}

this readResolve is the method of serializable which is to get the new instance of the serialized object. So in our singleton class we add this method so that singleton class can be breached.

Serialization
An ability to read or write a whole object to and from a raw BYTE STREAM.

It allows Java objects and primitives to be encoded into a BYTE STREAM suitable for
streaming to some type of network or
streaming to a file-system, or more generally,
streaming to a transmission medium (or storage facility).


How can I force garbage collection to take place
=You can't force it but you call System.gc(), which is a "hint" to the runtime engine that now might be a good time to run the GC. But garbage collection using this method is not guaranteed to be done immediately.

Unfortunately, System.gc() triggers a full collection, which includes tracing all live objects in the heap and sweeping and compacting the old generation. This can be a lot of work. In general, it is better to let the system decide when it needs to collect the heap, and whether or not to do a full collection.

Exception:
There are two types of exception Checked exception and Unchecked Exception (Runtime exception).

User can write customized exception for Checked exception only. For that user need to use throw new ….exception at the point where it may throw. But unchecked exceptions are unpredectible, it is not sure from where it may throw; so, user can not write customized exception for unchecked exception.

Unchecked Exceptions are:-
· NullPointerException
· IllegalArgumentException,
· IllegalStateException.
IllegalStateException - when session.invalidate() is called on an already invalidated session, this exception is thrown.

Q. User define Exception ?
=
public class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}


In another class:-
try {
………
throw new MyException (“..msg..”);
}
}catch (MyException ex) {
System.out.println(ex);
}
OR:-
USER DEFINE EXCEPTION:-

public class LAException extends Exception{

public LAException (String MSG){
super(msg);
}

/**
* Default constructor.
*/
public LAException () {
super();
}
}//End of Class


2.
public class UserCountryBlankException extends LAException {

public UserCountryBlankException(String MSG) {
super(MSG);
}



1. throw new UserCountryBlankException(“llfflkfljlfj”);




What is difference between ERROR and EXCEPTION?
= An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException.
Collections

What is Set?

1. Collection methods



The following list describes the core collection interfaces:
-Collection - the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List. Also see The Collection Interface section.
-Set - a collection that cannot contain duplicate elements.
Implementation classes are: HashSet and TreeSet.
HashSet: For efficiency objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. While most system classes override the default hashCode() implementation of the Object, when creating your own class to add to a HashSet remember to override hashCode().
TreeSet: The TreeSet implementations useful when you need to extract elements from a collection in a sorted manner. It is generally faster to add elements to the HasSet then convert the collection to a TreeSet for sorted traversal.
HashSet TreeSet
HashSet permits null elementsHashSet does not offer any ordering of elements.HashSet is more faster and the reason is obvious i.e no ordering of elements.HashSet does not print the element according to iterator order. iteration time is proportionl to size. Not nullTreeset stores in ordering of values.Slower than HashSet due to ordering of values.Permits.treeSet iteration time is proportional to log(n).


Note that these implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. I.e.
Set s = Collections.synchronizedSet(new HashSet(...));
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
-LinkedHashSet: It is as fast as HashSet and is implements using HashSet and LinkedList.
-List - an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). If you've used Vector, you're familiar with the general flavor of List. Also see The List Interface section.
-Queue - a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements' natural ordering. Whatever the ordering used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties. Also see The Queue Interface section.
Map –
The Map interface is a replacement for the Dictionary class, which is now considered obsolete.

There are seven non-abstract implementations of the Map interface that we will discuss.
Hashtable and Properties classes have been around since JDK 1.0.
Properties class is a special class used to access and maintain properties files that contain name value pairs.
TreeMap, HashMap and WeakHashMap were added in JDK 1.2.
LinkedHashMap and the IdentityHashMap added in J2SE 1.4.
The IdentityHashMap is a special Map that maintains key by reference equality (they point to the same object) rather than object equality (they contain the same value).



Each implementation contains features that make it appropriate for particular applications. Each of the classes has a unique feature that makes its use desirable in certain circumstances.

HashMap:
It is the basic Map implementation. It uses hash to store the key in the Map.
The hash allows fast lookup which means that the containKey( ) method will perform much better than the containsValue( ) method.
It allows one null key.
Duplicates are not permitted

TreeMap:
TreeMap stores data as Key, Value pair.
It cannot contain duplicate key.
TreeMap maintains keys in a sorted order. (Hence it is slow) – this is difference with that of HashMap

My Question:
What is Entry interface ?= Entry interface is static nested interface in Map. So it is written as Map.Entry.

WeakHashMap - A weak hash map has only weak references to the key. This means that it allows the KEY to be garbage collected if it is not used otherwise. If this happens, the entry will eventually disappear from the map, asynchronously. Other strange behaviors to be aware of: The size of this map may spontaneously shrink (even if you use a synchronized map and synchronize it). Both null values and the null key are supported. The null key is never deleted from the map (except explictly of course).
WeakHashMap is a Map with weak keys, that is, objects in a WeakHashMap will be garbage collected if the only reference to them is the WeakHashMap itself.
WeakhashMap is a hashtable-based Map implementation with weak keys
Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.

The last two core collection interfaces are merely sorted versions of Set and Map:

SortedSet - a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls. Also see The SortedSet Interface section.

SortedMap - a Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories. Also see The SortedMap Interface section.
Properties:
It is used to read any file (txt, ini) and get the name and value written inside that txt file. Eg.

BufferedInputStream bStream = new BufferedInputStream(new FileInputStream("c:/rishu.txt"));
Properties props = new Properties();
props.load(bStream);
props.remove("password");
props.list(System.out);
bStream.close();

Remember c:\rishu.txt contains like:
Name=ramesh
Password=kk
You=yes



Q: Can a ArrayList contain heterogenous objects?
A: Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.

Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList?
A: The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non-synchronized data structure will give better performance than the synchronized one.



What is the difference between vector and ArrayList ?

What are the differences between HashMap and Hashtable?
= Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.
- access to the Hashtable is synchronized on the table while access to the HashMap isn't.
- iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
- HashMap permits null values in it, while Hashtable doesn't.
For new code, I would tend to always use HashMap.
1) Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

2) Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
How to make an ArrayList unmodifiable ?
Collection c = new ArrayList();
c.add("hoge");
c = Collections.unmodifiableCollection(c);

How to make an ArrayList Synchronized ?
List list = Collections.synchronizedList(new ArrayList(...));

What is the difference between for-each and iterator to traverse a collection ?
= for- each example is:-
for (Object o : collection)
System.out.println(o);
Iterator:-
An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively
What is the difference between Iterator and Enumerator?
= Differences between Iterator & Enumeration:
Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration, b’ coz it always denies other threads to modify the collection object which is being iterated by it. Whenever a second thread tries for that Iterator will throw a ConcurrentModificationException. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly.
See what happens to this code segment,
Vector aVector = new Vector();
aVector.add("I");
aVector.add("am");
aVector.add("really");
aVector.add("good");

Iterator anItr = aVector.iterator();
// Traversal using Iterator
while(anItr.hasNext())
{
if ()
// This statement will throw ConcurrentModificationException.
// Means, Iterator won’t allow object modification while it is
// getting traversed. Even in the same thread.
aVector.remove(index);

/* the correct way is*/
// Note: the Iterator should
// point to any of its elements. The remove() removes the
// element which the Iterator corrently pointing to.
// Otherwise it will throw IllegalStateException
// Before using anItr.remove(),
anItr.remove();

System.out.println(anItr.next());
}
// Traversal using Enumeration
Enumeration anEnum = aVector.elements();
while(anEnum.hasMoreElements())
{
if ()
aVector.remove(index);

System.out.println(anEnum.nextElement());
}
#ramesh: does it shows that Enumerator does not throw any exceptiin ? Try do practical on it.
But Iterator provides a safer way to remove elements from the underlying collection during the iteration with well-defined semantics. See the implementation of Iterator. But here the remove() is supported by only those implementations of Collection that supports element removal.
public interface Iterator
{
boolean hasNext();
Object next();
void remove(); // Optional
}
Note that Iterator.remove() is the only safe way to modify a collection during iteration. In Enumeration, there is “no safe way” to remove elements from a collection while traversing.
My questions:-
Why we write List lst = new ArrayList();
Why not we write ArrayList lst = new ArrayList();
=Because: ArrayList is an concrete class and List is an interface. ArrayList implements List; and LinkedList also implements List interface.
So creating object by:
List lst = new ArrayList(): gives flexibility; that it can be changed even into LinkedList if required.

Also,
If there is an interface and we have a class that implements that interface. Then, by creating the object, like:
Interface int = new AnyClassThatImplementsThisInterface();
int.callOnlyThoseMethodsWhcihAreInInterface();// don’t call those methods which are not declared in interface but are local to implementing class.





1. What is the difference between a LinkedList and an ArrayList? Why would I use a LinkedList instead of an ArrayList?

=
a) A LinkedList is similar to an ArrayList in that it is ordered by index position, but it differs in that the elements are double-linked to one another. This linkage gives you new methods for adding and removing from the beginning or end.

b) 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.

c.) ArrayList has random access and LinkedList has sequential access.

=An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the number of elements in the collection increases, the internal array grows to fit them. If there are lots of growth periods, performance degrades as the old array needs to be copied into the new array. However, random access is very quick as it uses an array index to access.
With a LinkedList, the List implementation is backed by a doubly linked list data structure, allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the access must start at an end to get to the specific position.
ArrayList LinkedList
ArrayList has random accessLinkedLists slow indexed access times, but have fast insert times,i.e. you can quickly insert or delete an element of a linked list. but it takes more time to find the any element. LinkedList has sequential accessLinkedLists fast indexed access times, but have slow insert times,













What is the difference between Colletion and Array
= Colletion is growable but Array is not.
Colletion can store only Object and not primitives. While Array only premitive.

Can Array Sort the conents of Array ?
=Arrays do not directly support sorting, but this can be overcome by using the static methods of the Collections. Here is an example.

String s[] = new String[4];
s[0]="z";
s[1]="b";
s[2]="c";
s[3]="a";
Arrays.sort(s);
for(int i=0;i< s.length;i++)
System.out.println(s[i]);
}


How to create an object for a class whose name is not known; and it would be sent at run time dynamically ?
=
Remember :-> Object o = new (className); // WRONG!

We must use:
Class cls = Class.forName(className);
object = cls.newInstance();

EXAMPLE:-
class SampleNoArg {

public static void main(String[] args) {
Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
System.out.println(r.toString());
}

static Object createObject(String className) {
Object object = null;
try {
Class cls = Class.forName(className);
object = cls.newInstance();
} catch (InstantiationException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
}
return object;
}
}

The newInstance method throws a NoSuchMethodException if the class does not have a no-argument constructor

How to call Dos commands from Java code:-
= Runtime.getRuntime().exec("cmd /c dir c:\\/s > c:\\test.txt")

MarkUp Inteface:
Ex: SingleThreadModel, Serializable, Cloneable.
The purpose of marker interface is the JVM mark the interface which implementation take care me User could not implement them, JVM itself implement, that is why we are using marker interface.

The simplest way to make your class cloneable is to add implements Cloneable to your class's declaration. then your objects can invoke the clone() method.



Serializable and Externalizable:
Basically SERIALIZABLE uses default implementation for reading and writing the object you want to persist.
You just have to implement SERIALIZABLE interface for your class and rest will be taken care.
While implementing Serialzibale interface it generates a uniquie number . The significance of this unique number is to ……………..
To serialize an object means to write its complete internal state (including its private state) to a byte stream in such a way that a copy of the object can be reconstituted at some later time. When an object is serialized, the entire object graph of all the objects it refers to are serialized along with it.
Serialization also provides a convenient way to produce a "deep clone" of an object graph.
An object is serialized by the writeObject( ) method of the ObjectOutputStream class and deserialized by the readObject( ) method of the ObjectInputStream class.

For EXTERNALIZABLE you will have to implement the writeExternal() ande readExternal() methods.
As in you can specify your own way of storing the information and retrieving the information of the object.

Unless you have very specific requirements one wouldn't use EXTERNALIZABLE.

Ramesh:Serialization means creating any Text file and writing the objects into that file.
Deserializgin means oppenting this file and reading the object and casting it to actual class (from which object was created). For example see the following page:

Serialization best page : http://www.javabeginner.com/object-serialization.htm


Volatile and Transient:
transient and volatile both are used to define non-serializable members of any class.means if we want to convert an object into byte stream and write into file we serialize the class but if any variable or method which we dont want to serialize,we can specify them by above.
Volatile:
it will be shared and seen by all threads of an object. It says that several threads may be interested in the value, so threads must not keep their own local copies with different values. When the value is changed in one thread, all other threads must see it straight away.
Transient:
The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. (Variables that are part of the persistent state of an object must be saved when the object is archived.)

VOLATILE is used with variable andTRANSIENT is used with methods

A specific class variable, serialVersionUID (representing the Stream Unique Identifier, or SUID), may be used to specify the earliest version of the class that can be deserialized. The SUID is declared as follows:
static final long serialVersionUID = 2L;
This particular declaration and assignment specifies that version 2 is as far back as this class can go. It is not compatible with an object written by version 1 of the class, and it cannot write a version 1 object. If it encounters a version 1 object in a stream (such as when restoring from a file), an InvalidClassException will be thrown.
The SUID is a measure of backward compatibility. The same SUID can be used for multiple representations of a class, as long as newer versions can still read the older versions.
If you do not explicitly assign a SUID, a default value will be assigned when the object gets serialized. This default SUID is a hash, or unique numeric value, which is computed using the class name, interfaces, methods, and fields.
How u reverse a String ?
=Use StringBuffer.reverse()
How to make a class immutable ?
= To make a class immutable
1. Make the class as final
2. Instance variables are made private and final
3. It should contain only getter method but not the setter method.
4. It may have constructor.
The possible use of immutable classes would be a class containing a price list represented for a set of products.

Which classes in Java are immutable:
All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

What are the advantages of Immutablity
The advantages are:
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
4) The best use of the immutable objects is as the keys of a map.










Miscellaneous
java DAO
For each table in datanbase we make one DAO. J2EE developers use the Data Access Object (DAO) design pattern to separate low-level data access logic from high-level business logic. Implementing the DAO pattern involves more than just writing data access code. In this article, Java developer Sean C. Sullivan discusses three often overlooked aspects of DAO programming: transaction demarcation, exception handling, and logging.

What is the content of .ear
=.jar
.war
Q . Interface variables are implicitly final ; so, interface variables can not be reassigned.
= You can't reassign a final member, can you?
A final interface or class member can only be assigned a value once, in the class or interface declaration. But in Java it can be easy to forget the difference between a reference value and the object being referenced. Consider the interface names below:
interface names {
String num_names[] = new String[] { "zero", "one", "two", "three",
"four", "five", "six", "seven",
"eight", "nine" };
public void pr();
}
In this interface a String array object is assigned to the interface member num_names. Since this member is declared in an interface it is final automatically, even though there is no explicit final declaration.
In the example below, class more_names implements the names interface.
class ABC implements names {

public void set_two() {
num_names[2] = "bogus";
}

public void pr() {
for (int i = 0; i < num_names.length; i++) {
System.out.println("num_names[" + i + "] = " + num_names[i] );
}
}

}

class Test {
public static void main( String args[] ) {
ABC n = new ABC();

n.set_two();
n.pr();
}
}
This Java code compile without error. If it is executed it will print
num_names[0] = zero
num_names[1] = one
num_names[2] = bogus
num_names[3] = three
num_names[4] = four
num_names[5] = five
num_names[6] = six
num_names[7] = seven
num_names[8] = eight
num_names[9] = nine
Note that element two of the array has been changed from "two" to "bogus". If num_names is final how is this possible? Note that the reference variable is final, not the object assigned to it. So the object can be changed, but the reference variable cannot. The method below, reset, would be flagged with an error by the Java compiler, since the final variable is assigned a new object.

public void reset() {
num_names = new String[] { "ten", "eleven", "twelve" }; // illegal
}


What is Anonymous class ?
="An anonymous class is essentially a local class without a name."

Methods present inside Object class:-
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait.

Wraper Class ?

= Wrapper classes are used to remove coupling between classes and create
one hand doesn't know what the other hand does effect.

Primitive Type Wrappers
Primitive Wrapper
void java.lang.Void
boolean java.lang.Boolean
char java.lang.Character
byte java.lang.Byte
short java.lang.Short
int java.lang.Integer
long java.lang.Long
float java.lang.Float
double java.lang.Double

Wrapper classes throw a NumberFormatException when there is an error in parsing from a string.

These classes are designed to "wrap" the primitive types into a class.

Each of the wrapper classes have a method named parseclassname to convert a String into that type. For example the Interger.parseInt method converts a String into an int.
Simillarly Double.parseDouble method converts a String into a double.

In Java 5.0 version, additional wrapper classes were introduced in the java.util.concurrent.atomic package. They provide atomic operations for assignment, addition and increment. These classes act like variables and cannot be used as a substitute for the regular wrapper classes. Few of these new wrapper classes like AtomicInteger and AtomicLong are the subclasses of the Number Classes.
Primitive Wrapper
boolean AtomicBoolean
int AtomicInteger
long AtomicLong
V AtomicReference
Features Of the Wrapper Classes
Some of the sound features maintained by the Wrapper Classes are as under :
· All the methods of the wrapper classes are static.
· The Wrapper class does not contain constructors.
· Once a value is assigned to a wrapper class instance it can not be changed, anymore

What is the difference between:
Integer.valueOf("7").intValue(); and Integer.parseInt("7");

=
Integer.valueOf("7").intValue()
It means
Integer i = Integer.valueOf("7");
int temp_int = i.intValue();

The only difference between the two lines is that the first example goes out and instantiates an extra Integer instance. You would only want to actually instantiate the Integer instance if you needed to use it later; otherwise, you are needlessly instantiating an object. Object instantiation can be expensive, especially within loops. With that in mind, be sure to use valueOf() when you really need an Integer instance.

Integer.parseInt("7");
Here, Integer simply parses the "7" string and returns the int value.



Difference between Instance and Object:
An object and an instance are one in the same. The difference is between classes and objects.

Anything that is static in a class becomes propery of the class itself. These are things like static variables and static methods.

To use things that belong to the class itself, no instance of that class is required. No object is required.

Objects, on the other hand, are instances of a class. Any non-static method defined in a class requires an instance for it to be used.

Can we synchronise a constructor?
=No (It will give compile time error.)
Constructors are not synchronized, cannot be declared as synchronized, and don't need to be synchronized, because they can't be called on pre-existing objects, so there is no way for two threads to call the same constructor on the same object at the same time.

------Language Fundamentals-------
Can we write sop inside class and out side a method ?
Or
How to write sop Out side a method and inside a class ?
=
class a{
static{
System.out.println("Hello");
}
}

When to use static block ?
=You can use a static block when you want to do some processing without creating an instance of a class.

because executable code needs to be in the context of a method (constructors and initializers are really just methods with slightly different syntax).

Static methods and variables are thread safe, it means that when a thread call an static method other threads should wait until first thread finich the job and notify them.
you are right An static method execute in a syncorinezed block to stop multiple thread to access it at same time.



Q I have a interface, I want to use only few methods of this interface but not all the methods, how it can be achieved ?
= make abstract class, implement the interface in that abstract class and declare abstract to those method which are to be mandatory and leave rest as simple methods.

Q. Why can’t we override Static methods ? (means base class has static method, can we make it as instance method in child class ) ?
=
Q. If a methos is instance method. Can I make it static method in sub class ?
= No. because static method can not hide the instance method .
What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
Final
You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object

Can we serialize a static variable in a class ?
=No
Because, when we serialize an object, then in another machine (VM) it gets deserialized, so again there it is initialized with different values.
But static variables are class levels variables irrespective of instances

Q. Can I use static variable inside main method ?
= You can't declare them to be static in the main method. Either make them non-static or declare them outside the main method.
But we use static method to reference (do any operation on those variables) static variable inside the class.

What is an object in Java?
A: In Java the Object class is the ultimate super class of every other object type. All objects are extended from the Object class, either directly or by inheritance through any number of parent classes. If a class does not explicitly extend any named class, it implicitly extends the Object class. An object with a small o is the word used to describe an instance of a Java class.
toString():
toString() method is used when we need a string representation of an object.
Instance & Object:
instance means just creating a reference(copy) .
object :means when memory location is associated with the object( is a runtime entity of the class) by using the new operator.


# Neither Interface or Abstract classes can be instantiated.

Can we declare an interface as abstract ?
= Yes you can declare. But by default all interfaces are abstract.


What is System.out.println() ?
= System has a static member attribute called "out", which is of type PrintStream.
This PrintStream provides a method called "println()", which is called by System.out.println().
The class is like:-
public class System{
public static PrintStream out = new PrintStream();
}


Why wait(),notify() and notifyall() in Object class in java
=Because it belongs to the behaviour of an object and not of a thread. A thread may access an object, or wait until another object is done.

Can we instantiate an Interface?
= No,

How can I prevent inheritance without marking the class ‘final’ ?
= YES, declare all the variables of the class as ‘final’.

Is there any interface in java which do not have any method and any vairbles in that ?
= yes, it is interface RandomAccess.

Can a abstract class can have constructor?
= YES, it is not used for creating the instance; rather it can be used by subclass.










Remember
· Two public classes in the same file are not allowed.
· Check modifier of the top level class, it shouldn't be "private" or "protected ".
· The main method calling a non-static method directly, or accessing non-static variables, using this reference is a compile time error.
· Methods can have same name as the constructor(s), check for return type. (constructor do not have return type)
· Case statements with values out of permissible range, only integer compatible value are permitted.
· Private constructors, watch out for them especially if there is a subclass, if default no-argument constructor is private, a subclass will not be compiled, if its constructor has to use this default constructor.
· If the compiler gives you the default no-args constructor for the class, its accessibility is same as the class.
· An assignment statement for boolean data type, which looks like a comparison if (a=true), it is valid but will be always evaluated to true.
· main() can be declared final, or native.
· Class declarations can come in any order (superclass first, subclass next etc).
· Forward references to variables gives compiler error.
· -0.0 == 0.0 is *true*.
· Multi dimensional arrays can be sparce ie., if you imagine the array as a matrix, every row need not have the same number of columns.
· Arrays, whether local or class-level, are always initialized.
· Strings are initialized to null, not empty String. And an empty String ("") is *NOT* same as a null string.
· A declaration cannot be labeled.
· continue must be in a loop (for, do , while). It cannot appear in case constructs.
· break can be used to break out of any labeled block.
· If Base class’s method throws any Exception, then child class’s overriding method must throw the child exception of base-method’s-exception.
· Child class method can increase the visibility of base class method or can keep same. But can not be reduced. (eg base class method is private then it can be public in child class. But reverse is not possible.)
·
· A default constructor cannot handle exception type Exception thrown by implicit super constructor. Must define an explicit constructor.
· A Userdefined-constructor can throw any exception.
· Constructor must declare all the checked exceptions declared in the base constructor. They may add other exceptions. This behaviour is exactly opposite from that of methods. The overriding method cannot throw any exception other than overridden method. It may throw subclass of those exception.
· Initializer blocks are executed in the following order
1. Static initializers executed first, in the order they are declared. Takes place when the class is loaded, instance creation is not required.
2. Instance initializers are executed next, Instance initializers get executed ONLY IF the objects are constructed.
3. The constructor is executed at the last while creating an object.
· An instance final variable may be initialized only once, latest in the constructors.
· A static final variable may be only initialized once, latest in a static initializer, but not in the constructor because it can be referenced w/o creating an instance of the class.
· All comparisons involving NaN and a non-NaN would always result false, moreover comparisons involving two NaN values will also result in false, except for !=.
i.e. Float.NaN == Float.NaN results in false.
Float.NaN != Float.NaN results in true.
· Default type of a numeric literal with a decimal point is double.
· We can declare array of ZERO elements, it is perfectly valid and is commonly done by main() method if there are no command line arguments.
· you can *NOT* use more than '4' digits in case of character constant.
· Char constant '\101' is valid as it is representing the value in "octal", which is equivalent to 65.
· Values for char constant '\u000A' and '\u000D' is not valid as they represent line breaks, in fact these values can not appear anywhere in the Java source code.
· Interface methods can not be native, static, synchronized, final, private, or protected.
· Interface fields can't be private or protected. They are by default public static final. The final variable must be initialized.
· An interface can not be declared as ‘final’, it will cause compile time error.
· transient variables can't be members of interfaces.
· volatile variables can't be final or members of interfaces.
· CONSTANT values up to an int can be assigned (without cast) to variables of lesser size (eg. short to byte) if the value is representable by the variable.(ie. fits into the size of the variable).
· native method declarations can not have bodies, as they are implemented outside JVM.
· abstract method declarations can not have bodies, because its implementation is differed to the subclass.

Operators
· integer (and long ) operations / and % can throw ArithmeticException while / and % will never, even in case of division by zero.
· The == gives compiler error if the operands are cast-incompatible.
· instanceOf is *NOT* same as instanceof, later is Java operator, former is *NOT*.
· instanceof operator always return false for null value.
· Class H and class G have no relation (i.e if two class has no relation) with each other so both instanceof and == operator will give you compile time error.
· RHS of an instanceof operator must be a Class, Interface or an Array.
· The genral rule is that ~i = -i-1 (eg.: ~7 = -7 - 1 = -8)
· && and || oprators are "short-circuit" operators, i.e. they NEVER evaluate RHS operand if LHS operand can determine the result of the operation.
· operands of mathematical operators are ALWAYS promoted to ATLEAST int. (ie. for byte * byte both bytes will be first promoted to int.) and the return value will be ATLEAST int.
· int i = 5 + 'c'; is perfectly valid, and c will get converted to its numeric value.
· char is the only integral which is unsigned, all others are signed.
· Compound assignment oprators ( +=, *= etc) behave in this way -
operand1 += operand2;
Gives => operand1 = (TYPE_OF_OPERAND1)(operand1 + operand2);
except that operand1 is evaluated only once.
· Example
· int x = 4;
· x += 3.78; // x becomes 7, but no compiler error
·

Flow Control And Exceptions
· Check for uninitialized variable references with no path of proper initialization.
· You have finally w/o catch block, but try must be followed by either catch or finally.
· if there is a System.exit() in try-catch-finally blocks, finally won't complete.
· Order of try-catch-finally blocks matters.
· The following code will give you compiler error " Unreachable statement "
· while(false) //compiler error
· {
· System.out.println("Hello");
}
Casting and Conversion
· Conversion sequence for primitives is as follows -
· byte --> short --> int --> long --> float --> double
· /
· char ___/
· boolean can not be converyted to any other primitiv, and any other primitive can not be converted to boolean.
· objectOfSuperclass = objectOfSubclass is always valid w/o explicit casting.
· Primitive array types can never be assigned to each other, even though the primitives themselves can be assigned. ie. ArrayofLongPrimitives = ArrayofIntegerPrimitives gives compiler error even though longVar = intVar is perfectly valid.
· null value can be casted but do remember it is of no use to cast null value.
Overriding and Overloading
· A class without abstract methods can still be declared abstract.
· If a class has an abstract method, it must be declared abstract.
· An abstract class cannot be instantiated.
· If null is passed as a method parameter to an overloaded method, then most specific method as per the parameter hierarchy will be called. BUT if two methods which are not form the same hierarchy are present than compiler will raise an ambiguity error.
· Overriding method must have same signature and return type as the overriden method.
· Overriding method can be more accessible (public) than the overriden method, but it can not be more restrictive, otherwise it will result in a compile time error. The accessibilty (from most restrictive to least restrictive) is as follows -
private => package => protected => public
· The overriding method *MUST* throw exception which is either same as the exception that the overriden method is throwing, or should be a subclass of it. It may also choose not to throw an exception.
· When a subclass object is created, all the superclass constructors are invoked in the order starting from the top of the hierarchy.
· A subclass cannot override methods that are declared final in the superclass (by definition, final methods cannot be overridden). Means a final method in base classs can not be without final method in sub class; but vice versa is possible.






Threads
· Threads can not be initiated with classes that do not either implement Runnable or extend Thread.
· Signature of run() method is - public void run(), any other variation is not allowed and will result in a compile time error if a method by this signature is not present in a class extending Thread or implementing Runnable. This method does not throw any exception.
· The default Thread priority is the priority of the thread which started it, it can be changed using method setPriority(int priority).
· The methods sleep() and yield() are static methods of the thead class, they ALWAYS work on the thread which is currently executing. sleep() method throws IterruptedException, whereas yield() does not throw any.
· The methods wait(), notify(), and notifyAll() are the methods of Oject class, they are inherited in the Thread class and all throw InterruptedException.
· The methods wait(), notify(), and notifyAll() *MUST* be called in a synchronized block, otherwise the call will result in IllegalMonitorStateException at Runtime (It is-a RuntimeException).
· The instance method setDaemon(bolean on) of Thread class can be used to set a thread as daemon thread, or user thread. This method *MUST* be called before the thread is started, otherwise IllegalThreadStateException is thrown at Runtime.
· The instance method join() can be called on any thread, so that the calling thread waits till this particular thread (on which join() has been called) dies, i.e completes execution of its run() method. The method throws IterruptedException, and its overloaded version take "timeout" paramete in milli-seconds and other in mili-seconds and nano-seconds.
Inner Classes
· Inner classes can also be private or protected.
· Inner classes can access all the instance variables of the enclosing class.
· Local inner classes (…..) *CAN NOT* access non-final vars of the enclosing method, it is a compiler error.
· You cannot declare a static variable inside a non-static inner class but static final variable is allowed as the compiler will treat it as a constant.
· Inner classes do not have same name as the enclosing classes.
What is a static inner class? Can you provide an example from the Java API?
A static inner class is a class tightly associated with its enclosing class but not tied to any specific instance. Static inner classes can be instantiated independent of the enclosing class like any top level class. A common example is the Map.Entry class, which provides the standard contract for accessing maps in the Collections api.

Advantage:
If a class A is written requires another class B for its own use, there are two ways to do this. One way is to write a separate class B or to write an inner class B inside class A. Advantage of writing the inner class B in the class A is you can avoid having a separate class. Inner classes are best used in the event handling mechanism and to implement the helper classes. The advantage of using inner class for event handling mechanism is that the use of if/else to select the component to be handled can be avoided. If inner classes are used each component gets its own event handler and each event handler implicitly knows the component it is working for.

java.util Package
· Following classes are the implementations of various Collection framework interfaces.
1. interface Set extends Collection - HashSet
2. interface SortedSet extends Set - TreeSet
3. interface List extends Collection - ArrayList, Vector, LinkedList
4. interface Map - HashMap, HashTable
5. interface SortedMap extends Map - TreeMap
· Set => Unique values, no duplicates, List => Order, Map => key-value pair.
· Map *does not* extend Collection.
· Dictionary is a class, not an interface.
· Collection is an Interface where as Collections is a helper class.
· BitSet has nothing to do with sets or collections.
· Only Vector and Hashtable class of java.util package are thread safe.
· Important bulk operations of Collection with their mathematical equivalent statement. (Note that methods are called on "a" and a is being modified as a result)
· (1) a.containsAll(b) --> b is a subset of a
· (2) a.addAll(b) --> a is a union b
· (3) a.removeAll(b) --> a is a difference b
· (4) a.retainAll(b) --> a is a intersect b
(5) a.clear() --> a is an empty set
· The operations performed by methods addAll(b), removeAll(b), retainAll(b) and clear() *do modify* the original collecton.
java.lang Package
· Wrapper classes are all immuatable, the wrapper classes for primitives int and char are Integer, and Character respectively.
· void is *NOT* a primitive, so Wrapper class Void *IS NOT* a Primitive Wrapper class.
· Math class is not an immutable classes. It's final, non-instantiable (private constructor) class.
· Math.abs() will return the argument itself, if it is equivalent to Integer.MIN_VALUE or Long.MIN_VALUE. e.g. Math.abs(-2147483648) return -2147483648. if literal is less than MIN_VALUE then compile time error will occur "Decimal must be in the range of so and so".
· In java.lang.Math class -
Math.ceil(-0.5) = -0.0
Math.round(-5.5) = -5
Math.round(5.5) = 6
Math.round(5.49) = 5
Math.round(-5.49) = -5
· equals() method of standard Wrapper classes, String and StringBuffer return false if the object classes are different. It does not flag a compiler error. However, you can not be certain about the other classes if they override this method.
· You can not pass primitives to equals() method.
· You can use negative argument in indexOf() and lastIndexOf() method of String class. In such case it will start searching from zero.
· There is *no* trim() method in StringBuffer.
· There is *no* reverse() or append method in String.
· Strings are IMMUTABLE, can not be changed once created. They are immutable, period.
· replace() method of String class returns the same object if both the parameters are same, ie. if there is no change.
java.io Package
· File class has NO methods to deal with the contents of the file.
· File class can delete (delete()) and create new files (createNewFile()).
· File class method renameTo() takes File object as param.
· To test if file is a directory, method isDirectory() of File class can be used.
· getParent() of File class returns name of the parent directory as a String, whereas getParentFile() returns File object.
· RandomAccessFile descends from Object and implements DataInput and DataOutput, for reading and writing all java primitives. Additionally, also has methods to read/write UTF - readUTF() and writeUTF().
· InputStream and OutputStream are abstract classes, while DataInput and DataOutput are interfaces.
· Only InputStreamReader and OutputSreamWriter are for customizing the "Encoding", their constructors take encoding as a parameter.
The default encoding used by these classes is defined by the system property - file.encoding
· Only InputStreamReader and OutputSreamWriter are the reader/writer classes which take InputStream and OutputStream in their parameters respectively. Also PrintWriter class can take an OutputStream as a parameter in its constructor.
· The Writer class has no write() method with a parameter of type char, instead has a method that takes an int, only lower 16 bits of this int are written as a character.
· Abstract Reader class's subclass must implement are write(char[], int, int) and close() methods. Most other methods are defined, or are overridden by subclasses.
· Abstract Writer class's subclass must implement are write(char[], int, int), flush(), and close(). Most other methods are defined, or are overridden by subclasses.
· Abstract Writer class has 2 additional write() methods besides the write trio, which takes String as a parameter. They are -
1. void write(String str) throws IOException
2. void write(String str, int offset, int len) throws IOException
· Only FileOutputStream and FileWriter can append to a file. They both take boolean parameter "append" as second parameter in their constructors.
· LineNumberReader extends BufferedReader, there is *NO* corresponding LineNumberWriter class.
· System.out and System.err are PrintStream.
· PrintWriter extends Writer and has all print() and println() methods analogus to the PrintStream.
· PrintStream and PrintWriter constructors also have boolean as their second parameter, but the second parameter here indicates whether it is "autoFlush". By default auto flush is off.

No Class Definition Found error:
this mostly occurs when the classpath is not set properly in relation to whereever you put your compiled classes.
Memory Leaks in JAVA
Figure 1. Unused but still referenced

The figure illustrates two classes that have different lifetimes during the execution of a Java application. Class A is instantiated first and exists for a long time or for the entire life of the program. At some point, class B is created, and class A adds a reference to this newly created class. Now let's suppose class B is some user interface widget that is displayed and eventually dismissed by the user. Even though class B is no longer needed, if the reference that class A has to class B is not cleared, class B will continue to exist and to take up memory space even after the next garbage collection cycle is executed.
When garbage collection run? = Typically, the garbage collector won't be automatically run until a program needs more memory than is currently available.

So, to identify where the memory leakage takes palce, we need to use any one of thes tools:
JProbe Suite (J Quest Software's)
Optimizeit Enterprise Suite (Borland's)
Win32 Java Heap Inspector (Paul Moeller's)





Will this code work ?

class Math {

int x, y;
Math (int x, int y)
{
this.x = x;
this.y = y;
}
public static void main(String args[])
{
Math math = new Math();
}

}
= No, It will give compile time error, because the constructor we have defined here is explicit., but trying to instantiate using default constructor. Hence it will not work because the default constructor is not present here.

What is the finalize method ?
= The Object class provides a callback method, finalize, that allows you to clean up an object before it is garbage collected. The finalize method may be called automatically by the system, and this is where you put any necessary cleanup code.
OR.
It is called by Garbage collector when it determines no more reference to the object exists (i.e no more the object is being used).
Can I write finalize() in my program?
Yes, example:-

protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize(); // This is mandatory to write
}
}
finalize() is never run more than once on any object

TRY/ FINALY

when will we use exception handling without catch block.

try
{
}
finally
{

}

=There could be a situation where you least expect an exception to be thrown, (just for eg. when you are reading from a file, which you are VERY sure has been created by any other block) when the control reaches this block .. and then in the try block (which you can't avoid), you have to do some IO operations and depending on the data modified or other condition, execute some part of code inside finally and also release some resources

Java different version :
Version technology
1.1 RMIJDBCInner classJNIJavaBeanInternationalizationJar filesSeriliazation





Thread:
Race condition:
In a multithreaded environment when methods of an object are accessed by more than one thread simultaneoudly, ti could result in an unpredictable behavior. This unpredectiable behavior is called race condition



Miscellaneous:-

BigIP:-
Big-IP is providing port translation for the application. That is it has entry for learningacademy.com which finaly routs the request to the required server (IHS).

3DNS:-
We typically use 3DNS only when global failover is required. Since the learningacademy servers are only in one location, it appears that only Big-IP is needed. Big-IP load balances local traffic.

ClassLoader:
All Java virtual machines include one class loader that is embedded in the virtual machine. This embedded loader is called the primordial (bootstrap) class loader. It is somewhat special because the virtual machine assumes that it has access to a repository of trusted classes which can be run by the VM without verification.

Another is A non-primordial class loader (or class loader objects).

A non-primordial class loader has there are 3 class loaders AppletClassLoader, RemoteClassLoader and SecurityClassloader
The differences between SAX and DOM
There are a number of key distinctions between SAX and DOM, including:
Dom Sax
DOM is preferred for complicated jobs, such as when the XML schema is inherently intricate or when you need random access to the data in the document.DOM builds a type description for every node in the XML document it loads into memory. Collectively, these descriptions result in an easily traversable, though potentially huge, tree structure. If the XML is verbose, DOM represents runaway inflation. For example, a 300-KB XML document can result in a 3,000,000-KB DOM tree structure in RAM or virtual memory. So which do you choose? If you're doing something complicated such as advanced XSLT transformations or XPath filtering, choose DOM. You'd also pick DOM if you're actually creating or modifying the XML documents. SAX moves in a linear fashion from the start of the document down through each node to locate a particular node or otherwise provide information about the document.By contrast, a SAX document is not deconstructed at all, nor is it cached in memory (though, of course, parts of it reside briefly in memory buffers as the XML stream is read through). SAX is a “lighter” technology—imposing little burden on your system. SAX is the equivalent of watching a marathon go by; DOM is like inviting all the racers home for dinner.On the other hand, choose SAX for searching or reading XML documents. SAX can quickly scan a large XML document, then stop when it finds a match to your search criterion and hand you the appropriate fragment from the document.
In some situations, the best choice is to employ both DOM and SAX for different aspects of a single solution. For example, you might want to load XML into memory and modify it with DOM, but then transmit the final result by emitting a SAX stream from the DOM tree.

DOM: Tree-Based API
A tree-based API (such as DOM) builds an in-memory tree representation of the XML document. It provides classes and methods for an application to navigate and process the tree.
In general, the DOM interface is most useful for structural manipulations of the XML tree, such as reordering elements, adding or deleting elements and attributes, renaming elements, and so on. For example, for the immediately preceding XML document, the DOM creates an in-memory tree structure as shown in Figure 3-3.
SAX: Event-Based API
An event-based API (such as SAX) uses calls to report parsing events to the application. Your Java application deals with these events through customized event handlers. Events include the start and end of elements and characters.
Unlike tree-based APIs, event-based APIs usually do not build in-memory tree representations of the XML documents. Therefore, in general, SAX is useful for applications that do not need to manipulate the XML tree, such as search operations, among others. The preceding XML document becomes a series of linear events as shown in Figure 3-3.
Figure 3-3 Comparing DOM (Tree-Based) and SAX (Event-Based) APIs

Ternary operator
minVal = (a < b; a ? b);
In this code, if the variable a is less than b, minVal is assigned the value of a; otherwise, minVal is assigned the value of b. Note that the parentheses in this example are optional, but I use them to improve the readability of the code.

OR

minVal = getMinVal() == 1 ?true:false;























EAD4J

EAD4J - Enterprise Application Development frameworks for Java

EAD4J is comprised of a variety of components, one of which handles the VC (from MVC) in the model II (JSP/Servlet) framework space. The open-source framework Struts also provides similar functionality.


EAD4J, is an IBM BIS Java set of frameworks for the J2EE environment. There are currently seven gems in the package with others on the way.

1.EAD4J.Jade provides the base application infrastructure for a model II JSP/Servlet application.

2.EAD4J.Topaz is a set of guidelines and code to achieve a level of abstraction in regards to business processing, business modeling, and persistence.

3.EAD4J.Diamond is a security model that is intended to provide a unified set of security
services that will secure applications developed using the EAD4J.Jade Framework and
Programming Model.

4.EAD4J.Amethyst is a component that provides SOAP and WebServices functionality.
This allows the components built with EAD4J to be reutilized as service provider applications.
5. Onyx
6. Ruby
7. Emerald
8. Amber.
MVC I and II differences :-


WebSphere Studio Workbench is built on the open-source Eclipse Platform.



How you do performance testing:
= using ‘Java Profiler’ (it tells which class takes how much time to execute; which variables occupy how much spaces.)
= Using Load Runner tool. This is product of Mercury company.




Design Pattern

Creational (CategoryCreationalPatterns)
· AbstractFactoryPattern
· FactoryMethodPattern
· SingletonPattern
· PrototypePattern
· BuilderPattern
Structural (CategoryStructuralPatterns)
· FacadePattern
· BridgePattern
· CompositePattern
· DecoratorPattern
· AdapterPattern
· FlyweightPattern
· ProxyPattern
Behavioral (CategoryBehavioralPatterns)
· ObserverPattern
· ChainOfResponsibilityPattern
· CommandPattern
· InterpreterPattern
· IteratorPattern
· MediatorPattern
· MementoPattern
· StatePattern
· StrategyPattern
· TemplateMethodPattern
· VisitorPattern
Observer Pattern:
Simply, the Observer pattern allows one object (the observer) to watch another (the subject). The Observer pattern allows the subject and observer to form a publish-subscribe relationship. Through the Observer pattern, observers can register to receive events from the subject. When the subject needs to inform its observers of an event, it simply sends the event to each observer.

For example, you might have a spreadsheet that has an underlying data model. Whenever the data model changes, the spreadsheet will need to update the spreadsheet screen and an embedded graph. In this example, the subject is the data model and the observers are the screen and graph. When the observers receive notification that the model has changes, they can update themselves.

How to use Factory Pattern:
Say we have a certain functionality to do, but those functionality would be different for different classes. And at run time we don’t know which class’s functionality to use.
1. for that define an interface with all those functionality.
2. Write multiple classes implementing the interfaces. These all classes are will be implementing those functions in their own way.
3. Make a Class (name it as ….Factory)
4. Inside this Factory class create the instances of these different implementing classes, with reference to interface. And return the object to the caller method.
Now the decision to create object of which class is may be dependent on the parameter passed to factory class by the caller method.
The method in Factory class, which created the object, may be Singleton or simply static method.
So we can say:-
A Factory pattern is one that returns an instance of one of several possible classes depending on the data provided to it. Usually all of the classes it returns have a common parent class and common methods, but each of them performs a task differently and is optimized for different kinds of data


Factory Pattern:-


public class Person {

public String name;
private String sex;

public String getName() {return name;}
public String getSex() {return gender;}
}

public class Female extends Person {

public Female(String fullNname) {
System.out.println("Hello Ms. " + fullNname);
}
}

public class Male extends Person {

public Male(String fullName) {
System.out.println("Hello Mr. " + fullName);
}
}


public class SalutationFactory {

public static void main(String args[]) {

//USING SINGLETON CREATE THE OBJECT OF ‘SalutationFactory’//
SalutationFactory factory = new SalutationFactory();
factory.getPerson("Ramesh", "M");
}

public Person getPerson(String name, String sex) {
if (sex.equals("M")) return new Male(name);
else if (sex.equals("F")) return new Female(name);

else return null;
}

}

When to use a Factory Pattern?
The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer's language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.
Abstract Factory Pattern
This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes.
public abstract class Computer {
public abstract Parts getRAM();
public abstract Parts getProcessor();
public abstract Parts getMonitor();
}

public class Parts {
public String specification;
public Parts(String specification) { this.specification = specification; }
}



public class PC extends Computer {public Parts getRAM() { return new Parts("512 MB");}public Parts getProcessor() {return new Parts("Celeron");}} public class Workstation extends Computer {public Parts getRAM() { return new Parts("1 GB");}public Parts getProcessor() { return new Parts("Intel P3");}}



public class ComputerType {
private Computer comp;
public static void main(String[] args) {

ComputerType type = new ComputerType();
Computer computer = type.getComputer("PC");
System.out.println("RAM: "+computer.getRAM().getSpecification());
System.out.println("Processor: "+computer.getProcessor().getSpecification());
}

public Computer getComputer(String computerType) {
if (computerType.equals("PC"))
comp = new PC();
else if(computerType.equals("Workstation"))
comp = new Workstation();

return comp;
}

}




When to use Abstract Factory Pattern?
One of the main advantages of Abstract Factory Pattern is that
it isolates the concrete classes that are generated.
The names of actual implementing classes are not needed to be known at the client side.
Because of the isolation, you can change the implementation from one factory to another.


Façade Pattern
Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face.
This is how facade pattern is used. It hides the complexities of the system and provides an interface to the client from where the client can access the system. In Java, the interface JDBC can be called a facade. We as users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. The implementation is left to the vendor of driver.

So it is like: SessionFacade, MessageFacade. SessionFacader takes request from user and internally interacts with Mulitple Entity beans and gives result to user in the form of response. So here User do not care abou how the SessionFacade works and what are the complexity under which it acts.
Adaptor Pattern
The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using an Adapter.

Command Pattern
This is another of the data-driven pattern. The client invokes a particular module using a command. The client passes a request; this request gets propagated as a command. The command request maps to particular modules. According to the command, a module is invoked.

This pattern is different from the Chain of Responsibility in a way that, in the earlier one, the request passes through each of the classes before finding an object that can take the responsibility. The command pattern however finds the particular object according to the command and invokes only that one.

It’s like there is a server having a lot of services to be given, and on Demand (or on command), it caters to that service for that particular client.

A classic example of this is a restaurant. A customer goes to restaurant and orders the food according to his/her choice. The waiter/ waitres takes the order (command, in this case) and hands it to the cook in the kitchen. The cook can make several types of food and so, he/she prepares the ordered item and hands it over to the waiter/waitress who in turn serves to the customer.

Let’s have a look at this example with Java code.

First thing is the Order. The order is made of command which the customer gives the waiter.

Order.java
/**
* This is the command. The customer orders and hands it to the waiter.
*/
public class Order {
private String command;
public Order(String command) {
this.command = command;
}
}
}
The other thing is the waiter who takes the order and forwards it to the cook.

Waiter.java
/**
* A waiter is associated with multiple customers and multiple orders
*/
public class Waiter {
public Food takeOrder(Customer cust, Order order) {
Cook cook = new Cook();
Food food = cook.prepareOrder(order, this);
return food;
}
}
The waiter calls the prepareFood method of the cook who in turn cooks.

Cook.java
public class Cook {
public Food prepareOrder(Order order, Waiter waiter) {
Food food = getCookedFood(order);
return food;
}
public Food getCookedFood(Order order) {
Food food = new Food(order);
return food;
}
}
Now, here, the waiter takes command and wraps it in an order, the order is associated to a particular customer. For, the cook, the order is associated to a cook and also Food is associated to the Order.

The order is an object which depends on the command. The food item will change as soon as the command changes. This is loose-coupling between the client and the implementation.

JTA
Using JDBC APIs for transaction management in an environment involving multiple databases or distributed databases is impractical. It is here that Java Transaction APIs, also known as JTA, come into the picture.
distributed database transactions require JTA.

Comments

Popular posts from this blog

RTC - Repository : How to Revert Back the Changes