Math Class


The Java Math class has many methods that allow you to perform mathematical tasks on numbers. The Math.max(x,y) method can be used to find the highest value of x and y:

1System.out.println( Math.max( 10, 20 ) );      // Output: 20

The Math.min(x,y) method can be used to find the lowest value of x and y:

1System.out.println( Math.min( 10.2, 20.5 ) );      // Output: 10.2

The Math.sqrt(x) method returns the square root of x:

1System.out.println( Math.sqrt( 36.0 ) );      // Output: 6.0

Monitor.java (multi-dimensional arrays)
01// Elements of array are objects of a class Pixel.
02public class Monitor {
03  public static void main( String[ ] args ) {
04    int  x = Integer.parseInt( args[0] );
05    int  y = Integer.parseInt( args[1] );
06    int  code[ ] = { 10, 20, 30, 40, 50, 60 };
07    String  color[ ] = { "red", "green", "blue", "white", "black", "purple" };
08    // Declaring an array of Pixels
09    Pixel[ ][ ]  arr;
10    // Allocating memory for 6 objects of type Pixel
11    arr = new Pixel[3][2];
12 
13    for ( int i = 0; i < 3; i++ )
14      for ( int j = 0; j < 2; j++ )
15        arr[i][j] = new Pixel( code[i*2+j], color[i*2+j] );
16    System.out.println( arr[x][y].getCode( ) + " " +  arr[x][y].getColor( ) );
17  }
18}
19 
20class Pixel {
21  public int    code;
22  public String color;
23 
24  // Constructor
25  Pixel( int code1, String color1 ) {
26    this.code  = code1;
27    this.color = color1;
28  }
29  int    getCode(  ) { return code;  }
30  String getColor( ) { return color; }
31}
shell> java Monitor                 Output: 40 white