0

Its something I am unsure about rather than a problem.This code i had encountered during a test I was taking.I am gonna paste the code here now.

static void count(String...obj){
     System.out.println(obj.length);
}

public static void main(String str[]){
    count(null,null,null);
    count(null,null);
    count(null);
}

The program run fine and the output is 3 2 and in the last count call it throws a null point exception(obviously enough).Which was the questions in the test by the way. Anyways,I am not able to understand what kind of function argument is (String...obj). Can someone help me with it please.

MByD
  • 135,866
  • 28
  • 264
  • 277
Kanwaljeet Singh
  • 1,215
  • 4
  • 15
  • 25

4 Answers4

6

It's a varargs parameter, which basically allows you to specify multiple arguments and let the compiler create an array for you.

The reason you get an NPE in the last line is that the compiler effectively has the choice between:

count(new String[] { null })

and

count((String[]) null)

... and it prefers the latter.

You could force it to use the former conversion by casting the null:

count((String) null);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you that was helpful .. Can you please explain the difference between count(new String[]{ null}) and count((String[] null) – Kanwaljeet Singh Aug 09 '12 at 19:10
  • @KanwaljeetSingh: Sure - the first is a reference to an array with a single element, and that elemen is null. The second is just a null reference - there's no array at all. – Jon Skeet Aug 09 '12 at 19:22
0

It is another version of specifying array parameter.

count(String...obj)

Means count method accepts String[]

which is equal to

count(String[] obj)
kosa
  • 65,990
  • 13
  • 130
  • 167
0

String... takes either a succession of String parameters, or an String array. When putting null I guess it is interpreted as a null array.

kgautron
  • 7,915
  • 9
  • 39
  • 60
0

These method arguments are known as varargs, and allow for an arbitrary number of arguments of a given type to be passed into your method. As mentioned in an answer to another question, they were introduced in Java 1.5, although they're not usable with Java mobile editions.

Community
  • 1
  • 1
Edd
  • 3,724
  • 3
  • 26
  • 33