Wednesday, June 1, 2011

Aspects in Java

Aspects in Java
Lets take an example of a Student class. Student class is responsible for calculating marks of a Student.

class Student{
Now, after six months, your manager tells you to add some code, which will be called before calculateTotalMarks () method will be called.

One solution is to add that code above the first line of method statement. For e.g
class Student{
calculateTotalMarks (){
// Do what manager told me to do

But, it might happen that this method is being called from some other places in your project. So, changing calculateTotalMarks() may break the code.
This is where aspects come into picture. You don’t need to modify Student class. Simply create an aspect class and define pointcuts. For example:

public aspect StudentAspect {
pointcut monitorStudent()
: execution(* Student.calculateTotalMarks (..));

before() : monitorStudent (){

after():monitorStudent (){

Here, I have defined a StudentAspect aspect class and before/after pointcuts. When ever calculateTotalMarks method of Student will be called, getStudentDetails will be called before that and after execution of calculateTotalMarks method, calculateAverageMarks method will be called.

-getStudentDetails method will be called
-calculateTotalMarks method will be called
-calculateAverageMarks method will be called

pointcut monitorStudent()
: execution(* Student.calculateTotalMarks (..));

Pointcut monitorStudent() – declare pointcut with name monitorStudent

execution(* Student.calculateTotalMarks (..)) – Apply pointcuts to any method which resides in any package with Student as class name and calculateTotalMarks as method name with any number of arguments.

Saturday, July 18, 2009

Generics in Java 5

Arrays in Java have always been type safe. For example, an array declared as type integer can only accept integers (not String, Dog, Cat). But, collections are not like that. There is no syntax for declaring type safe collections in pre java 5. To create an ArrayList of integers, you would say:

ArrayList lst = new ArrayList();

Similarly, for creating ArrayList of String, you would say:

ArrayList lst = new ArrayList();

There is no difference between the above two declarations. They are declared of type integer and String respectively, but you can put anything into it. Like, Dog object, Cat Object as so on.

As of java 5, you can use type safe collections. If you want to create an ArrayList of type String, you would say,

ArrayList lst = new ArrayList();
List lst = new ArrayList();

How you add elements to collection in pre java 5?

List lst = new ArrayList ();
lst.add (“Danny”);
lst.add (new Cat ());
lst.add (new Double ());

As you can see, a non- generic collection can hold any kind of Object.

How you add elements to collection in java 5?

List lst = new ArrayList ();
lst.add (“Danny”);
lst.add (“Katty”);
lst.add (new Cat ()); // Compilation Error

You can’t add Cat object in lst ArrayList – You can add only and only Strings.

How to get objects from collection in Pre java 5?

In pre-java 5, the method that get objects out from collection could have only one kind of return type – java.lang.Object. If you want to get element from String list, you require a cast to do so.

String element = (String) lst.get (0);

and since, you can’t guarantee that what is coming out really is a String, the cast could fail at run time.

How to get objects from collection in java 5?

By using generic syntax, you can ensure that what is coming out is what you have added. So, no cast is required here.

String element = lst.get (0);

You are sure that lst List holds only Strings, so no cast is required here.

Thursday, July 16, 2009

Enums in Java 5

Following are the advantages of using Enums:

  • Enums are type safe.
  • Enums are Serializable and Comparable by default
  • Programmers doesn’t require to do extra work of implementing toString(), equals() and hashCode(). Enums provide implementation of these by default.
  • Programmers can use Enums in switch-case statements.
  • Enums are permitted to implement to interfaces.

Java 5.0 lets you to confine a variable to have only a fixed set of predefined values. For example, a cold drink shop may want to serve cold drinks in just three sizes- SMALL, MEDIUM, and LARGE. With this simple declaration, it can be guaranteed that the compiler will stop you from assigning anything to cold drinks except SMALL, MEDIUM, and LARGE.

Syntax enum DrinkSize {SMALL, MEDIUM, LARGE};

Now, if you want to get DrinkSize, you will do something like this

DrinkSize ds = DrinkSize.SMALL;

According to sun coding convention, all constants should be in caps, although you can give these in small letters also.

One important rule you need to remember about Enums is:

They must not be declared within a method.

How to declare Enum outside a class?

enum DrinkSize { SMALL, MEDIUM, LARGE } // this cannot be

// private or protected

class Drink {
DrinkSize size;
public class DrinkTest {
public static void main(String[] args) {
Drink drink = new Drink ();
drink.size = DrinkSize.BIG; // enum outside class

Key point to remember here is that the enum can be declared with only public or default modifier.

How to declare Enum inside a class?

class Drink {
enum DrinkSize { SMALL, MEDIUM, LARGE }
DrinkSize size;
public class DrinkTest {
public static void main(String[] args) {
Drink drink = new Drink();
drink.size = Drink. DrinkSize.SMALL; // enclosing class
// name required

At the end of the enum, putting a semicolon is optional

enum DrinkSize { SMALL, MEDIUM, LARGE };

Tuesday, July 14, 2009

Static Imports in Java 5

One reason of introducing static imports in java is to reduce keystrokes. Although, this is not the only reason, static imports are used when you want to use static members of a class. For example, if you want to use static fields and methods of Math class, you use it as Math, a dot operator (.), followed by a field or method name. Static import declarations enable programmers to use static members of a class as if they were declared in the same class. Class name and dot operator are not required in this case.

Forms of static imports

Static Imports in java comes in two forms:

  • Import a particular static member of a class.

    import static packageName.className.staticMemberName;
    for ex. java.lang.System.out;
  • Import all static members of a class.

    import static packageName.className.*;
    for ex. java.lang.Integer.*;

Let’s look at the static imports with a simple example:

Without using static imports

public class WithoutStaticImportProg {
public static void main(String[] pmt) {

Using static imports

import static java.lang.System.out;
import static java.lang.Integer.*;
public class StaticImportProg {
public static void main(String[] pmt) {

Both classes produce the same output:


Points to remember for static imports:

  • If you use static import for MAX_VALUE member for both Integer and Long class in the same program, you will get a compilation error, since both have a MAX_VALUE constant. Java won’t come to know which class MAX_VALUE you are talking about.
  • Static imports can only be used with static object references, constants (as they are static and final), and static methods.
  • You can use import static; you can’t say static import.

Monday, July 13, 2009

Scanners in Java 5

Java.util.Scanner class in java 5 is mainly used for tokenizing data and finding stuff. Although, Scanners in java 5 doesn’t provide location information or search and replace functionality, it can be used to source data by applying regular expressions to find out how many instances of an expression exists in source data.


Tokenizing is the process of taking big pieces of source data, breaking them into pieces and storing the pieces into variables. Besides scanners in java 5, tokenizing functionality is provided by String (with the help of split() method).
For the purpose of Tokenizing, source data comprises of tokens and delimiters. Tokens are the actual pieces of data, and delimiters are the expressions that separate tokens from each other.

For Example:

Source: “123,23,india,delhi”
If we say that our delimiter is a comma, then our four tokens would be


Tokenizing with Scanner

Let’s look at it using an example. Scanner’s default delimiter is white space.

Scanner methods:
  1. hasNextXxx() - tests the value of the next token but do not actually get the token. For example, hasNextDouble() checks if the next token is of double data type.
  2. nextXxx() - returns the next token
  3. useDelimeter() - allows you to set the delimiter to be any valid regular expression.

Code Snippet:

import java.util.Scanner;
class ScanProg {
public static void main(String [] args) {
boolean b1, b2;
int i;
String s, hitsCntr = " ";
Scanner s1 = new Scanner(args[0]);
Scanner s2 = new Scanner(args[0]);
while(b1 = s1.hasNext()) {
s =;
hitsCntr += "s";
while(b1 = s2.hasNext()) {
if (s2.hasNextInt()) {
i = s2.nextInt();hitsCntr += "i";
else if (s2.hasNextBoolean()) {
b2 = s2.nextBoolean();hitsCntr += "b1";
else {;
hitsCntr += "s2";
System.out.println("hitsCntr " + hitsCntr);

If this program is invoked with
java ScanNext "2 false 46 tty"
it produces

hitsCntr ssssibis2

Sunday, July 12, 2009

printf() method in Java 5

The format() and printf() methods were added to with java 5.

Syntax of printf() method in java 5:

printf("format string", argument (s));

The point to remember here is that, formatting data will always start with a percent sign (%).

For Example:
System.out.printf("%1$d + %2$d", 10, 20);

10 + 20

Here, as we can see, inside the double quotes, is a format string. 1$ represents the first argument. Similarly, 2$ represents the second argument. + sign is used to add a + symbol. d character is a conversion character.

Now, lets watch out for complete syntax:

% [arg_index$] [flags] [width] [.precision] conversion char

  1. arg_index An integer value followed by $. arg_index indicates which argument should be printed in this position.
  2. flags Following is the list of some of the flags:
    "-" Left justify the argument
    "+" Include a (+ or -) sign with the argument
    "0" Pad the argument with zeros
    "," Use comma in argument (like 100,678)
    "(" Enclose nagitive numbers in parentheses

  3. width Determines minimum of characters to be printed

  4. precision Used for formatting with floating point numbers. precision determines the number of digits to be printed after decimal point.

  5. conversion Type of argument to be formatted. For Example:
  • b boolean

  • c char

  • d integer

  • f floating point

  • s string

Sunday, February 8, 2009

Var-Args in Java 5

Java 5 allows methods to take variable number of arguments

Pre Java 5 Example
void doSomething(int i, int j){
Save as Draft


This method will be called as follows:
doSomething(10, 20);

Using Java 5, you can declare doSomething method by giving variable arguments as follows:

void doSomething(int... i){

And at the time of calling the method, pass any number of arguments as you want.

and so on....

Declaration rules for var-args:
  1. Var-arg Type: When you declare var-args in method, you must specify type of arguments method can receive.
  2. Syntax: Var-args should be declared with type followed by three dots (...) and then name of array that will hold the parameters
  3. Positioning and number of var-args parameters: Var-args must be the last argument in a method signature and you can have only one var-arg in a method.