All but the most trivial computer programs need to make decisions. They test a condition and operate differently based on the outcome of the test. This is quite common in real life. For instance you stick your hand out the window to test if it's raining. If it is raining then you take an umbrella with you. If it isn't raining then you don't.
All programming languages have some form of an if
statement that tests conditions. In the previous code you should
have tested whether there actually were command line arguments
before you tried to use them.
Arrays have lengths and you can access that length by
referencing the variable arrayname.length
You test the
length of the args
array as follows.
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
if (args.length > 0) {
System.out.println("Hello " + args[0]);
}
}
}
System.out.println(args[0])
was wrapped in a
conditional test, if (args.length > 0) { }
. The
code inside the braces, System.out.println(args[0])
,
now gets executed if and only if the length of the args array is
greater than zero.
The arguments to a conditional statement like if
must be a boolean value, that is something that evaluates to true
or false. Integers are not permissible.
In Java numerical greater than and lesser than tests are done
with the >
and <
operators
respectively. You can test whether a number is less than or equal
to or greater than or equal to another number with the
<=
and >=
operators.