Friday, August 20, 2010

Static imports in java 1.5

Static imports allow the static items of another class to be referenced without qualification.

package com;

import static com.StaticImportMe.doStaticImportOnMe;

public class StaticImport {

 /**
  * @param args
  */
 public static void main(String[] args) {
  /**
   * No need to use StaticImportMe.doStaticImportOnMe(args[0]); 
   */
  doStaticImportOnMe(args[0]);
 }

}

Saturday, July 31, 2010

Thread - simple note

Thread - a Breaf Note

Threads - Thread Synchronization

* every instance of class Object and its subclass's has a lock
* primitive data type fields (Scalar fields) can only be locked via their enclosing class
* fields cannot be marked as synchronized however they can be declared volatile which orders the way they can be used or you can write synchronized accessor methods
* array objects can be synchronized BUT their elements cannot, nor can their elements be declared volatile
* Class instances are Objects and can be synchronized via static synchronized methods

Synchronized blocks

* allow you to execute synchronized code that locks an object without requiring you to invoke a synchronized method

synchronized( expr ) {
// 'expr' must evaluate to an Object
}

Synchronized methods

* declaring a method as synchronized ie synchronized void f() is equivalent to

void f() { synchronized(this) {
// body of method
}
}

* the synchronized keyword is NOT considered part of a method's signature. IT IS NOT AUTOMATICALLY INHERITED when subclasses override superclass methods
* methods in Interfaces CANNOT be declared synchronized
* constructors CANNOT be declared synchronized however they can contain synchronized blocks
* synchronized methods in subclasses use the same locks as their superclasses
* synchronization of an Inner Class is independent on it's outer class
* a non-static inner class method can lock it's containing class by using a synchronized block

synchronized(OuterClass.this) {
// body
}

Locking

* locking follows a built-in acquire-release protocol controlled by the synchronized keyword
* a lock is acquired on entry to a synchronized method or block and released on exit, even if the exit is the result of an exception
* you cannot forget to release a lock
* locks operate on a per thread basis, not on a per-invocation basis
* Java uses re-entrant locks ie a thread cannot lock on itself

class Reentrant {

public synchronized void a() {
b();
System.out.println("here I am, in a()");
}
public synchronized void b() {
System.out.println("here I am, in b()");
}
}

* in the above code, the synchronized method a(), when executed, obtains a lock on it's own object. It then calls synchronized method b() which also needs to acquire a lock on it's own object
* if Java did not allow a thread to reacquire it's own lock method b() would be unable to proceed until method a() completed and released the lock; and method a() would be unable to complete until method b() completed. Result: deadlock
* as Java does allow reentrant locks, the code compiles and runs without a problem

* the locking protocol is only followed for synchronized methods, it DOES NOT prevent unsynchronized methods from accessing the object
* once a thread releases a lock, another thread may acquire it BUT there is no guarantee as to WHICH thread will acquire the lock next

Class fields and methods

* locking an object does not automatically protect access to static fields
* protecting static fields requires a synchronized static block or method
* static synchronized statements obtain a lock on the Class vs an instance of the class
* a synchronized instance method can obtain a lock on the class

synchronized(ClassName.class) {
// body
}

* the static lock on a class is not related to any other class including it's superclasses
* a lock on a static method has no effect on any instances of that class (JPL pg 185)
* you cannot effectively protect static fields in a superclass by adding a new static synchronized method in a subclass; an explicit block synchronization is the preferred way
* nor should you use synchronized(getClass()); this locks the actual Class which might be different from the class in which the static fields are declared

Thursday, July 29, 2010

Inner Classes in Java

As we all know what an inner class is so lets try to know few more rules about Inner Classes.

Inner classes cannot have static members. only static final variables.

Interfaces are never inner.

Static classes are not inner classes.

Inner classes may inherit static members that are not compile-time constants even though they may not declare them.

Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language. Member interfaces are always implicitly static so they are never considered to be inner classes.A statement or expression occurs in a static context if and only if the innermost method, constructor, instance initializer, static initializer, field initializer, or explicit constructor invocation statement enclosing the statement or expression is a static method, a static initializer, the variable initializer of a static variable, or an explicit constructor invocation statement.

A blank final field of a lexically enclosing class may not be assigned within an inner class.


For Example:

class HasStatic {
static int j = 100;
}

class Outer{

final int z=10;

class Inner extends HasStatic {
static final int x = 3;
static int y = 4;
}

static class Inner2 {
public static int size=130;
}

interface InnerInteface {
public static int size=100;
}
}

public class InnerClassDemo {

public static void main(String[] args) {

Outer outer=new Outer();
System.out.println(outer.new Inner().y);
System.out.println(outer.new Inner().x);
System.out.println(outer.new Inner().j);

System.out.println(Outer.Inner2.size);

System.out.println(Outer.InnerInteface.size);
}
}

Hence it gives compilation problems as y cannot be used in inner class "Inner".

Also note Method parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor. However, a parameter of a method or constructor may be shadowed anywhere inside a class declaration nested within that method or constructor. Such a nested class declaration could declare either a local class or an anonymous class.


For Example:
public class MethodParameterExamples {

public String s="bt";

public void m1(String s) {
s=this.s;
s="uk";

//abstract
class InnerClass extends MethodParameterExamples {

String s="ros";

public void m1() {
System.out.println(super.s=this.s);
}
}

InnerClass innerClass=new InnerClass();
innerClass.s=s;
innerClass.m1();

}

public static void main(String[] args) {

MethodParameterExamples methodParameterExamples=new MethodParameterExamples();
methodParameterExamples.m1("vij");
System.out.println(methodParameterExamples.s);

}

}

Hence Prints the output:
uk
bt

Now coming to Section Nested Inner Classes:

Consider the below program.


class WithDeepNesting {
boolean toBe;

WithDeepNesting(boolean b) { toBe = b;}

class Nested {
boolean theQuestion;

class DeeplyNested {

DeeplyNested(){
theQuestion = toBe || !toBe;
}
}
}

public static void main(String[] args) {

WithDeepNesting withDeepNesting=new WithDeepNesting(true);
WithDeepNesting.Nested nested=withDeepNesting.new Nested();
nested.new DeeplyNested();
System.out.println(nested.theQuestion);

}
}

Please note that Inner classes whose declarations do not occur in a static context may freely refer to the instance variables of their enclosing class. An instance variable is always defined with respect to an instance. In the case of instance variables of an enclosing class, the instance variable must be defined with respect to an enclosing instance of that class. So, for example, the class Local above has an enclosing instance of class Outer. As a further example:

Here, every instance of WithDeepNesting.Nested.DeeplyNested has an enclosing instance of class WithDeepNesting.Nested (its immediately enclosing instance) and an enclosing instance of class WithDeepNesting (its 2nd lexically enclosing instance). Hence it prints: true.

Serialization Interview Questions

Q1) What is Serialization?

Ans) Serializable is a marker interface. When an object has to be transferred over a network ( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs to implement Serializable interface. Implementing this interface will allow the object converted into bytestream and transfer over a network.

Q2) What is use of serialVersionUID?

Ans) During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

* Add fields
* Change a field from static to non-static
* Change a field from transient to non-transient
* Add classes to the object tree

List of incompatible changes:

* Delete fields
* Change class hierarchy
* Change non-static to static
* Change non-transient to transient
* Change type of a primitive field

So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly metion the suid using the statement:

private final static long serialVersionUID =

then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Q3) What is the need of Serialization?

Ans) The serialization is used :-

* To send state of one or more object’s state over the network through a socket.
* To save the state of an object in a file.
* An object’s state needs to be manipulated as a stream of bytes.

Q4) Other than Serialization what are the different approach to make object Serializable?

Ans) Besides the Serializable interface, at least three alternate approaches can serialize Java objects:

1)For object serialization, instead of implementing the Serializable interface, a developer can implement the Externalizable interface, which extends Serializable. By implementing Externalizable, a developer is responsible for implementing the writeExternal() and readExternal() methods. As a result, a developer has sole control over reading and writing the serialized objects.
2)XML serialization is an often-used approach for data interchange. This approach lags runtime performance when compared with Java serialization, both in terms of the size of the object and the processing time. With a speedier XML parser, the performance gap with respect to the processing time narrows. Nonetheless, XML serialization provides a more malleable solution when faced with changes in the serializable object.
3)Finally, consider a "roll-your-own" serialization approach. You can write an object's content directly via either the ObjectOutputStream or the DataOutputStream. While this approach is more involved in its initial implementation, it offers the greatest flexibility and extensibility. In addition, this approach provides a performance advantage over Java serialization.

Q5) Do we need to implement any method of Serializable interface to make an object serializable?

Ans) No. Serializable is a Marker Interface. It does not have any methods.

Q6) What happens if the object to be serialized includes the references to other serializable objects?

Ans) If the object to be serialized includes the references to other objects whose class implements serializable then all those object’s state also will be saved as the part of the serialized state of the object in question. The whole object graph of the object to be serialized will be saved during serialization automatically provided all the objects included in the object’s graph are serializable.

Q7) What happens if an object is serializable but it includes a reference to a non-serializable object?

Ans- If you try to serialize an object of a class which implements serializable, but the object includes a reference to an non-serializable class then a ‘NotSerializableException’ will be thrown at runtime.

e.g.

public class NonSerial {
//This is a non-serializable class
}

public class MyClass implements Serializable{
private static final long serialVersionUID = 1L;
private NonSerial nonSerial;
MyClass(NonSerial nonSerial){
this.nonSerial = nonSerial;
}
public static void main(String [] args) {
NonSerial nonSer = new NonSerial();
MyClass c = new MyClass(nonSer);
try {
FileOutputStream fs = new FileOutputStream("test1.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("test1.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (MyClass) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

On execution of above code following exception will be thrown –
java.io.NotSerializableException: NonSerial
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java)

Q8) Are the static variables saved as the part of serialization?

Ans) No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object.

Q9) What is a transient variable?

Ans) These variables are not included in the process of serialization and are not the part of the object’s serialized state.

Q10) What will be the value of transient variable after de-serialization?

Ans) It’s default value.
e.g. if the transient variable in question is an int, it’s value after deserialization will be zero.

public class TestTransientVal implements Serializable{

private static final long serialVersionUID = -22L;
private String name;
transient private int age;
TestTransientVal(int age, String name) {
this.age = age;
this.name = name;
}

public static void main(String [] args) {
TestTransientVal c = new TestTransientVal(1,"ONE");
System.out.println("Before serialization: - " + c.name + " "+ c.age);
try {
FileOutputStream fs = new FileOutputStream("testTransients.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }


try {
FileInputStream fis = new FileInputStream("testTransients.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (TestTransientVal) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After de-serialization:- " + c.name + " "+ c.age);
}

}

Result of executing above piece of code –
Before serialization: - Value of non-transient variable ONE Value of transient variable 1
After de-serialization:- Value of non-transient variable ONE Value of transient variable 0

Explanation –
The transient variable is not saved as the part of the state of the serailized variable, it’s value after de-serialization is it’s default value.

Q11) Does the order in which the value of the transient variables and the state of the object using the defaultWriteObject() method are saved during serialization matter?

Ans) Yes. As while restoring the object’s state the transient variables and the serializable variables that are stored must be restored in the same order in which they were saved.

Q12) How can one customize the Serialization process? or What is the purpose of implementing the writeObject() and readObject() method?

Ans) When you want to store the transient variables state as a part of the serialized object at the time of serialization the class must implement the following methods –
private void wrtiteObject(ObjectOutputStream outStream)
{
//code to save the transient variables state as a part of serialized object
}

private void readObject(ObjectInputStream inStream)
{
//code to read the transient variables state and assign it to the de-serialized object
}

e.g.

public class TestCustomizedSerialization implements Serializable{

private static final long serialVersionUID =-22L;
private String noOfSerVar;
transient private int noOfTranVar;

TestCustomizedSerialization(int noOfTranVar, String noOfSerVar) {
this.noOfTranVar = noOfTranVar;
this.noOfSerVar = noOfSerVar;
}

private void writeObject(ObjectOutputStream os) {

try {
os.defaultWriteObject();
os.writeInt(noOfTranVar);
} catch (Exception e) { e.printStackTrace(); }
}

private void readObject(ObjectInputStream is) {
try {
is.defaultReadObject();
int noOfTransients = (is.readInt());
} catch (Exception e) {
e.printStackTrace(); }
}

public int getNoOfTranVar() {
return noOfTranVar;
}

}

The value of transient variable ‘noOfTranVar’ is saved as part of the serialized object manually by implementing writeObject() and restored by implementing readObject().
The normal serializable variables are saved and restored by calling defaultWriteObject() and defaultReadObject()respectively. These methods perform the normal serialization and de-sirialization process for the object to be saved or restored respectively.

Q13) If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from super class after deserialization?

Ans) The values of the instance variables inherited from superclass will be reset to the values they were given during the original construction of the object as the non-serializable super-class constructor will run.
E.g.

public class ParentNonSerializable {
int noOfWheels;

ParentNonSerializable(){
this.noOfWheels = 4;
}

}

public class ChildSerializable extends ParentNonSerializable implements Serializable {

private static final long serialVersionUID = 1L;
String color;

ChildSerializable() {
this.noOfWheels = 8;
this.color = "blue";
}
}

public class SubSerialSuperNotSerial {

public static void main(String [] args) {

ChildSerializable c = new ChildSerializable();
System.out.println("Before : - " + c.noOfWheels + " "+ c.color);
try {
FileOutputStream fs = new FileOutputStream("superNotSerail.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }

try {
FileInputStream fis = new FileInputStream("superNotSerail.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (ChildSerializable) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After :- " + c.noOfWheels + " "+ c.color);
}

}

Result on executing above code –
Before : - 8 blue
After :- 4 blue

The instance variable ‘noOfWheels’ is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.

Q14) To serialize an array or a collection all the members of it must be serializable. True /False?

Ans) true.
-------------------------------------------------------
How many methods in the Serializable interface? Which methods of Serializable interface should I implement?

There is no method in the Serializable interface. It’s an empty interface which does not contain any methods. The Serializable interface acts as a marker, telling the object serialization tools that the class is serializable. So we do not implement any methods.

What is the difference between Serializalble and Externalizable interface? How can you control over the serialization process i.e. how can you customize the seralization process?

When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

How to make a class or a bean serializable? How do I serialize an object to a file?

Or

What interface must an object implement before it can be written to a stream as an object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

What happens to the object references included in the object?

The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original object.

What is serialization?

The serialization is a kind of mechanism that makes a class or a bean persistent by having its properties or fields and state information saved and restored to and from storage. That is, it is a mechanism with which you can save the state of an object by converting it to a byte stream.

Common Usage of serialization.

Whenever an object is to be sent over the network or saved in a file, objects are serialized.

What happens to the static fields of a class during serialization?

There are three exceptions in which serialization doesn’t necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields.

What one should take care of while serializing the object?

One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

What is a transient variable?

Or

Explain the usage of the keyword transient?

Or

What are Transient and Volatile Modifiers

A transient variable is a variable that may not be serialized i.e. the value of the variable can’t be written to the stream in a Serializable class. If you don't want some field to be serialized, you can mark that field transient or static. In such a case when the class is retrieved from the ObjectStream the value of the variable is null.

Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

What is Serialization and deserialization?

Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

What is Externalizable?

Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.



If you think that an important java interview question is missing or some answers are wrong in the site please contribute it to sriniappl@gmail.com

Wednesday, July 21, 2010

The basics: override hashCode() and equals()

If you want to override equals method in your class, you should also override hashCode method as well. There are a lot of ways the two methods can be implemented incorrectly.

I found the easiest way is to use the wizard in Eclipse, just running Source | Generate hashCode() and equals()... either from menu or context menu. For example, this is what Eclipse generated for a simple class Scrap with a instance variable number:

Correct Implementation Example

The following code exemplifies how all the requirements of equals and hashCode methods should be fulfilled so that the class behaves correctly and consistently with other Java classes. This class implements the equals method in such a way that it only provides equality comparison for the objects of the same class, similar to built-in Java classes like String and other wrapper classes.


package com;

class Test {
private int x;
private String y;
public Test(int x, String y) {

this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + ((y == null) ? 0 : y.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Test)) {
return false;
}
Test other = (Test) obj;
if (x != other.x) {
return false;
}
if (y == null) {
if (other.y != null) {
return false;
}
} else if (!y.equals(other.y)) {
return false;
}
return true;
}



}

public class HashCodeAndEquals {

/**
* @param args
*/
public static void main(String[] args) {


Test t = new Test(10,"rama");
Test t1 = new Test(10,"rama");
System.out.println(t==t1);
System.out.println(t.hashCode()==t1.hashCode());
System.out.println(t.equals(t1));
}
}
-------------------------------------------------------------
The theory (for the language lawyers and the mathematically inclined):

equals() (javadoc) must define an equality relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
In practice:

If you override one, then you should override the other.

Use the same set of fields that you use to compute equals() to compute hashCode().

Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:

public class Person {
private String name;
private int age;
// ...

public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}

public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (obj.getClass() != getClass())
return false;

Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}

Also remember:

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits

Tuesday, July 20, 2010

Struts Spring Plugin

* Overview
* Features
* What's New
o Discontinued - April 12, 2004
o 0.1 - October 17, 2003
* Requirements
* Usage
* Contact

Overview

This project was originally created to integrate the Spring Framework's Inversion of Control (IoC) into Struts 1.1+. As of Spring's 1.0.1 release, the ContextLoaderPlugin was added to Spring that has this same functionality. Therefore, this project's plugin is no longer recommended for use. We continue to maintain this site for documentation and an example app.

The integration uses Spring to create and populate Struts actions, using IoC to resolve dependencies. It does NOT use a custom request processor and therefore can be more easily used with existing web applications and/or other Struts extensions.

To demonstrate the project, we modified the struts-example webapp that is distributed with Struts 1.1 to use Spring to resolve all UserDatabase dependencies automatically. Comments and suggestions are appreciated.
Features

* Intuitive Inversion of Control (IoC)
* Requires little or no direct references to Spring in the Struts webapp
* Can be used with other Struts extensions that use a custom RequestProcessor
* Can create new Actions for every request (aleviating need for thread-safe Actions)
* Includes modified Struts example

What's New
Discontinued - April 12, 2004

* This plugin is now part of Spring (as of 1.0.1). You can read more about Spring's Struts support on Matt Raible's Spring Live blog.

0.1 - October 17, 2003

* Initial release

Requirements

This plugin requires Struts 1.1 or greater.
Usage

To use the Struts Spring plugin, add the ContextLoaderPlugIn to your Struts config file (usually struts-config.xml):





The "contextConfigLocation" property is the location of the Spring beans configuration file.

For each action that uses Spring, you need to define the action mapping to use org.springframework.web.struts.DelegatingActionProxy and declare a matching (action "path" == bean "name") Spring bean for the actual Struts action. This is an example of an action that requires an instance of UserDatabase:





The corresponding Spring bean configuration:







For more information on the Spring configuration file format, see the Spring beans DTD.

The Struts action org.apache.struts.webapp.example.LogonAction will automatically receive a reference to UserDatabase without any work on its part or references to Spring by adding a standard JavaBean setter:

private UserDatabase database = null;

public void setUserDatabase(UserDatabase database) {
this.database = database;
}

hashCode() and equals()

with out overriding of hashCode() method.

package com;

class Test{
String r;
Test(String r){
this.r =r;
}
}

public class TestHashCodeAndEquals {

private int no;
private String name;
public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setNo(int no) {
this.no = no;
}

public int getNo() {
return no;
}

public TestHashCodeAndEquals(int no,String name) {
this.setNo(no);
this.setName(name);

}

/*@Override
public int hashCode() {

return 11;
}*/

public static void main(String[] args) {

TestHashCodeAndEquals o1 = new TestHashCodeAndEquals(1,"rama");
System.out.println(o1.hashCode());
TestHashCodeAndEquals o2 = new TestHashCodeAndEquals(1,"rama");
System.out.println(o2.hashCode());
System.out.println(o1.equals(o2));
System.out.println((o1==o2)+" wew");

String s1 = "rama";
String s2 = "rama";
System.out.println(s1==s2);
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
String s11 = new String("rama");
String s21 = new String("rama");
System.out.println(s11==s21);
System.out.println(s11.equals(s21));
System.out.println(s11.hashCode());
System.out.println(s21.hashCode());
Integer i1 = new Integer(10);
Integer i2 = new Integer(1234);
System.out.println(i1==i2);
System.out.println(i1.equals(i2));
System.out.println(i1.hashCode());
System.out.println(i2.hashCode());
Test t1 = new Test("rama");
Test t2 = new Test("rama");
System.out.println(t1.equals(t2));
System.out.println(t1.hashCode());
System.out.println(t2.hashCode());

Thread t = new Thread();
Thread t11 = new Thread(t);
System.out.println(t.hashCode()+" "+t11.hashCode());

// other than System defined wapper classes, we will not get the hashcode equal if and only if we override the hashCode() method in our class.

// even though we override the hashCode() ,override the hashCode() in our class,we can have same hashcode for all instance ,still, equals() will return false

}
}
out put
.......
-1-
4072869
1671711
false
false wew
-2-
true
3492867
3492867
-3-
false
true
3492867
3492867
-4-
false
false
10
1234
-5-
false
4384790
9634993
-6-
1641745 11077203

------------------------------------------------------------------
with overriding of hashCode() method.
package com;

class Test{
String r;
Test(String r){
this.r =r;
}
}

public class TestHashCodeAndEquals {

private int no;
private String name;
public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setNo(int no) {
this.no = no;
}

public int getNo() {
return no;
}

public TestHashCodeAndEquals(int no,String name) {
this.setNo(no);
this.setName(name);

}

@Override
public int hashCode() {

return 11;
}

public static void main(String[] args) {

System.out.println("-1-");
TestHashCodeAndEquals o1 = new TestHashCodeAndEquals(1,"rama");
System.out.println(o1.hashCode());
TestHashCodeAndEquals o2 = new TestHashCodeAndEquals(1,"rama");
System.out.println(o2.hashCode());
System.out.println(o1.equals(o2));
System.out.println((o1==o2)+" wew");

String s1 = "rama";
String s2 = "rama";
System.out.println("-2-");
System.out.println(s1==s2);
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println("-3-");
String s11 = new String("rama");
String s21 = new String("rama");
System.out.println(s11==s21);
System.out.println(s11.equals(s21));
System.out.println(s11.hashCode());
System.out.println(s21.hashCode());
System.out.println("-4-");
Integer i1 = new Integer(10);
Integer i2 = new Integer(1234);
System.out.println(i1==i2);
System.out.println(i1.equals(i2));
System.out.println(i1.hashCode());
System.out.println(i2.hashCode());
System.out.println("-5-");
Test t1 = new Test("rama");
Test t2 = new Test("rama");
System.out.println(t1.equals(t2));
System.out.println(t1.hashCode());
System.out.println(t2.hashCode());
System.out.println("-6-");
Thread t22 = new Thread();
Thread t11 = new Thread(t22);
System.out.println(t22.hashCode()+" "+t11.hashCode());

// other than System defined wapper classes, we will not get the hashcode equal if and only if we override the hashCode() method in our class.

// even though we override the hashCode() ,override the hashCode() in our class,we can have same hashcode for all instance ,still, equals() will return false

}
}
out put
.......
-1-
11
11
false
false wew
-2-
true
3492867
3492867
-3-
false
true
3492867
3492867
-4-
false
false
10
1234
-5-
false
1671711
11394033
-6-
4384790 9634993

The DROP TRIGGER statement

In a DROP TRIGGER statement, the table name must be prepended to the name of the trigger:
DROP TRIGGER . mysql>
mysql>
mysql>
mysql> CREATE TABLE Employee(
-> id int,
-> first_name VARCHAR(15),
-> last_name VARCHAR(15),
-> start_date DATE,
-> end_date DATE,
-> salary FLOAT(8,2),
-> city VARCHAR(10),
-> description VARCHAR(15)
-> );
Query OK, 0 rows affected (0.03 sec)

mysql>
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, salary, City, Description)
-> values (1,'Jason', 'Martin', '19960725', '20060725', 1234.56, 'Toronto', 'Programmer');
Query OK, 1 row affected (0.00 sec)

mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, salary, City, Description)
-> values(2,'Alison', 'Mathews', '19760321', '19860221', 6661.78, 'Vancouver','Tester');
Query OK, 1 row affected (0.00 sec)

mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, salary, City, Description)
-> values(3,'James', 'Smith', '19781212', '19900315', 6544.78, 'Vancouver','Tester');
Query OK, 1 row affected (0.00 sec)

mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, salary, City, Description)
-> values(4,'Celia', 'Rice', '19821024', '19990421', 2344.78, 'Vancouver','Manager');
Query OK, 1 row affected (0.00 sec)

mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, salary, City, Description)
-> values(5,'Robert', 'Black', '19840115', '19980808', 2334.78, 'Vancouver','Tester');
Query OK, 1 row affected (0.00 sec)

mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, salary, City, Description)
-> values(6,'Linda', 'Green', '19870730', '19960104', 4322.78,'New York', 'Tester');
Query OK, 1 row affected (0.00 sec)

mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, salary, City, Description)
-> values(7,'David', 'Larry', '19901231', '19980212', 7897.78,'New York', 'Manager');
Query OK, 1 row affected (0.02 sec)

mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, salary, City, Description)
-> values(8,'James', 'Cat', '19960917', '20020415', 1232.78,'Vancouver', 'Tester');
Query OK, 1 row affected (0.00 sec)

mysql>
mysql> select * from Employee;
+------+------------+-----------+------------+------------+---------+-----------+-------------+
| id | first_name | last_name | start_date | end_date | salary | city | description |
+------+------------+-----------+------------+------------+---------+-----------+-------------+
| 1 | Jason | Martin | 1996-07-25 | 2006-07-25 | 1234.56 | Toronto | Programmer |
| 2 | Alison | Mathews | 1976-03-21 | 1986-02-21 | 6661.78 | Vancouver | Tester |
| 3 | James | Smith | 1978-12-12 | 1990-03-15 | 6544.78 | Vancouver | Tester |
| 4 | Celia | Rice | 1982-10-24 | 1999-04-21 | 2344.78 | Vancouver | Manager |
| 5 | Robert | Black | 1984-01-15 | 1998-08-08 | 2334.78 | Vancouver | Tester |
| 6 | Linda | Green | 1987-07-30 | 1996-01-04 | 4322.78 | New York | Tester |
| 7 | David | Larry | 1990-12-31 | 1998-02-12 | 7897.78 | New York | Manager |
| 8 | James | Cat | 1996-09-17 | 2002-04-15 | 1232.78 | Vancouver | Tester |
+------+------------+-----------+------------+------------+---------+-----------+-------------+
8 rows in set (0.00 sec)

mysql>
mysql>
mysql>
mysql> DELIMITER //
mysql>
mysql> CREATE TRIGGER myTrigger BEFORE UPDATE ON employee
-> FOR EACH ROW
-> BEGIN
->
-> IF NEW.id > 5 THEN
-> SET NEW.first_name = NEW.first_name+ " *";
-> END IF;
->
-> IF NEW.salary IS NULL OR NEW.salary = 0 THEN
-> SET NEW.salary = 100;
-> ELSE
-> SET NEW.salary = NEW.salary + 100;
-> END IF;
->
-> END
->
-> //
Query OK, 0 rows affected (0.02 sec)

mysql> DELIMITER ;
mysql>
mysql> SELECT * FROM INFORMATION_SCHEMA.TRIGGERS;
+-----------------+----------------+--------------+--------------------+----------------------+---------------------+--------------------+--------------+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+---------------+----------------------------+----------------------------+--------------------------+--------------------------+---------+----------+----------------+
| TRIGGER_CATALOG | TRIGGER_SCHEMA | TRIGGER_NAME | EVENT_MANIPULATION | EVENT_OBJECT_CATALOG | EVENT_OBJECT_SCHEMA | EVENT_OBJECT_TABLE | ACTION_ORDER | ACTION_CONDITION | ACTION_STATEMENT | ACTION_ORIENTATION | ACTION_TIMING | ACTION_REFERENCE_OLD_TABLE | ACTION_REFERENCE_NEW_TABLE | ACTION_REFERENCE_OLD_ROW | ACTION_REFERENCE_NEW_ROW | CREATED | SQL_MODE | DEFINER |
+-----------------+----------------+--------------+--------------------+----------------------+---------------------+--------------------+--------------+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+---------------+----------------------------+----------------------------+--------------------------+--------------------------+---------+----------+----------------+
| NULL | test | myTrigger | UPDATE | NULL | test | employee | 0 | NULL | BEGIN
IF NEW.id > 5 THEN
SET NEW.first_name = NEW.first_name+ " *";
END IF;
IF NEW.salary IS NULL OR NEW.salary = 0 THEN
SET NEW.salary = 100;
ELSE
SET NEW.salary = NEW.salary + 100;
END IF;
END | ROW | BEFORE | NULL | NULL | OLD | NEW | NULL | | root@localhost |
+-----------------+----------------+--------------+--------------------+----------------------+---------------------+--------------------+--------------+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+---------------+----------------------------+----------------------------+--------------------------+--------------------------+---------+----------+----------------+
1 row in set (0.03 sec)

mysql>
mysql>
mysql> DROP TRIGGER myTrigger;
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> SELECT * FROM INFORMATION_SCHEMA.TRIGGERS;
Empty set (0.02 sec)

mysql>
mysql>
mysql> drop table Employee;
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql>

Monday, July 19, 2010

assertion replacing sop()s in code debugging from JDK 1.4

Assertion in Java

Assertion facility is added in J2SE 1.4. In order to support this facility J2SE 1.4 added the keyword assert to the language, and AssertionError class. An assertion checks a boolean-typed expression that must be true during program runtime execution. The assertion facility can be enabled or disable at runtime.

Declaring Assertion

Assertion statements have two forms as given below

assert expression;

assert expression1 : expression2;

The first form is simple form of assertion, while second form takes another expression. In both of the form boolean expression represents condition that must be evaluate to true runtime.

If the condition evaluates to false and assertions are enabled, AssertionError will be thrown at runtime.

Some examples that use simple assertion form are as follows.

assert value > 5 ;

assert accontBalance > 0;

assert isStatusEnabled();

The expression that has to be asserted runtime must be boolean value. In third example isStatusEnabled() must return boolean value. If condition evaluates to true, execution continues normally, otherwise the AssertionError is thrown.

Following program uses simple form of assertion

//AssertionDemo.java

Class AssertionDemo{

Public static void main(String args[]){

System.out.println( withdrawMoney(1000,500) );

System.out.println( withdrawMoney(1000,2000) );

}

public double withdrawMoney(double balance , double amount){

assert balance >= amount;

return balance – amount;

}

}

In above given example, main method calls withdrawMoney method with balance and amount as arguments. The withdrawMoney method has a assert statement that checks whether the balance is grater than or equal to amount to be withdrawn. In first call the method will execute without any exception, but in second call it AssertionError is thrown if the assertion is enabled at runtime.

Enable/Disable Assertions

By default assertion are not enabled, but compiler complains if assert is used as an identifier or label. The following command will compile AssertionDemo with assertion enabled.

javac –source 1.4 AssertionDemo.java

The resulting AssertionDemo class file will contain assertion code.

By default assertion are disabled in Java runtime environment. The argument –eanbleassertion or –ea will enables assertion, while –disableassertion or –da will disable assertions at runtime.

The following command will run AssertionDemo with assertion enabled.

Java –ea AssertionDemo

or

Java –enableassertion AssertionDemo

Second form of Assertion

The second form of assertion takes another expression as an argument.

The syntax is,

assert expression1 : expression2;

where expression1 is the condition and must evaluate to true at runtime.

This statement is equivalent to

assert expression1 : throw new AssertionError(expression2);

Note: AssertionError is unchecked exception, because it is inherited from Error class.

Here, expression2 must evaluate to some value.

By default AssertionError doesn’t provide useful message so this form can be helpful to display some informative message to the user.
---------------------------------------------------------
links

http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/guide/lang/assert.html

---------------------------------------------------------
1. How do I get the assert statement to work?
2. How do I get line numbers?
3. How do I get soft tabs?
4. How do I run Javadoc?
5. How do I see the javadoc for Sun-supplied classes?
6. Why are my JUnit results not showing up?
7. How do I create a test suite?
8. In JUnit, what's the difference between a "failure" and an "error"?
9. Why does Source->Format really mess up my formatting?
10. How do I import an existing program into Eclipse?

1. How do I get the assert statement to work?

In Eclipse 3.1, go to Window -> Preferences -> Java -> Compiler and set the Compiler Compliance Level to 1.4 or 5.0. Also check Use Default compliance settings. This tells the compiler to recognize and allow assert statements, but does not enable them.

In Eclipse 3.0 (Java 1.4), the settings are a little fussier. Go to Window -> Preferences -> Java -> Compiler -> Compliance and Classfiles and set:

Compiler Compliance Level: to 1.4
Use default compliance settings to unchecked
Generated .class files compatibility: to 1.4
Source compatibility: to 1.4
Disallow identifiers called 'assert': to Error
Compiler Compliance Level to 1.4


To enable (make active) assert statements, you must set a flag to the compiler. Go to Run -> Run... -> Arguments, and in the box labeled VM arguments:, enter either -enableassertions or just -ea. Accept the changes and close the dialog.

To get Javadoc to recognize the assert statement, see How do I run Javadoc?

2. How do I get line numbers?

Go to Window -> Preferences -> General -> Editors -> All Text Editors and check Show line numbers.

3. How do I get soft tabs?

To get soft tabs (tabs replaced by spaces) as you type, go to Window -> Preferences -> Java -> Code style-> Formatter and select the profile Java Conventions [built-in]. This should be set correctly to give soft tabs.

You can create your own profile by clicking Show...; for soft tabs, go to Indentation uncheck Use tab characters. After making your changes, you will be prompted for a name for your new profile.

4. How do I run Javadoc?

1. In the Package Explorer window, choose the package or file for which you want to generate documentation.
2. Choose File -> Export... -> Javadoc -> Next>
1. If the dialog box displays the message The Javadoc command does not exist, then you need to click the Configure... button and locate javadoc.exe. You already have this file--it is probably in YourJavaDirectory/jdk1.5.0/bin/.
3. Select the project, and the destination for the Javadoc files. Normally, you should only generate documentation for public fields and methods.
4. If you have no assert statements, you can click Finish at this point.
5. Click Next >.
6. Click Next > again.
7. Check JRE 1.4 source compatibility (otherwise your assert statements will be treated as errors). [See also How do I get the assert statement to work?]
8. Click Finish.

5. How do I see the javadoc for Sun-supplied classes?

If you hover (don't click) your mouse over the name of a method, you should see a simplified Javadoc explanation. If this doesn't work for Sun-supplied methods, then you don't have the source code installed. Here's how to install the source code:

1. Go to http://java.sun.com/j2se/1.5.0/download.jsp and choose to download the JDK 5.0 Source Code (I don't know what SCSL and JRL are, but SCSL worked for me).
2. For JDK 5.0, select Download(SCSL source) .
3. Register. This is relatively painless, especially if you either ignore or enjoy reading license agreements.
4. Download JDK (SCSL) 5.0 (1.5.0). This will give you a file jdk-1_5_0-src.scsl.zip. You do not need to unzip this file; Eclipse likes it the way it is.
5. In Eclipse, go to Projects -> Properties -> Java Build Path -> Libraries and expand JRE System Library [jre 1.5.0], then rt.jar. Select Source attachment and click Edit....
6. Select the above zip file.
7. Finish by exiting the dialog boxes.

6. Why are my JUnit results not showing up?

Maybe it's because all your tests succeeded. For more satisfying results, go to Window -> Preferences -> Java -> JUnit and uncheck Show the JUnit results view only when an error or failure occurs.

7. How do I create a test suite?

Go to File -> New -> Other... -> Java -> JUnit -> TestSuite, and click Next>. Select all the classes, and click Finish.

You can run this test suite the same way you run other JUnit tests.

8. In JUnit, what's the difference between a "failure" and an "error"?

A failure is when one of your assertions fails--that is, your program does something wrong, and your JUnit test notices and reports the fact. An error is when some other Exception occurs--one you haven't tested for and didn't expect, such as a NullPointerException or an ArrayIndexOutOfBoundsException.

9. Why does Source->Format really mess up my formatting?

You have unmatched brackets, braces, or parentheses, and the code reformatter is doing the best it can. Find the syntax error (somewhere near the beginning of the messed up formatting), fix it, and reformat.

10. How do I import an existing program into Eclipse?

Here are two ways that work. First,
1. In your workspace folder, create a new folder, and put your files into that folder.
2. Ask Eclipse to create a new project (File -> New -> Project...) and, for the name of the project, type in the exact name of your new folder.
3. Click Finish.
The second way is very similar:
1. Ask Eclipse to create a new project (File -> New -> Project...) with any suitable name.
2. Copy your files into the new folder.
3. In Eclipse's Package Explorer pane, right-click on the new project and choose Refresh from the pull-down menu.


---------------------------------------------------------

package com;

public class AssertTest {

/**
* @param args
*/

public boolean myErrorDisplay(){
System.out.println("here error");
return false;
}
public static void main(String[] args) {
// The following assert statement will stop execution
// with a message if assertions are turned on.

assert 1<10; assert true; assert 1>10 : new AssertTest().myErrorDisplay();
assert 1<10;
assert true;
// The following statement will only be printed if
// assertions are turned off because assertions
// were not allowed at run time by the -ea parameter.
System.out.println("Assertions are not active.");


}

}

Anonymous and Inner Class - example

an example of a simple anonymous class


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

interface Ball {
void hit();
}
}

and

-------------------------------------------------------
package com;

public class AnuClass {

/**
* @param args
*/


public static void myanmethod(){

Ball b = new Ball(){
public void hit() {
System.out.println("You hit it!");
}
};
b.hit();
}

interface Ball {
void hit();
}

public static void main(String[] args) {
AnuClass.myanmethod();




}
}
-------------------------------------------------------


Access inner class from outside


public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
outer.new Inner().hello();
}
}
class Outer {
public class Inner {
public void hello(){
System.out.println("Hello from Inner()");
}
}
}


------------------------------------------------------

Access inner class from outside


public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
outer.new Inner().hello();
}
}
class Outer {
public class Inner {
public void hello(){
System.out.println("Hello from Inner()");
}
}
}


--------------------------------------------------------

package com;


public class InOutClass {

/**
* @param args
*/
public static void main(String[] args) {
Outer outer = new Outer();
outer.new Inner().hello();

new Thread(new Thread(){
int i=0;
public void run() {
try {
while (i<10) {
sleep(1000); System.out.print("1");
i++;
}
}
catch(InterruptedException ex) {}
}
}).start();

// second option

Thread t = new Thread(new Thread(){
public void run() {
int i=0;
try {
while (i<10) {
sleep(1000); System.out.print("2");
i++;
}
}
catch(InterruptedException ex) {}
}
});
t.start();

new Thread(new Runnable() {
public void run() {
int i=0;
while (i<10) { //sleep(1000); //sleep is not a method of Runnable Interface,its in Thread class
System.out.print("3");
}
}
}).start();

}


}

class Outer {
public class Inner {
public void hello(){
System.out.println("Hello from Inner()");
}
}
}

Comparable,Comparator - sample

package com;

import java.io.Serializable;
import java.util.Comparator;

@SuppressWarnings("serial")
public class Emp implements Comparable, Comparator , Serializable {

private int empId;
private String name;
private int age;

/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/


@Override
public int compareTo(Emp arg0) {
if (!(arg0 instanceof Emp))
throw new ClassCastException("A Person object expected.");

return this.getName().compareTo(arg0.getName()) ;
}



public Emp(int empId, String name, int age) {
this.empId = empId;
this.name = name;
this.age = age;
}

public int getEmpId() {
return empId;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

@Override
public int compare(Emp arg0, Emp arg1) {

return arg0.compareTo(arg1);

}

public static Comparator> nameComparator 
                          = new Comparator>() { 
public int compare(Emp emp1, Emp emp2) {
String name1 = emp1.getName().toUpperCase();
String name2 = emp2.getName().toUpperCase();
//ascending order
return name1.compareTo(name2);
 //descending order
//return name2.compareTo(name1);
	    }
 
	};

}
---------------------------------------------------
package com;

import java.util.ArrayList;
import java.util.List;

public class Util {

public static List getEmployees() {

List col = new ArrayList();

col.add(new Emp(5, "Frank", 28));
col.add(new Emp(1, "Jorge", 19));
col.add(new Emp(6, "Bill", 34));
col.add(new Emp(3, "Michel", 10));
col.add(new Emp(7, "Simpson", 8));
col.add(new Emp(4, "Clerk",16 ));
col.add(new Emp(8, "Lee", 40));
col.add(new Emp(2, "Mark", 30));

return col;
}

}
------------------------------------------

package com;

import java.util.Collections;
import java.util.List;

public class TestEmployeeSort {

/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {

List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll);

//Arrays.sort(coll , Emp.nameComparator);
printList(coll);
}

private static void printList(List list) {
System.out.println("EmpId\tName\tAge");
for (Emp e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}

}
--------------------------------------

Shallow Copy and Deep CopyTest in Cloning

/*
Java provides a mechanism for creating copies of objects called cloning. There are two ways to make a copy of an object called shallow copy and deep copy.
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 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. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.
Java supports shallow and deep copy with the Cloneable interface to create copies of objects. To make a clone of a Java object, you declare that an object implements Cloneable, and then provide an override of the clone method of the standard Java Object base class. Implementing Cloneable tells the java compiler that your object is Cloneable. The cloning is actually done by the clone method.*/


package com.shallow;

class Person implements Cloneable {
//Lower-level object
private Car car;

private String name;

public Car getCar() {
return car;
}

public String getName() {
return name;
}

public void setName(String s) {
name = s;
}

public Person(String s, String t) {
name = s;
car = new Car(t);
}

public Object clone() {
//shallow copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}

class Car {

private String name;

public String getName() {
return name;
}

public void setName(String s) {
name = s;
}

public Car(String s) {
name = s;
}
}

public class ShallowCopyTest {

/**
* @param args
*/
public static void main(String[] args) {
//Original Object
Person p = new Person("Person-A", "Civic");
System.out.println("Original (orginal values): " + p.getName() + " - "
+ p.getCar().getName());

//Clone as a shallow copy
Person q = (Person) p.clone();

System.out.println("Clone (before change): " + q.getName() + " - "
+ q.getCar().getName());

//change the primitive member
q.setName("Person-B");

//change the lower-level object
q.getCar().setName("Accord");

System.out.println("Clone (after change): " + q.getName() + " - "
+ q.getCar().getName());

System.out.println("Original (after clone is modified): " + p.getName()
+ " - " + p.getCar().getName());

}

}
--------------------------------------------------
package com.deep;

class Person implements Cloneable {
//Lower-level object
private Car car;

private String name;

public Car getCar() {
return car;
}

public String getName() {
return name;
}

public void setName(String s) {
name = s;
}

public Person(String s, String t) {
name = s;
car = new Car(t);
}

public Object clone() {
/*//Deep copy
Person p = new Person(name, car.getName());

return p;*/
try {
Person copy = (Person)super.clone();
copy.car = (Car)car.clone();
return copy;
} catch (CloneNotSupportedException e) {
throw new Error("This should not occur since we implement Cloneable");
}


}
}

class Car implements Cloneable{

private String name;

public String getName() {
return name;
}

public void setName(String s) {
name = s;
}

public Car(String s) {
name = s;
}

@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}

public class DeepCopyTest {

public static void main(String[] args) {
//Original Object
Person p = new Person("Person-A", "Civic");
System.out.println("Original (orginal values): " + p.getName() + " - "
+ p.getCar().getName());

//Clone as a shallow copy
Person q = (Person) p.clone();

System.out.println("Clone (before change): " + q.getName() + " - "
+ q.getCar().getName());

//change the primitive member
q.setName("Person-B");

//change the lower-level object
q.getCar().setName("Accord");

System.out.println("Clone (after change): " + q.getName() + " - "
+ q.getCar().getName());

System.out.println("Original (after clone is modified): " + p.getName()
+ " - " + p.getCar().getName());

}
}
---------------------------------

//from web site

Shallow Copy Test


class Person implements Cloneable {
//Lower-level object
private Car car;

private String name;

public Car getCar() {
return car;
}

public String getName() {
return name;
}

public void setName(String s) {
name = s;
}

public Person(String s, String t) {
name = s;
car = new Car(t);
}

public Object clone() {
//shallow copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}

class Car {

private String name;

public String getName() {
return name;
}

public void setName(String s) {
name = s;
}

public Car(String s) {
name = s;
}
}

public class ShallowCopyTest {

public static void main(String[] args) {
//Original Object
Person p = new Person("Person-A", "Civic");
System.out.println("Original (orginal values): " + p.getName() + " - "
+ p.getCar().getName());

//Clone as a shallow copy
Person q = (Person) p.clone();

System.out.println("Clone (before change): " + q.getName() + " - "
+ q.getCar().getName());

//change the primitive member
q.setName("Person-B");

//change the lower-level object
q.getCar().setName("Accord");

System.out.println("Clone (after change): " + q.getName() + " - "
+ q.getCar().getName());

System.out.println("Original (after clone is modified): " + p.getName()
+ " - " + p.getCar().getName());

}
}

//
in shallow copy , the obj having ref var of any other class, then if u try to change the value of that ref var value in cloned obj of original obj, we can find changed value in ref var.but other instance var values will remain same.

it means , in shallow cpoy,
change in clone obj may effect the ref variable which r there in the original obj.
out put
--------
Original (orginal values): Person-A - Civic
Clone (before change): Person-A - Civic
Clone (after change): Person-B - Accord
Original (after clone is modified): Person-A - Accord


//----------------------------------------------------------------


Deep Copy Test

/*
Correct Output:
Original (orginal values): Person-A - Civic
Clone (before change): Person-A - Civic
Clone (after change): Person-B - Accord
Original (after clone is modified): Person-A - Civic

*/

/*
Software Architecture Design Patterns in Java
by Partha Kuchana

Auerbach Publications

*/



class Person implements Cloneable {
//Lower-level object
private Car car;

private String name;

public Car getCar() {
return car;
}

public String getName() {
return name;
}

public void setName(String s) {
name = s;
}

public Person(String s, String t) {
name = s;
car = new Car(t);
}

public Object clone() {
//Deep copy
Person p = new Person(name, car.getName());
return p;
}
}

class Car {

private String name;

public String getName() {
return name;
}

public void setName(String s) {
name = s;
}

public Car(String s) {
name = s;
}
}

public class DeepCopyTest {

public static void main(String[] args) {
//Original Object
Person p = new Person("Person-A", "Civic");
System.out.println("Original (orginal values): " + p.getName() + " - "
+ p.getCar().getName());

//Clone as a shallow copy
Person q = (Person) p.clone();

System.out.println("Clone (before change): " + q.getName() + " - "
+ q.getCar().getName());

//change the primitive member
q.setName("Person-B");

//change the lower-level object
q.getCar().setName("Accord");

System.out.println("Clone (after change): " + q.getName() + " - "
+ q.getCar().getName());

System.out.println("Original (after clone is modified): " + p.getName()
+ " - " + p.getCar().getName());

}
}

Sunday, July 18, 2010

Performance Tuning of Java Applications

Ever since the first version of Java Technology hit the streets, performance has been an important issue for Java developers. Java has improved dramatically and continually but, performance tuning is very essential to get the best results, especially when we think of J2EE applications.



Sponsored Links


Introduction:

Java Performance Tuning (abbreviated as JPT), 2nd edition provides a comprehensive guide to eliminate all the types of performance problems. By considering real-life examples JPT shows how to get rid off all the types of performances problems. For example JPT shows tricks such as how to minimize object creation and replacing strings with arrays can really pay off in improving code performance.

Few of important fundamentals and guidelines included in Java Performance Tuning are….

* Tuning tips for object creation.
* Tuning in JDBC.
* Web services performance tips.
* Tuning in EJB.
* Tuning in J2EE.
* Tuning in JMS.
* Tuning in RMI.

Guidelines for tuning java code without destroying program’s skeleton is efficiently presented in second edition of Java Performance Tuning. It includes how to use threads effectively, how to optimize the use of strings, minimizing the creation of objects in program, avoiding bottleneck operation by including all the important fundamentals of Software Engineering to re-pioneer the code, issues of speed of Servlets and JSPs etc. That provides very crucial guidelines in performance tuning for java developers.

Tuning Tips for Object Creation:

Object Creation is one of the most basic and essential thing while developing a Java Application, as such; object defines the physical reality of class. Pay proper attention while declaring class’ methods and variables because careless work carried out at this stage, can cost you in terms of speed and performance because variables and methods unwontedly declared and initialize can create overhead in overall speed. Object should always be created early when there is spare time in the application, object once created should be in hold position until it is required. Care should be taken while defining methods that can accept the reusable objects to be filled with the data rather than methods that return objects holding that data, immutable objects can also be used here. Object should be created only when class logically needs. Constructor of class should always be simple. Methods that alter objects directly should always be preferred. Use classes that handle primitive data types rather than wrapping the primitive data types.

Performance Tuning in JDBC:

Java Database Connectivity (JDBC) is mainly used in most of the Java application. To keep trace on performance tuning in JDBC becomes very crucial and prime issue when Java developer realizes that most of the processing time should not be wasted behind data processing over the network.

Here are few of the tuning tips for JDBC that can improve the over all performance in Java application.

* SQL statements should be tuned to minimize the data that is return from the database.
* Use of prepared statements and parameterized SQL statements can speed up the over all process in data processing.
* Transaction conflicts should always be avoided.
* Usage of stored procedures, connection pooling, selection of fastest JDBC driver should be encouraged.
* Any of the open resources that is not in use in Java application can keep processor engaged unwontedly, any of the resource that is open and not required to perform any of database activity should be closed like Connections, Statements, ResultSet etc.

Web Services performance tips:

Because of Java’s outstanding performance in web services there are few of the performance tips that are to be considered while developing a web service application. Here are few of the tips given for improving the web services performance.

* Avoid using XML messaging, this helps to achieve fine-grained RPC.
* Frequency of the messaging should be taken into consideration with the replication of the data as necessary.
* Always try to retrieve data during off-hours this helps in course gained transactions.
* Overall system performance should never be neglected and optimized until we know where the bottlenecks are present.
* Asynchronous messaging model should always be taken into account when transport is slow or / and unreliable, or when processing is complex and long running.

Tips for Quality of services for Web Services

* The main requirements in quality of service for web services are:
o Availability and accessibility.
o Integrity and reliability. This ensures that weather program will crash or not while it is running, if so, how often can it crash.
o Number of simultaneous request that can be made to application by the user i.e. “throughput” and what will be the response time to process this request by application i.e. “latency”.
o Security issues.
* HTTP is a best-effort delivery service as far as web services issue is concerned. The main reason behind this is that request could simply be dropped. Messaging in web services should always be Asynchronous because Asynchronous messaging can improve throughput no matter at the cost of latency.
* DOM based parsers are slower than SAX based ones.
* Requests results should be cached whenever it is possible.
* Extreme care should be taken to make sure that resources are not locked for long periods of time to avoid serious scalability problems.
* Other factor that affects web service performance are:
o Response time of web server.
o Availability of web server.
o Execution time of web application.
o Backend database.

Scaling web services Tips

Use of faster communication protocol, like plain socket, should always be preferred. Whenever there is requirement of sending large number of documents over the network, basic load-balancing scheme should be achieved, all the documents to be sent should have different URL hosts i.e. binding addresses. For scalability of server better and speedy hardware should be preferred though there is limitation of scalability of server is that most application performance does not scale linearly with increases in the hardware power. Most of the times in web related services cluster of more than one server is used.

Performance Tuning tips for EJB:

While developing an EJB application if EJB services for an object is not required than plain Java object should be replaced in place of EJB object. Multiple remote method calls should be changed into one remote method call with all the data combined into a parameter object to enhance the overall process. There should be proper tuning in EJB Server thread count; Use Stateless session beans pool size to minimize the creation and destruction of the beans. When multiple EJB remote calls have to be changed into one session bean remote call and several local calls(SessionFacade), wrap multiple entity beans in a session bean. Transactional time-out should be set previously. Use HttpSession object rather than Stateful session bean to maintain client state. Bulk updating should be used to reduce the overall database calls to fetch and retrieving the data. When dealing with large amounts of data such as searching large database JDBC should be directly used rather than using entity beans.

J2EE Performance tuning tips:

Here few of the important tuning tips for J2EE in points.

* Entity beans from session beans should always be accessed.
* When you no longer need to use session call HttpSession.invalidate() to clean up a session.
* Save resources by turning off automatic session creation using < % @page session=”false” % > for web pages that don’t require session tracking.
* Use compile time directive < % @include file=”copyleft.html” % > where possible.
* Whenever beans are co-located in the same JVM, use local entity beans.
* Proprietary stubs can be used for caching and batching data.
* To generate unique primary keys dedicated remote object should be used.
* Whenever possible use cache tagging.
* User JDBC directly instead of using an entity bean only for data access.

Tuning tips for JMS:

For developing an efficient JMS application transient variables should be used to reduce serialization overheads. For receiving messages asynchronously implement MessageListener. To avoid persistency overhead choose non-durable (NON_PERSISTENT) messages wherever appropriate. It is practically efficient to use DUPS_OK_ACKNOWLEDGE AND AUTO_ACKNOWLEDGE than CLIENT_ACKNOWLEDGE as far as issue of performance is concerned. Separate transactional sessions and non-transactional sessions for transactional and non-transactional messages should be used separately. Because of the fact that “ a higher redelivery delay and lower redelivery limit reduces the overhead” remember to tune the destination parameters. Open java resources can claim for more system resources never forget to close all the resources whenever they are not in use. The last point to be kept while developing a JMS application is that consumer should always start before we start the producer so that the initial messages do not need to be queued up.



Sponsored Links


RMI tuning performance tips:

To improve the performance in RMI application always consider altering the Tcp WindowSize parameter. To measure the bandwidth of network netp erf should be used. By setting the properties sun.rmi.dgc.client.gcInterval and sun.rmi.dgc.server.gcInterval RMI garbage collection should be configured in a proper manner. Since sending the object over network may consume much of the time in a big application sending groups of objects together rather than one object at a time is advisable. To speed up the transfers, implement Externalize interface. To handle special cases such as singleton or reusable objects use special codes. To improve overall development quality never try to add the extra complications once the performance target have been met
.

==, .equals(), compareTo(), and compare()

Equality comparison: One way for primitives, Four ways for objects
Comparison Primitives Objects
a == b, a != b Equal values Compares references, not values. The use of == with object references is generally limited to the following:

* Comparing to see if a reference is null.
* Comparing two enum values. This works because there is only one object for each enum constant.
* You want to know if two references are to the same object

a.equals(b) N/A Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.

It turns out that defining equals() isn't trivial; in fact it's moderately hard to get it right, especially in the case of subclasses. The best treatment of the issues is in Horstmann's Core Java Vol 1. [TODO: Add explanation and example]
a.compareTo(b) N/A Comparable interface. Compares values and returns an int which tells if the values compare less than, equal, or greater than. If your class objects have a natural order, implement the Comparable interface and define this method. All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).
compare(a, b) N/A Comparator interface. Compares values of two objects. This is implemented as part of the Comparator interface, and the typical use is to define one or more small utility classes that implement this, to pass to methods such as sort() or for use by sorting data structures such as TreeMap and TreeSet. You might want to create a Comparator object for the following.

* Multiple comparisions. To provide several different ways to sort somthing. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the sort() method.
* System class. To provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length.
* Strategy pattern. To implement a Strategey pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.

If your class objects have one natural sorting order, you may not need this.
Comparing Object references with the == and != Operators

The two operators that can be used with object references are comparing for equality (==) and inequality (!=). These operators compare two values to see if they refer to the same object. Although this comparison is very fast, it is often not what you want.

Usually you want to know if the objects have the same value, and not whether two objects are a reference to the same object. For example,

if (name == "Mickey Mouse") // Legal, but ALMOST SURELY WRONG

This is true only if name is a reference to the same object that "Mickey Mouse" refers to. This will be false if the String in name was read from input or computed (by putting strings together or taking the substring), even though name really does have exactly those characters in it.

Many classes (eg, String) define the equals() method to compare the values of objects.
Comparing Object values with the equals() Method

Use the equals() method to compare object values. The equals() method returns a boolean value. The previous example can be fixed by writing:

if (name.equals("Mickey Mouse")) // Compares values, not refererences.

Because the equals() method makes a == test first, it can be fairly fast when the objects are identical. It only compares the values if the two references are not identical.
Other comparisons - Comparable interface

The equals method and == and != operators test for equality/inequality, but do not provide a way to test for relative values. Some classes (eg, String and other classes with a natural ordering) implement the Comparable interface, which defines a compareTo method. You will want to implement Comparable in your class if you want to use it with Collections.sort() or Arrays.sort() methods.
Defining a Comparator object

As described in the table above on compare(), you can create Comparators to sort any arbitrary way for any class. For example, the String class defines the CASE_INSENSITIVE_ORDER comparator.
If you override equals, you should also override hashCode()

Overriding hashCode(). The hashCode() method of a class is used for hashing in library data structures such as HashSet and HashMap. If you override equals(), you should override hashCode() or your class will not work correctly in these (and some other) data structures.
Shouldn't .equals and .compareTo produce same result?

The general advice is that if a.equals(b) is true, then a.compareTo(b) == 0 should also be true. Curiously, BigDecimal violates this. Look at the Java API documentation for an explanation of the difference. This seems wrong, although their implementation has some plausibiliby.
Other comparison methods

String has the specialized equalsIgnoreCase() and compareToIgnoreCase(). String also supplies the constant String.CASE_INSENSITIVE_ORDER Comparator.
The === operator (Doesn't exist - yet?)

Comparing objects is somewhat awkward, so a === operator has been proposed. One proposal is that
a === b would be the same as ((a == b) || ((a != null) && a.equals(b)))
Common Errors

Using == instead of equals() with Objects
When you want to compare objects, you need to know whether you should use == to see if they are the same object, or equals() to see if they may be a different object, but have the same value. This kind of error can be very hard to find.