Java Reference
In-Depth Information
public static void main(String[] args)
{
for (int i = 0; i < args.length; i++)
switch (args[i])
{
case "-v":
case "-V": System.out.println("version 1.0");
break;
default : showUsage();
}
}
For'sinitializationsectiondeclaresvariable
i
forcontrollingtheloop,itstestsection
compares
i
'scurrentvaluetothelengthofthe
args
arraytoensurethatthisvalueis
lessthanthearray'slength,anditsupdatesectionincrements
i
by1.Theloopcontinues
until
i
's value equals the array's length.
Eachiteration accesses oneofthearray'svaluesviathe
args[i]
expression. This
expressionreturnsthisarray's
i
thvalue(whichhappenstobea
String
objectinthis
example). The first value is stored in
args[0]
.
The
args[i]
expression serves as the switch statement's selector expression. If
this
String
object contains
-V
, the second case is executed, which calls
Sys-
tem.out.println()
to output a version number message. The subsequent break
statement keeps execution from falling into the default case, which calls
showUsage()
tooutputusageinformationwhen
main()
iscalledwithunexpected
arguments.
If this
String
object contains
-v
, the lack of a break statement following the
first case causes execution to fall through to the second case, calling
Sys-
tem.out.println()
. This example demonstrates the occasional need to group
cases to execute common code.
Note
Although I've named the array containing command-line arguments
args
,
this name isn't mandatory. I could as easily have named it
arguments
(or even
some_other_name
).
Thefollowingexampleusestheforstatementtooutputthecontentsofthepreviously
declared
matrix
array, which is redeclared here for convenience: