Sunday 2 March 2014

Command Line Parameters in Java (3)

If you need to supply two or more parameters, separate each parameter from the next with a space as shown below:

andrew@UBUNTU:~/Java$ cat prog36.java
public class prog36
{
public static void main(String[] args)
  {
  int x = Integer.parseInt(args[0]);
  int y = Integer.parseInt(args[1]);
  int z = x + y;
  System.out.println
  (x + " + " + y + " = " + z);
  }
}
andrew@UBUNTU:~/Java$ javac prog36.java
andrew@UBUNTU:~/Java$ java prog36 3 8
3 + 8 = 11
andrew@UBUNTU:~/Java$ java prog36 -5 11
-5 + 11 = 6
andrew@UBUNTU:~/Java$

Command Line Parameters in Java (2)

If you need to include space(s) in a command line parameter, the whole parameter must be enclosed by quotes as shown below:

andrew@UBUNTU:~/Java$ cat prog35.java
public class prog35
{
public static void main(String[] args)
  {
  System.out.println("Hello " + args[0]);
  }
}
andrew@UBUNTU:~/Java$ javac prog35.java
andrew@UBUNTU:~/Java$ java prog35 "Andrew Reid"
Hello Andrew Reid
andrew@UBUNTU:~/Java$

Command Line Parameters in Java (1)

You can pass parameters from the command line to a Java program as shown below. In the final example, a parameter of -1 is supplied. The square root of -1 is a complex number if I remember correctly. The answer given, NaN, stands for not a number:

andrew@UBUNTU:~/Java$ cat prog34.java
public class prog34
{
public static void main(String[] args)
  {
  double x = Double.parseDouble(args[0]);
  System.out.println
  ("The square root of " + x     
   + " is " + Math.pow(x,0.5));
  }
}
andrew@UBUNTU:~/Java$ javac prog34.java
andrew@UBUNTU:~/Java$ java prog34 4
The square root of 4.0 is 2.0
andrew@UBUNTU:~/Java$ java prog34 10
The square root of 10.0 is 3.1622776601683795
andrew@UBUNTU:~/Java$ java prog34 -1
The square root of -1.0 is NaN
andrew@UBUNTU:~/Java$