Thursday, June 04, 2009

New Features in Java 1.5

  1. Generics: Collection<Student> students;
  2. Enhanced looping: for (Student currentStudent : students)
  3. Autoboxing and unboxing: Integer x = 4 // boxing; Integet y = 5 //boxing; System.out.println(x+y); //unboxing
  4. Enums: instead of static final constants e.g. enum colors {WHITE, GREEN, BLUE}
  5. Variable number of arguments:

·         Use sparingly and try not to overload variable argument methods as it becomes difficult to figure out which method will get invoked. They are invoked when no other method signature matches the call.

·         Zero or more arguments can be passed for variable arguments

·         Variable arguments can only be used as the final set of argument in a method

e.g.

…..func1(String one, String… args) // correct

…..func1(String… args, String one) // not correct

 

Old:

public class Test2

{

        public static void main(String[] args)

        {

                System.out.println(contact(",",new String[]{"one", "two", "three"}));

        }

 

        private static String contact(String seperator, String[] tokens)

        {

                StringBuilder s = new StringBuilder();

                for (String currentValue : tokens)

                {

                        s.append(currentValue);

                        s.append(seperator);

                }

                return s.toString();

        }

}

New:

public class Test3

{

        public static void main(String[] args)

        {

                System.out.println(contact(",","one", "two", "three"));

        }

 

        private static String contact(String seperator, String... tokens)

        {

                StringBuilder s = new StringBuilder();

                for (String currentValue : tokens)

                {

                        s.append(currentValue);

                        s.append(seperator);

                }

                return s.toString();

        }

}

 

No comments: