• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

VarArgs in constructor

 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We can have varargs in constructor, but in place of printng integer 2 , it prints some object.
i is being treated as object or wrapper.
Why .
Varargs is legal in constructor ,no error is coming up.???
//-----------------------------

class TestDemo1 {
TestDemo1(int... i) {
System.out.println("my cnstructor"+i);
}

publicvoid method(){}


public static void main(String args[]) {
TestDemo1 myclass = new TestDemo1(2);
}
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's nothing special about constructors here. You would get the same results if this were a regular method. The thing you have to remember is, i is an array. (A rather poorly-named array.) If you want the individual elements in the array, you need to do something that accesses those elements. For example:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic