Objective 3, Passing values from the command line

State the correspondence between index values in the argument array passed to a main method and command line arguments.

Note: This seems to be a tiny subject hardly worth an objective of its own.

This objective can catch out the more experienced C/C++ programmer because the first element of argv[] is the first string after the name of the program on the command line. Thus if a program was run as follows.

java myprog myparm

the element argv[0] would contain "myparm". If you are from a C/C++ background you might expect it to contain "java". Java does not contain the Visual Basic equivalent of Option Base and arrays will always start from element zero.

Take the following example

public class MyParm{
public static void main(String argv[]){
        String s1 = argv[1];

I have placed argument one into a String just to highlight that argv is a String array. If you run this program with the command

java MyParm hello there

The output will be there, and not MyParm or hello


Question 1)

Given the following main method in a class called Cycle and a command line of

java Cycle one two

what will be output?

public static void main(String bicycle[]){

1) None of these options
2) Cycle
3) one
4) two

Question 2)

How can you retrieve the values passed from the command line to the main method?

1) Use the System.getParms() method
2) Assign an element of the argument to a string
3) Assign an element of the argument to a char array
4) None of these options


Answer 1)

3) one

Answer 2)

2) Assign an element of the argument to a string

Other sources on this subject

This topic is covered in the Sun Tutorial at