Java: Passing arguments to main

This entry is part 4 of 54 in the series Learn Java

When starting a Java program from the command line, we can pass some arguments into the program.

We will use our previous example for illustration.

package javaapplication3;

import javax.swing.*;

public class JavaApplication3 {

    public static void main(String[] args) {
        String[] argument = args;
        JFrame frame = new JFrame( "HelloJava" );
        JLabel label = new JLabel(argument[0], JLabel.CENTER );
        frame.setSize( 300, 300 );
        frame.setVisible( true );

We can see in the code that there is a string array that is past into the main program.

We look at this line:

public static void main(String[] args)

This is the entrance to the program and in an Object oriented program, we call main a method of the program.

This main method is a static method as shown in the declaration.  We need this to be a static method as this method is not invoked through an instance.

We will look at instance in an object oriented program in our later examples.

To pass one argument Hello into the program, we use the following command:

java -jar JavaApplication3.jar Hello

The Hello argument will be past into the program and printed out as shown in the screenshot below.


Series Navigation<< Java: Swing
Java: integer variables >>