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.


C#: Passing an argument or a variable into a method

This entry is part 16 of 71 in the series C#

As in any other programming languages, we can pass variables or arguments into a function or method.

using System;

namespace Hello
    class Friend
        private void displayName(String name)
            Console.WriteLine("Hello, what is your name?");
            Console.WriteLine("Your name is " + name);

        static void Main()
            string name = "John";

            Friend friend = new Friend();           

The displayName() has one string argument.

The argument is initialized in the Main() body and printed out by the member function displayName().

I have declared the displayName() method as private.  Its use will be restricted to member functions of the same class.  And in this example, the member functions of Friend class.

In our later examples, we will use constructor to initialize a variable or argument.