Showing posts with label Java5 / tiger. Show all posts
Showing posts with label Java5 / tiger. Show all posts

Wednesday, 27 April 2011

Annotations in java5

  1. Java defines seven built-in annotations.
  2. Four are imported from java.lang.annotation: @Retention, @Documented, @Target, and @Inherited.
  3. Three, @Override, @Deprecated, and @SuppressWarnings, are included in java.lang.
Seeing them one by one:
@Override
@Deprecated
@SuppressWarnings
@Retention
@Documented
@Target
@Inherited

Wednesday, 13 April 2011

Static Imports in Java 5

Static keyword is used to allow access to an attribute/ a method or a class without creating instance of it. (Some of you may argue that this is not object oriented way, but we leave that discussion aside for now.) We use static for those elements which do not change from instance to instance of a class. An example would be constant variables in a program. These values are stored using ‘public static final’ keywords. In enum article we have seen one way of managing logically linked constants. Static import tries to improve the way we store and use static elements in program.
Java says it has tried to address an anti-pattern – using interface for constants. Some of us may have used this type of design in programs, where constants are grouped in an interface and used by implementing that interface. This approach is wrong because it alters the purpose of having interfaces in a Java application. Interfaces are used to define highest level of abstract behavior and also to expose a contract to the world in terms of method signatures. Thus, we cannot use interfaces to store constants. An alternative is having them in respective functional classes or in a separate class which can be reused.
When we use this class, we import it and use it wherever the variable is required. Here is the example.
Constants class
package constants;  

public class MyConstants {

public static final String CONSTANT1 = "constant 1";
public static final String CONSTANT2 = "constant 2";
public static final String CONSTANT3 = "constant 3";
}

 Class using constants without static import
import constants.MyConstants;  

public class WithoutStaticImport {

public static void main(String[] args) {
System.out.println(MyConstants.CONSTANT1);
}

}


 
If you have many such constants, then every time you need to use these constants with class name in front of it. With static import, you can get rid of the class name and use constants directly. Let us see how.

Using Static Constant

import static constants.MyConstants.CONSTANT1;  

public class WithStaticImport {

public static void main(String[] args) {
System.out.println(CONSTANT1);
}

}


Important Considerations:

  • Java suggests – use static imports sparingly because these reduce readability and maintainability of a program considerably.
  • Use it when you feel you are going to wrongly use inheritance (i.e. interfaces).
  • When number of variables is less and you can maintain the readability by using meaningful names.
Benefits of static import with already present static java fields
Here are some examples:
  • instead of System.out.println you can use out.println:
    Import the field:
    import static java.lang.System.out;

    So now in code you can write:
    out.println("Hello, World!");
  • PI instead of Math.PI
    area = PI * R * R
    look so much nicer than
    area = Math.PI * R * R

    Tuesday, 12 April 2011

    Pre-java 5 style enums

    Enumerations already existed in other languages like C, C++, SmallTalk etc. Enums are used primarily to handle a collection of logically grouped constants.
    But in java, in prior releases, the standard way to represent an enumerated type was the int Enum pattern:
    // int Enum Pattern - has severe problems!
    public static final int SEASON_WINTER = 0;
    public static final int SEASON_SPRING = 1;
    public static final int SEASON_SUMMER = 2;
    public static final int SEASON_FALL = 3;

    Drawbacks of This Approach:

    • Type Safety: All statuses above may carry some business meaning, but in Java language context, these are just int values. This means any int value is a status for this Java program. So the program using these statuses can break with any int value not defined in this group.
    • Compile Time Constants: All these constants are compiled and used in the program. If you want to add any new constant then you will have to add it to the list and recompile everything.
    • Uninformative: When printed, these are just numbers for a reader. E.g. if a program prints status = 3, the reader will have to go and find out what does it actually mean. Amount of information available with the print is minimal.
    • Restricted Behavior: If you want to use these values in a remote call, or compare them, then you will have to handle it explicitly. Serializable, Comparable interfaces offered by Java for same purpose cannot be used. Also there is no room to add any additional behavior to the statuses, e.g. attaching basic object behavior of hashCode(), toString() and equals() methods.
    • Meaningless Switch-Case Use: When you use statuses above in switch case, you cannot use the variable names; instead you will have to use the meaningless/uninformative numbers to compare. Readability of program goes down considerably in this case.
    • Non-Iterative List: This is a list of values, but you cannot iterate over it the way you can on any collection.
    The solution to above problem is Enum data type in Java 5. Concept of Enum is obtained from the counterpart technologies like C, C++, C# etc. and also considering the Typesafe Enum design pattern in Effective Java book by Joshua Bloch:


    You can read this pattern here.

    Thursday, 3 March 2011

    Varargs in Java: Variable argument method in Java 5

    I think I am late for writing about varargs. The feature of variable argument has been added in Java 5 since its launch. Still I will write something about varargs.
    varargs has been implemented in many languages such as C, C++ etc. These functionality enables to write methods/functions which takes variable length of arguments. For example the popular printf() method in C. We can call printf() method with multiple arguments.

    1
    2
    printf("%s", 50);
    printf("%d %s %s", 250, "Hello", "World");

     

    Syntax

    Varargs was added in Java 5 and the syntax includes three dots (also called ellipses). Following is the syntax of vararg method for method called testVar :

    1
    public void testVar(int count, String... vargs) { }
     
    Notice the dots … in above code. That mark the last argument of the method as variable argument. Also the vararg must be the last argument in the method.
    Now let us check simple hello world varargs code.
     
    Example:
    public class HelloWorldVarargs {

    public static void main(String args[]) {
    test(215, "India", "Delhi");
    test(147, "United States", "New York", "California");
    }

    public static void test(int some, String... args) {
    System.out.print("\n" + some);
    for(String arg: args) {
    System.out.print(", " + arg);
    }
    }
    }




    In above code, the test() method is taking variable arguments and is being called from main method with number of arguments.


    So when should you use varargs?

    As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

    Monday, 20 September 2010

    Enums in java

    In prior releases, the standard way to represent an enumerated type was the int Enum pattern:
    // int Enum Pattern - has severe problems!
    public static final int SEASON_WINTER = 0;
    public static final int SEASON_SPRING = 1;
    public static final int SEASON_SUMMER = 2;
    public static final int SEASON_FALL = 3;
    But these are not type safe, and clearly naming them is bit of a problem.
    See here more for details. So in Java 5, they introduced Enums.

    Defining Enums
    Eg.
    enum Season { WINTER, SPRING, SUMMER, FALL } 
    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
    SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
      
    public enum Shape { RECTANGLE, CIRCLE, LINE } 
      
    Note on Semicolon ( ; )
    Enum embedded inside a class. Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.
    public class Outter {
    public enum Color {
    WHITE, BLACK, RED, YELLOW, BLUE
    }
    }

    Declaring enum variables and using enum values

    The enum class name can be use like any other class type in declarations. Usually enum values must be prefixed with the enum type name.

    Shape drawing = Shape.RECTANGLE;   // Only a Shape value can be assigned.

    Looping over all enum values with foreach loop

    The static values() method of an enum type returns an array of the enum values. The foreach loop is a good way to go over all of them.

    for ( Color c :Color.values() ) {
             System.out.print( c + " " );
    }


    Getting an integer equivalent of an enum value

    Each enum value in an enum class has an associated default value, starting with zero for the first value and incrementing by one for each additional value. This may be accessed with the ordinal() method.
    System.out.println(drawing.ordinal());     // Prints 0 for RECTANGLE.
     

    Input (Convert string to enum)

    The valueOf() method can be used to convert a string value to an enum value. Here is an example of reading in a Shape value from a Scanner object in.
    drawing = Shape.valueOf(in.next());
     
    or
    drawing = Shape.valueOf("RECTANGLE");
     
    The static methods valueOf() and values() are created at compile time and do not appear in source code. 
    They do appear in Javadoc, though; 
     
    Read more in Effective java for better practises.