Java Tutorial

Basic Concepts

Object Oriented Concepts

Coming Tutorials

>Home>Java Tutorial>Command Line Arguments in Java

Java Tutorial

Basic Concepts

Object Oriented Concepts

Coming Tutorials



Command Line Arguments Example in Java

The command line arguments in Java means the values passed to a program at the time of execution. In other word arguments(one or more values) passed on the same line where the Java program execution command is written to run the program. A Java application can accept any number of arguments from the command line.

Example:

D:> java Sample 10 “Rajveer Wavre” 2017

Note: each argument separated by space is considered as independent argument, therefore if you want to pass a multi word string as a single argument then enclose it in “ ” double quote.


What is Use of Command Line Arguments

The Java command line arguments are used to pass some values at the time of starting execution of a program. The Command line arguments in Java are basically used to pass configuration information to the program before starting its actual execution.

For example, you developed a socket program which communicates with server socket program and to connect to the server socket/ server you will require the server IP address and port number of the server program. In this situation you can pass the IP address and port number through command line arguments.


How to access command line arguments in Java program

When you pass the command line arguments to a program, those arguments will get stored into the String type array which is the parameter of the main() method. You can get the arguments from array of String in Java main() method. The following example shows that how to access / get the command line arguments inside the java program.


Example:


class CmdLineArgs
{
 // main() method
public static void main(String[] args)
{
try
{
//directly accessing array values
String ipaddr = args[0];
String portNo = args[1];
// print the received values
System.out.println("Entered IP address is "+ipaddr);
System.out.println("Entered Port number is "+portNo);

// if you want to get an integer value then convert received value into integer, like below
int port = Integer.parseInt(args[1]);

// accessing values using normal for loop
for(int i=0; i<args.length; i++)
{
System.out.println(args[i]);
}

// accessing values using for each loop
for(String s :  args)
{
System.out.println(s);
}
}catch(NumberFormatException ne)
{
System.err.println("Argument Port "+args[1]+" must be an integer.");
System.exit(0);
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.err.println("Please pass ip address and port number at command line");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}  

Share the article to help your friends