Yeni adresim http://doganberktas.com

29 Mart 2009 Pazar

Weird Three Point Syntax for Method Arguments in Java 1.5 -- and other new things I haven't known

Recently, I read an article in JavaWorld  about the new features of Java 1.5 -- although they are not new anymore :) -- . There are really interesting cool things that I dont use in daily coding. Time savers we can say. Below the ones that I liked :

Instead of using this for a method parameter,


int sum(Integer[] numbers)
{
  int mysum = 0;  
  for(int i: numbers)
  mysum += i;
  return mysum;
}
// Code fragment that calls the sum method
sum(new Integer[] {12,13,20});

Instead of this, you can use 

// An example method that takes a variable number of parameters
int sum(Integer... numbers)
{
  int mysum = 0;  
  for(int i: numbers)
  mysum += i;
  return mysum;

// Code fragment that calls the sum method
sum(12,13,20);


Another one is the printf method:

// Using System.out.println and System.out.printf
int x = 5;
int y = 6;
int sum = x + y;
// Pre 1.5 print statement
System.out.println(x + " + " + y + " = " + sum);
// Using 1.5 printf
System.out.printf("%d + %d = %d\n", x, y, sum);

// Demonstrating printf versatility
System.out.printf("%02d + %02d = %02d\n", x, y, sum);


0 yorum: