Home > Uncategorized > Varargs in Java

Varargs in Java

I have recently asked most of my fellow coders the following question.

What is the output of this java program?

public class TestClient {
public static void main(String… args) {
System.out.println(“mohan”);
}
}

All of the answers were “Compile time error”. Needless to say, I have introduced varargs to them.

Here is another question, how do you create a list which has 5 pre-defined element in it.

List<Integer> listIntegers = new LinkedList<Integer>();
listIntegers.add(Integer.valueOf(1));
listIntegers.add(Integer.valueOf(2));
listIntegers.add(Integer.valueOf(3));
listIntegers.add(Integer.valueOf(4));

But it is simple with varargs.

List<Integer> ids2 = Arrays.asList(1, 2, 3, 4);

was it cool!!? it is cool if we don’t know Ruby or Lisp.


Advertisements
  1. January 28, 2009 at 4:21 pm

    The first question makes me to think that many java developers doesn’t aware of Java5 generic feature. I am also in the same group 😉

    The second question creating pre-defined list using utility function, I am sure many java developers doesn’t aware this utility classes unless theu copy/paste examples from websites.

    I don’t want to compare two languages with their utility functions. Ruby makes developer write less number of lines it doesn’t mean it is a great/next generation language. Sun can enhance Java compiler to support Ruby kind of syntax. If Ruby wants to take over Java space they have come up with more innovative ideas like Ruby on Rails framework.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: