Java Reference
In-Depth Information
This command has fi ve command-line arguments, so the fi rst element in the String
array is “hi” , the second element in the array is “goodbye” , and so on. The following
PrintGreetings class contains a for loop that iterates through the command-line
arguments and outputs them to the console:
1. package com.sybex.demos;
2. public class PrintGreetings {
3. public static void main(String [] args) {
4. for(int i = 0; i < args.length; i++) {
5. System.out.println(args[i]);
6. }
7. }
8. }
If PrintGreetings is executed with the command line in Figure 1.4, then the output
looks like this:
hi
goodbye
see
you
later
Command-Line Arguments on the Exam
Notice that the fi rst command-line argument in the array is args[0] because Java uses
zero-based indexes for arrays. The exam creators seem to like questions about arrays
and command-line arguments, so don't be surprised if you see a question that tests both
topics at the same time. For example, what is the output of the DoSomething class when
executed with the following command?
java DoSomething one two
1. public class DoSomething {
2. public static void main(String args []) {
3. System.out.print(args[1]);
4. System.out.print(args[2]);
5. }
6. }
Search WWH ::




Custom Search