INTEROPY

Ranjan Kumar

Prototype Pattern – GOF

leave a comment »

Intent of this pattern is to specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Structure

Prototype Pattern

Participants

  • Prototype: declares an interface for cloning itself.
  • ConcretePrototype: implements an operation for cloning itself.
  • Client: creates a new object by asking a prototype to clone itself.

Example

Prototype Class:

/**
 * Prototype Class
 */
abstract class PrototypeFactory implements Cloneable {
    public PrototypeFactory clone() throws CloneNotSupportedException {
        // call Object.clone()
        PrototypeFactory copy = (PrototypeFactory) super.clone();
        //In an actual implementation of this pattern you might now change references to
        //the expensive to produce parts from the copies that are held inside the prototype.
        return copy;
    }

    abstract void prototypeFactory(int x);

    abstract void printValue();
}

Concrete Prototypes to clone

/**
 * Concrete Prototypes to clone
 */
class PrototypeImpl extends PrototypeFactory {
    int x;

    public PrototypeImpl(int x) {
        this.x = x;
    }

    @Override
    void prototypeFactory(int x) {
        this.x = x;
    }

    public void printValue() {
        System.out.println("Value :" + x);
    }
}

Client Class

/**
 * Client Class
 */
public class PrototypeExample {

    private PrototypeFactory example; // Could have been a private Cloneable example.

    public PrototypeExample(PrototypeFactory example) {
        this.example = example;
    }

    public PrototypeFactory makeCopy() throws CloneNotSupportedException {
        return this.example.clone();
    }

    public static void main(String args[]) {
        try {
            PrototypeFactory tempExample = null;
            int num = 1000;
            PrototypeFactory prot = new PrototypeImpl(1000);
            PrototypeExample cm = new PrototypeExample(prot);
            for (int i = 0; i < 10; i++) {
                tempExample = cm.makeCopy();
                tempExample.prototypeFactory(i * num);
                tempExample.printValue();
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

Consequences

Prototype has many of the same consequences that Abstract Factory and Builder have: It hides the concrete product classes from the client, thereby reducing the number of names clients know about. Moreover, these patterns let a client work with application-specific classes without modification.

Additional benefits:

  • Adding and removing products at run-time.
  • Specifying new objects by varying values.
  • Specifying new objects by varying structure.
  • Reduced subclassing.
  • Configuring an application with classes dynamically.

References

Written by Ranjan Kumar

February 6, 2010 at 2:39 pm

Builder Pattern – GOF

leave a comment »

The idea of this pattern is to separate the construction of a complex object from its representation so that the same construction process can create different representations.

Class Diagram

Builder Pattern

Builder: Abstract interface for creating objects (product).
Concrete Builder: Provide implementation for Builder. Construct and assemble parts to build the objects.
Director: The Director class is responsible for managing the correct sequence of object creation. It receives a Concrete Builder as a parameter and executes the necessary operations on it.
Product: The final object that will be created by the Director using Builder.

Example

Product:

/** "Product" */
class Pizza {
	private String dough = "";
	private String sauce = "";
	private String topping = "";

	public void setDough(String dough) {
		this.dough = dough;
	}

	public void setSauce(String sauce) {
		this.sauce = sauce;
	}

	public void setTopping(String topping) {
		this.topping = topping;
	}
}

Abstract Builder:

/** "Abstract Builder" */
abstract class PizzaBuilder {
	protected Pizza pizza;

	public Pizza getPizza() {
		return pizza;
	}

	public void createNewPizzaProduct() {
		pizza = new Pizza();
	}

	public abstract void buildDough();

	public abstract void buildSauce();

	public abstract void buildTopping();
}

ConcreteBuilder:

/** "ConcreteBuilder" */
class HawaiianPizzaBuilder extends PizzaBuilder {
	public void buildDough() {
		pizza.setDough("cross");
	}

	public void buildSauce() {
		pizza.setSauce("mild");
	}

	public void buildTopping() {
		pizza.setTopping("ham+pineapple");
	}
}

/** "ConcreteBuilder" */
class SpicyPizzaBuilder extends PizzaBuilder {
	public void buildDough() {
		pizza.setDough("pan baked");
	}

	public void buildSauce() {
		pizza.setSauce("hot");
	}

	public void buildTopping() {
		pizza.setTopping("pepperoni+salami");
	}
}

Director:

/** "Director" */
class Cook {
	private PizzaBuilder pizzaBuilder;

	public void setPizzaBuilder(PizzaBuilder pb) {
		pizzaBuilder = pb;
	}

	public Pizza getPizza() {
		return pizzaBuilder.getPizza();
	}

	public void constructPizza() {
		pizzaBuilder.createNewPizzaProduct();
		pizzaBuilder.buildDough();
		pizzaBuilder.buildSauce();
		pizzaBuilder.buildTopping();
	}
}

Example:

/** A given type of pizza being constructed. */
public class BuilderExample {
	public static void main(String[] args) {
		Cook cook = new Cook();
		PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
		PizzaBuilder spicyPizzaBuilder = new SpicyPizzaBuilder();

		cook.setPizzaBuilder(hawaiianPizzaBuilder);
		cook.constructPizza();

		Pizza pizza = cook.getPizza();
	}
}

What is the difference between Builder and Factory pattern?

  • The factory pattern defers the choice of what concrete type of object to make until run time. E.g. going to a restaurant to order the special of the day. The waiter is the interface to the factory that takes the abstract generic message “Get me the special of the day!” and returns the concrete product (i.e Liver souffle or Chicken caramel)
  • The builder pattern encapsulates the logic of how to put together a complex object so that the client just requests a configuration and the builder directs the logic of building it. E.g The main contractor (builder) in building a house knows, given a floor plan, knows how to execute the sequence of operations (i,e. by delegating to subcontractors) needed to build the complex object. If that logic was not encapsulated in
    a builder, then the buyers would have to organize the subcontracting themselves (“Dear, shouldn’t we have asked for the foundation to be laid before the roofers showed up?”)
  • The factory is concerned with what is made, the builder with how it is made. Design patterns points out that (page 105) Abstract factory is similar to builder in that it too may construct complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract factor’s emphasis is on families of product objects(either simple or complex). Builder returns the product as
    the final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

Other Points

  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components are built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.

References:

Written by Ranjan Kumar

February 2, 2010 at 3:37 pm

Singleton Pattern – GOF

with one comment

Singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This pattern is useful when we want only one object to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five).

Implementation:

Traditional Simple Way:
This solution is thread-safe without requiring any spacial language construct. But the instance is created as soon as the class is initialized. That might even be long before getInstance() is called. If laziness is not needed or the instance needs to be created early in the application’s execution, this simple solution can be used.

 public class Singleton {
   private static final Singleton INSTANCE = new Singleton();

   // Private constructor prevents instantiation from other classes
   private Singleton() {}

   public static Singleton getInstance() {
      return INSTANCE;
   }
 }

The solution of Bill Pugh:
This solution is also thread-safe without requiring any language specific construct. But this uses “Initialization on demand holder idiom“.

public class Singleton {
   // Private constructor prevents instantiation from other classes
   private Singleton() {}

   /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance()
    * or the first access to SingletonHolder.INSTANCE, not before.
    */
   private static class SingletonHolder {
     private static final Singleton INSTANCE = new Singleton();
   }

   public static Singleton getInstance() {
     return SingletonHolder.INSTANCE;
   }
 }

Consequences:

  • It can be difficult to subclass a Singleton, since this can only work if the
    base Singleton class has not yet been instantiated.
  • You can easily change a Singleton to allow a small number of instances where this is allowable and meaningful.
  • Design Patterns – Java Companion by James W. Cooper (Download Book in pdf format)

Reference:

Written by Ranjan Kumar

February 1, 2010 at 4:42 pm

The Abstract Factory Pattern – GOF

with one comment

The Abstract Factory pattern is one level of abstraction higher than the 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.

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, we can change the implementation from one factory to another.

References:

Note:
Looking for a good example in Java.

Written by Ranjan Kumar

February 1, 2010 at 3:11 pm

The Factory Pattern – GOF

with 2 comments

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.

Example:

Client.java

public class Client {
	public static void main(String [] args) {
		new Client().test();
	}
	public void test() {
		Message message = new Message();
        	message.setMessageType("Synch");
		MessageProcessor messageProcessor = new MessageProcessorFactory().getMessageProcessor(message.getMessageType());
		messageProcessor.process(message);
	}
}

Message.java

public class Message {
	public String messageType;

	public void setMessageType(String msgType) {
		messageType = msgType;
	}

	public String getMessageType() {
		return messageType;
	}
}

MessageProcessor.java

public abstract class MessageProcessor {
	public abstract void process(Message message);
}

SynchMessageProcessor.java

public class SynchMessageProcessor extends MessageProcessor{
		public void process(Message message) {
			System.out.println("Send the message to the Recipient directly and return.");
		}
}

AsynchMessageProcessor.java

public class AsynchMessageProcessor extends MessageProcessor{
		public void process(Message message) {
			System.out.println("Put the message on the queue and return so that it can be processed asynchronously.");
		}
}

MessageProcessorFactory.java

public class MessageProcessorFactory{
	public MessageProcessor getMessageProcessor(String messageType) {
		if (messageType.equals("Synch")){
			return new SynchMessageProcessor();
		} else {
			return new AsynchMessageProcessor();
		}
	}
}

When to Use a Factory Pattern?

  • You should consider using a Factory pattern when
  • A class can’t anticipate which kind of class of objects it must create.
  • A class uses its subclasses to specify which objects it creates.
  • You want to localize the knowledge of which class gets created.

There are several similar variations on the factory pattern to recognize.

  1. The base class is abstract and the pattern must return a complete working class.
  2. The base class contains default methods and is only subclassed for cases where the default methods are insufficient.
  3. Parameters are passed to the factory telling it which of several class types to return. In this case the classes may share the same method names but may do something quite different.

References:

  • Design Patterns – Elements of Reusable Object-Oriented Software by Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides).
  • “Java Design Patterns: A Tutorial” by James W Cooper, published by Addison-Wesley.

Written by Ranjan Kumar

January 30, 2010 at 10:24 pm

Cryptography

leave a comment »

What is Cryptography?
Cryptography is the science of using mathematics to encrypt and decrypt data. Cryptography enables you to store sensitive information or transmit it across insecure networks (like the Internet) so that it cannot be read by anyone except the intended recipient.

Encryption and decryption
Data that can be read and understood without any special measures is called plaintext or cleartext. The method of disguising plaintext in such a way as to hide its substance is called encryption. Encrypting plaintext results in unreadable gibberish called ciphertext. You use encryption to ensure that information is hidden from anyone for whom it is not intended, even those who can see the encrypted data. The process of reverting ciphertext to its original plaintext is called decryption.

Plaintext -> encryption -> ciphertext -> decryption -> plaintext

Cryptanalysis is the science of analyzing and breaking secure communication.

How does cryptography work?
A cryptographic algorithm, or cipher, is a mathematical function used in the encryption and decryption process. A cryptographic algorithm works in combination with a key — a word, number, or phrase — to encrypt the plaintext. The same plaintext encrypts to different ciphertext with different keys. The security of encrypted data is entirely dependent on two things: the strength of the cryptographic algorithm and the secrecy of the key.

Cryptosystem: A cryptographic algorithm, plus all possible keys and all the protocols that make it work comprise a cryptosystem.

Conventional cryptography
Conventional cryptography uses one key for both encryption and decryption. This key is called the secret-key or symmetric-key. The Data Encryption Statndard (DES) is the example of a conventional cryptosystem.

The problem with conventional encryption is key distribution: how you will send the key to the recipient without someone intercepting it?

Public key cryptography
Public key cryptography solved the problem of key distribution.

Public key cryptography is an asymmetric scheme that uses a pair of keys for encryption: a public key, which encrypts data, and a corresponding private, or secret key for decryption. You publish your public key to the world while keeping your private key secret. Anyone with a copy of your public key can then encrypt information that only you can read.

It is computationally not possible to deduce the private key from the public key. Anyone who has a public key can encrypt information but cannot decrypt it. Only the person who has the corresponding private key can decrypt the information.

Keys
A Key is a value which is measured in bits and used by cryptographic algorithm to produce a specific ciphertext.

Larger keys will be cryptographically secure for a longer period of time.
References:
http://www.pgpi.org/doc/pgpintro

Written by Ranjan Kumar

December 1, 2009 at 4:45 pm

Java policytool – Policy File Creation and Management Tool

leave a comment »

A policy file in Java is an ASCII text file and can be edited in a text editor or the graphical Policy Tool Utility polocytool. It can be started from the command prompt like:

C:\Documents and Settings\ranjan>policytool

Following is a very good tutorial on this tool:

policytool – Policy File Creation and Management Tool

Written by Ranjan Kumar

December 1, 2009 at 12:13 pm

Posted in Java / Java EE

Tagged with ,

Exception in thread “main” java.lang.NoClassDefFoundError

leave a comment »

Suppose you are trying to run the simple Java class in the current directory where you have the .class file also. Suppose you have GetProps.class file in C:\Test directory and the command you run is the following:

C:\Test>java GetProps

and you are getting the following exception:

Exception in thread "main" java.lang.NoClassDefFoundError: GetProps
Caused by: java.lang.ClassNotFoundException: GetProps
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: GetProps.  Program will exit.

Then probably the reason is that the current directory in not in classpath environment variable. So add the current directory “.” in the classpath or you run the above command as the following:

C:\Test>java -classpath “.” GetProps

Written by Ranjan Kumar

December 1, 2009 at 11:36 am

Javacc – Java Compiler Compiler

leave a comment »

JavaCC (Java Compiler Compiler) is an open source parser generator for the Java programming language. JavaCC is similar to Yacc in that it generates a parser for a formal grammar provided in EBNF notation, except the output is Java source code.

References:
Javacc – @Wiki
Javacc – Project Home
Yacc – @Wiki

Written by Ranjan Kumar

November 13, 2009 at 5:05 pm

Java SE 6: Top 10 Features

leave a comment »

A very good summary of top 10 features of Java SE 6 by Sang Shin – Sun Microsystems Inc. : Java SE 6: Top 10 Features

Written by Ranjan Kumar

November 10, 2009 at 4:39 pm

Posted in Java / Java EE

Tagged with ,

Secure Coding

leave a comment »

I have found links of some good articles on “Secure Coding” which was the topic of my today’s lecture in FPGDST course of CDAC Mumbai & Banglore.

Here are some important links that I have found:

Guidelines for Secure Coding by Trupti Shiralkar and Brenda Grove, January 2009
(This is a very good article.)

Secure Coding Guidelines Version 2.0 for the Java Programming Language

Secure a Web application, Java-style
Use Java’s multiple-layer security implementation to protect your Web
By Michael Cymerman, JavaWorld.com, 04/28/00

CERT Secure Coding Standards

Secure Coding: Principles & Practices (Book)

http://www.secureprogramming.com/
Recipes for Cryptography, Authentication, Networking, Input Validation and More

Written by Ranjan Kumar

October 6, 2009 at 4:28 pm

OOP in Java

leave a comment »

Reusing Classes
The idea is to use the classes without soiling the existing code. There are two ways, you can do this:

  • Compositions
  • Inheritance

Composition: The new class is composed of objects of existing classes. You are simply reusing the functionality of the code, not its form.

Inheritance: It creates a new class as a type of an existing class. You literally take the form of the existing class and add code to it without modifying the existing class. Compiler does most of the work.

It is important to note that how  cleanly the classes are separated. You don’t even need the source code for the methods in order to reuse the code. At most just import a package. (This is true for both inheritance and composition).

Delegation: Not directly supported in Java.

Composition vs. Inheritance

  • Composition is generally used when you want the features of an existing class inside your new class, but not its interface. That is, you embed an object so that you can use it to implement features in your new class, but the user of your new class sees the interface you have defined for the new class rather than the interface from the embedded object. For this effect, you embed private objects of existing classes inside your new class.
  • Composition is for has-a relationship whereas Inheritance is for is-a relationship.
  • Ask whether you will ever need to upcast from your new class to the base class. If you must upcast, then inheritance is necessary, but if you don’t need to upcast then you should look closely at whether you need inheritance. “Do I need to upcast?” you will have a good tool for deciding between composition and inheritance.

Polymorphism deals with decoupling in terms of types. Inheritance allows the treatment of an object as its own type or its base type. This ability is critical because it allows many types (derived from the same base type) to be treated as if they were one type and a single piece of code to work on all those different types equally.

Polymorphism (also called dynamic binding or late binding or run-time binding).

Read the rest of this entry »

Writing good XML Schema

leave a comment »

I have found out some good articles to go through if you want to write a good XML Schema and follow best practices.

Written by Ranjan Kumar

September 18, 2009 at 12:41 pm

eForm Solutions in the Software Industry and Trends

leave a comment »

I was searching for the currently existing eform (electronic form) solutions in the industry. I found the following major products with their companies.

  1. Cardiff Liquid Office eForms” from Autonomy Cardiff.
  2. PureEdge eForms (now Lotus Forms) from IBM.
  3. Livecycle (eForm for the enterprise) from Adobe.

Read the rest of this entry »

Written by Ranjan Kumar

September 18, 2009 at 12:16 pm

UUID – Universally Unique Identifier

leave a comment »

The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination. Thus, anyone can create a UUID and use it to identify something with reasonable confidence that the identifier will never be unintentionally used by anyone for anything else. (Globally Unique Identifiers (GUIDs) are also related.)

The J2SE 5.0 release of Java provides a class that will produce 128-bit UUIDs, although it only implements version 3 and 4 generation methods, not the original method (due to lack of means to access MAC addresses using pure Java). The API documentation for the java.util.UUID class refers to ISO/IEC 11578:1996.

Open source implementations supporting MAC addresses on several common operating systems are UUID – generate UUIDs (or GUIDs) in Java , Java Uuid Generator (JUG) and ActiveScript.

We have used Java Uuid Generator (JuG) from Safehaus (http://jug.safehaus.org/) in NSDG/SSDG projects. It had the requirement of 2 IDs (CorrelationID and AuditID) to be unique across the gateway constellation. These 2 ids required to be 128 bits(32 hexadecimal bits).

Notes: JUG generates UUIDs according to the IETF UUID draft specification(and further clarified in UUID URN name space IETF draft ) – all 3 ‘official’ types defined by the draft – is fast, portable and Open Source(as well as Free Software ).

Reference:
http://jug.safehaus.org/
http://en.wikipedia.org/wiki/Uuid

Written by Ranjan Kumar

September 15, 2009 at 11:02 am

Design Patterns – GOF

leave a comment »

Christopher Alexander says, “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice”.

Design patterns(Gang of Four) are grouped in the following categories:

  1. Creational patterns
  2. Structural patterns
  3. Behavioral patterns
Purpose Design Pattern Aspect(s) That Can Vary
Creational Factory Method families of product objects
Abstract Factory how a composite object gets created
Builder subclass of object that is instantiated
Prototype class of object that is instantiated
Singleton the sole instance of a class
Structural Adapter interface to an object
Bridge implementation of an object
Composite structure and composition of an object
Decorator responsibilities of an object without subclassing
Facade interface to a subsystem
Flyweight storage costs of objects
Proxy how an object is accessed; its location
Behavioral Chain of Responsibility object that can fulfill a request
Command when and how a request is fulfilled
Interpreter grammar and interpretation of a language
Iterator how an aggregate’s elements are accessed, traversed
Mediator how and which objects interact with each other
Memento what private information is stored outside an object, and when
Observer number of objects that depend on another object; how the dependent objects stay up to date
State states of an object
Strategy an algorithm
Template Method steps of an algoritm
Visitor operations that can be applied to object(s) without changing their class(es)

Table: Design aspects that design patterns let you vary

Discussion of Creational Patterns (GoF, page 135)

There are two common ways to parametrize a system by the classes of objects it creates. One way is to subclass the class that creates the objects; this corresponds to using the Factory Method pattern. The main drawback of this approach is that it can require creating a new subclass just to change the class of the product. Such changes can cascade. For example, when the product creator is itself created by a factory method, then you have to override its creator as well.
The other way to parametrize a system relies more on object composition: Define an object that’s responsible for knowing the class of the product objects, and make it a parameter of the system. This is a key aspect of the Abstract Factory, Builder, and Prototype patterns. All three involve creating a new “factory object” whose responsibility is to create product objects. Abstract Factory has the factory object producing objects of several classes. Builder has the factory object building a complex product incrementally using a correspondingly complex protocol. Prototype has the factory object building a product by copying a prototype object. In this case, the factory object and the prototype are the same object, because the prototype is responsible for returning the product.
Which pattern is best depends on many factors.
Factory Method makes a design more customizable and only a little more complicated. Other design patterns require new classes, whereas Factory Method only requires a new operation. People often use Factory Method as the standard way to create objects, but it isn’t necessary when the class that’s instantiated never changes or when instantiation takes place in an operation that subclasses can easily override, such as an initialization operation.
Designs that use Abstract Factory, Prototype, or Builder are even more flexible than those that use Factory Method, but they’re also more complex. Often, designs start out using Factory Method and evolve toward the other creational patterns as the designer discovers where more flexibility is needed. Knowing many design patterns gives you more choices when trading off one design criterion against another.

References:

Download

Written by Ranjan Kumar

September 14, 2009 at 1:54 pm

Java – Fast Revision

leave a comment »

Important Points
If there is a method call to methods with the same name and with (String[] args) and (String… args), the code won’t compile because it won’t know which method to call.
Static methods can’t override non-static methods and vice-versa – will not compile.
If there is unreachable portion of code, it will not compile(java.lang.Unreachable). e.g. after throwing an exception.
new Boolean(“TRue”) results in true, new Boolean(“AnythingOtherThanCaseInsensitiveTrue”) is false, boolean x = true or false (boolean x=True or boolean x=TRUE will not compile).
in System.out.format/printf(“%b”, varX) will print true if varX has any value
HashMap and LinkedHashMap can have 1 null key and multiple null values, but TreeMap can’t have any null keys (can have null values), and Hashtable can’t have any null keys or values (will result in NullPointerException)
Use of collectionType.toArray() and trying to use as array as specific types, without casting, when toArray() returns Objects.
Static member variables are automatically initialized, final member variables must initialized by the time the constructor finishes, and static final member variables must be assigned at time of declaration or in a static initialization block. Breaking these rules results in failed compilation.
Flow of execution: First the static variables are initialized –> then static block is executed –> then main method is called.
Classes can have multiple static initialization blocks and instance initialization blocks. Remember these Rules:

  • Initialization blocks execute in the order they appear.
  • Static Initialization blocks run once, when the class is first loaded.
  • Instance Initialization blocks run every time a class instance is created.
  • Instance Initialization blocks run after the constructor’s call to super();

Example:

class Init {
	// constructors
        Init(int x) {System.out.println(“1-arg const”);}
	Init() {System.out.println(“no-arg const”);}

        // Static Initialization block
	static {System.out.println(“1st static init”);}

        // Instance Initialization blocks
        {System.out.println(“1st instance init”);}
        {System.out.println(“2nd instance init”);}

        public static void main(String [] args) {
	     new Init();
             new Init(7);
        }
}

Result of running this program:

1st static init
1st instance init
2nd instance init
no-arg const
1st instance init
2nd instance init
1-arg const

Read the rest of this entry »

Written by Ranjan Kumar

September 11, 2009 at 5:16 pm

Posted in Java / Java EE

Overloading in Java

leave a comment »

Constructor Overloading
We may have the requirement of creating objects in many ways. But constructor name is the same as the name of the class, so all the required constructor will have the same name as that of the class. This is called constructor overloading. And can be overloaded on argument types. (constructors have no return types)

Method Overloading
Similarly methods can be overloaded on argument types. Meaning by you can keep the name of methods same but make methods different by arguments. So how methods will be distinguished? Each method have unique list of arguments and will be decided which method will be called.

You can’t overload a method on return values in Java. But why?
To understand this lets consider the following:

void someMethod() {}
String someMethod(){return "something";}

So if I call someMethod() method in the following way:

someMethod();

How can Java determine which someMethod() should be called? So to avoid this confusion methods can not be overloaded on return type.

Written by Ranjan Kumar

September 11, 2009 at 12:36 pm

Posted in Java / Java EE

Cloud Computing

leave a comment »

“The rise of the cloud is more than just another platform shift that gets geeks excited. It will undoubtedly transform the IT industry, but it will also profoundly change the way people work and companies operate.” —The Economist, “Let it Rise,” 10/23/08

“By 2011, early technology adopters will forgo capital expenditure and instead purchase 40% of their IT infrastructure as a service… ‘Cloud computing’ will take off, thus untying applications from specific infrastructure.” — Gartner Press Release, “Gartner Highlights Key Predictions for IT Organisations and Users in 2008 and Beyond,” 1/31/08

Cloud Computing Defined
“It’s one of the foundations of the next generation of computing… It’s a world where the network is the platform for all computing, where everything we think of as a computer today is just a device that connects to the big computer we’re building. Cloud computing is a great way to think about how we’ll deliver computing services in the future.” — Tim O’Reilly, CEO, O’Reilly Media
Read the rest of this entry »

Written by Ranjan Kumar

August 26, 2009 at 10:56 am

Enterprise Integration Patterns

leave a comment »

Some important points from the book Enterprise Integration Pattern” – Gregor Hohpe, Bobby Woolf:

Basic Messaging Concepts

  • Channels
  • Messages
  • Pipes and Filters
  • Routing
  • Transformation
  • Endpoints

Message Channel

Read the rest of this entry »

Written by Ranjan Kumar

May 8, 2009 at 5:04 pm