• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

OCPJP  RSS feed

 
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?
 
Marshal
Posts: 60060
188
  • 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: 60060
188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!