New features added to Java 5
Java 5 provides Autoboxing, var args, static imports,Generics, scanners and many other useful features.
Wednesday, June 1, 2011
Aspects in Java
Lets take an example of a Student class. Student class is responsible for calculating marks of a Student.
class Student{
calculateTotalMarks(){
....
....
}
}
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 (){
getStudentDetails();
}
after():monitorStudent (){
calculateAverageMarks();
}
}
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
Syntax
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
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
OR
List
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.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
- 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
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) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.toHexString(42));
}
}
Using static imports
import static java.lang.System.out;
import static java.lang.Integer.*;
public class StaticImportProg {
public static void main(String[] pmt) {
out.println(MAX_VALUE);
out.println(toHexString(42));
}
}
Both classes produce the same output:
2147483647
2a
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
Tokenizing
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
123
23
india
delhi
Tokenizing with Scanner
Let’s look at it using an example. Scanner’s default delimiter is white space.
Scanner methods:
- 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.
- nextXxx() - returns the next token
- 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 = s1.next();
hitsCntr += "s";
}
while(b1 = s2.hasNext()) {
if (s2.hasNextInt()) {
i = s2.nextInt();hitsCntr += "i";
}
else if (s2.hasNextBoolean()) {
b2 = s2.nextBoolean();hitsCntr += "b1";
}
else {
s2.next();
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
Syntax of printf() method in java 5:
- arg_index An integer value followed by $. arg_index indicates which argument should be printed in this position.
- 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 - width Determines minimum of characters to be printed
- precision Used for formatting with floating point numbers. precision determines the number of digits to be printed after decimal point.
- 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
Pre Java 5 Example
void doSomething(int i, int j){
}
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.
doSomething(10);
doSomething(10,20);
and so on....
Declaration rules for var-args:
- Var-arg Type: When you declare var-args in method, you must specify type of arguments method can receive.
- Syntax: Var-args should be declared with type followed by three dots (...) and then name of array that will hold the parameters
- 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.