0 Replies Latest reply on Nov 28, 2016 5:43 PM by Patrick Cicero

    OCA Java SE 8 Programmer Study Guide

    Patrick Cicero

      On page 191 talking about varargs  it states

      fly(new int[] { 1,2,3 });

       

      However you can only call varags version with standalone parameters

       

      fly(1, 2, 3);

       

      I wrote the following test code

      class testVariableArgumentMethodOverloading

      {

          public static void main(String args)

          {

              testOne tOne = new testOne();

              testTwo tTwo = new testTwo();

              tOne.fly(new int[] {1,2,3});

              tOne.fly(1, 2);

       

              tTwo.fly(new int[] {1,2,3});

              tTwo.fly(1,2,3,4);

          }

      }

      class testOne

      {

        void fly(int[] lengths)  // array parm

        {

        System.out.println("In testOne.fly");

        }

      }

      class testTwo

      {

        void fly(int... lenghts)  //vararg parm

        {

        System.out.println("In testTwo.fly"); 

        }

      }

       

      The vararg will compile if you pass in standalone parameters or an array but the method with array as parm will not compile if you pass in standalone parms

      Get the following message when compile

       

      error: method fly in class testOne

      cannot be applied to give types;

          tOne.fly(1,2);

       

          required int[]

          found: int, int

          reason: actual and formal argument lists differ in lengh

      1 error

       

      At the very leas the statement you can only call the varargs version with stand-alone parameters is not defined well enough