Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

varargs, Chapter 4, no 5  RSS feed

 
Petra Miller
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the book "OCA study guide" from Boyarsky/Selikoff the 5th question in chapter 4 is:

Given the following method, which of the method calls return 2?
public int howMany(boolean b, boolean... b2){
   return b2.length;
}
...
F. howMany(true, {true, true}
...


F is a wrong answer and in eclipse it actually does not compile. But why? {true, true} is a short form to create an array and to fill it. For example I can write "boolean b = {true, true};
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37044
505
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Petra,
Great question. The "full" syntax for creating a primitive array is



If you pass new boolean[] {true} to a method that takes varargs, all is well.

Java recognizes there is redundancy. So if you are assigning the array to a variable, it lets you omit the new boolean[] part. With method signatures, this isn't implied so isn't allowed.
 
Charles O'Leary
Ranch Hand
Posts: 184
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Petra,
If needed, here's an additional reference
 
You have to be odd to be #1 - Seuss. An odd little ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!