• Post Reply Bookmark Topic Watch Topic
  • New Topic

OCPJP  RSS feed

 
Kajal Dusseja
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between var-args and an array?

1.public void myMethod(int y, String...z){}
2.public void myMethod(int y, String[] z){}

Do both methods mean the same?
 
Campbell Ritchie
Marshal
Posts: 56223
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the viewpoint of the receiving method, there is no real difference. The compiler will see those two methods as override‑equivalent, so they won't both compile together. The difference is how you call them. You can call
myMethod(123, "CodeRanch", "is", "brilliant");
or
myMethod(123, new String[]{"CodeRanch", "is", "brilliant"});
But the receiving method will receive one int and one three‑element String[] in both cases. The variable arguments list is collected into an array.
You will notice a difference like this:-
 
Kajal Dusseja
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:


Method with three integer arguments will be called.
Thank You.
 
Campbell Ritchie
Marshal
Posts: 56223
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!