Sunday, September 6, 2009

What is user-defined exception in java ?

Answer : User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inherite the Exception class as shown below. Using this class we can throw new exceptions.

Java Example :

public class noFundException extends Exception {
}

Throw an exception using a throw statement:

public class Fund {

...
public Object getFunds() throws noFundException {

if (Empty()) throw new noFundException();
...

}
}

User-defined exceptions should usually be checked.

How to Make a Java Class Immutable ?

Making a class immutable.
Immutability must be familiar to every one when we talk about String & StringBuffer classes in java. Strings are considered immutable because the values contained in the reference variable cannot be changed. Whereas String Buffer is considered mutable because the value in a string buffer can be changed (i.e. mutable).

However I always thought how to make our user defined classes as immutable though I am unaware as to why any one would need this.

The reason perhaps might be clear once we have a look at the code.

Now in order to make a class immutable we must restrict changing the state of the class object by any means. This in turn means avoiding an assignment to a variable. We can achieve this through a final modifier. To further restrict the access we can use a private access modifier. Above do not provide any method where we modify the instance variables.

Still done? No. How if some body creates a sub class from our up till now immutable class? Yes here lies the problem. The new subclass can contain methods, which over ride our base class (immutable class) methods. Here he can change the variable values.

Hence make the methods in the class also final. Or a better approach. Make the immutable class itself final. Hence cannot make any sub classes, so no question of over ridding.

The following code gives a way to make the class immutable.

/*
Code Developed Satya
This code demonstrates the way to make a class immutable
*/

// The immutable class which is made final
final class MyImmutableClass
{
// instance var are made private & final to restrict the access

private final int count;
private final double value;

// Constructor where we can provide the constant value
public MyImmutableClass(int paramCount,double paramValue)
{
count = paramCount;
value = paramValue;
}

// provide only methods which return the instance var
// & not change the values

public int getCount()
{
return count;
}

public double getValue()
{
return value;
}
}

// class TestImmutable
public class TestImmutable
{
public static void main(String[] args)
{
MyImmutableClass obj1 = new MyImmutableClass(3,5);

System.out.println(obj1.getCount());
System.out.println(obj1.getValue());

// there is no way to change the values of count & value-
// no method to call besides getXX, no subclassing, no public access to var -> Immutable
}
}

The possible use of immutable classes would be a class containing a price list represented for a set of products.
Otherwise also this represents a good design.

garbage collection

Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed. In Java, it is good idea to explicitly assign null into a variable when no more in use.

what are the different ways to create objects in Java?

There are five different ways (I really don’t know is there a sixth way to do this) to create objects in java:

1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.

MyObject object = new MyObject();

2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

3. Using clone()
The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();

4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();Now you know how to create an object. But its advised to create objects only when it is necessary to do

5. Using classloader

like this.getClass().getClassLoader().loadClass(”com.amar.myobject”).newInstance();

How to iterate Map in java?

No direct iteration over Maps -- Get Set of keys or key-value pairs from Map to iterate.
Maps do not provide an iterator() method as do Lists and Sets. A Set of either keys (keySet()) or key-value Map.Entry elements (entrySet()) can be obtained from the Map, and one can iterate over that.

Example:

public static void dumpMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}

Sunday, August 30, 2009

for Hibernate tutorials

Please go through this url

http://www.techfaq360.com/tutorial/hibernate_setup.jsp

Advantage of Hibernate over JDBC

Advantage are
1) Hibernate is data base independent, same code will work for all data bases like ORACLE,MySQL ,SQLServer etc.
In case of JDBC query must be data base specific.

2) As Hibernate is set of Objects , you don't need to learn SQL language.
You can treat TABLE as a Object .
In case of JDBC you need to learn SQL.

3) Don't need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.
In case of JDBC you need to tune your queries.

4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache .

Tuesday, February 17, 2009

Java class loaders-:

Java Class loaders are Two types:-
1.Static Class Loaders 2.Dynamic class loaders
static class loaders:: Classes are statically loaded with Java’s
“new” operator.
Dynamic class loaders::
Dynamic loading is a technique for programmatically invoking the functions of a
class loader at run time. Let us look at how to load classes dynamically.

Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that
is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with
the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the
classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one
class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at
non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of
primordial class loader. Let us look at the class loaders created by the JVM

Bootstrap
(primordial)
Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path
system property, typically loads rt.jar and i18n.jar)

Extensions
Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system
property – usually lib/ext directory of the JRE)

System
Loads classes from system classpath (as defined by the java.class.path property, which
is set by the CLASSPATH environment variable or –classpath or –cp command line
options)