Comparing multiple arguments and returns the smallest argument I want to see if anyone knows how to optimize the code below:

public class smallestTest
{
   public static void main(String[] args)
   {
      double resultSmallest = smallest(2.5, 3.5, 4.5);
      System.out.println("The smallest number out of 2.5, 3.5, and 4.5 is: " + resultSmallest);
   }

  /**
  Computes the smallest of three variables
  @param x, y, z
  @returns smallestNumber
 */


    public static double smallest(double x, double y, double z)
    {
         double smallestNumber = 0;
         if ( x &lt; y &amp;&amp; x &lt; z)
         {
           smallestNumber = x;

         }
         else if (y &lt; x &amp;&amp; y &lt; z)
         {
            smallestNumber = y;

         }
         else if (z &lt; x &amp;&amp; z &lt; y)
         {
            smallestNumber = z;

         }

         return smallestNumber;
      }
}
You can use something called Varargs that was introduced in java 5.

It is used in method declarations to declare arguments as an array.

public void myMethod(double... doubleArray) {
}

public void callMyMethod() {
    myMethod(1.2, 4, 2, 1); // all those are put into a double[]
}


You can adapt this to your program by doing the following:

public static double smallest(double... vals) {
    // must pass at least 1 argument. You could also return Double.NaN or something
    if(vals.length == 0) throw new IllegalArgumentException("smallest must be passed at least 1 value.");
    // start with the first value as the smallest
    double smallest = vals[0];
    for(int i=1;i&lt;vals.length;i++) {
        // see if this ones smaller than our stored smallest
        if(vals[i] &lt; smallest) {
            smallest = val[i];
        }
    }
    return smallest;
}


You can then call this with as many double values as you like.