Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Command Line Arguments in Java [With Example]

Updated on 03 July, 2023

7.17K+ views
7 min read

While writing your Java programs, you must have noticed the (String[] args) in the main() method. These are command-line arguments being stored in the string passed to the main method. These arguments are called command-line arguments.

It is quite common to use command-line arguments because you don’t want your application to do the same thing in every run. If we want to configure its behaviour somehow, we will have to use command-line arguments.

Check out our free courses to get an edge over the competition

A Few Facts to Keep in Mind about Command Line Arguments in Java

Before understanding the use of Java program command line arguments, let’s quickly evaluate the most important facts in the following points:

  • You can use command-line arguments to specify any configuration information while launching the Java application
  • You can use multiple arguments in the command line simultaneously without any limitations
  • Command-line arguments have data that come in the form of string

What is the Use of Command-Line Arguments?

These command-line arguments are passed from the console. They can be received in the java program to be used as input. We can pass as many arguments as we want, as it is stored in an array. Here is an example of how you can use the command line arguments.

In the program

class test
{
    public static void main(String[] args)
    {
        for(int i=0;i< args.length;++i)
        {
            System.out.println(args[i]);
        }
    }
}

 

Check out upGrad’s Advanced Certification in Blockchain\

A Brief on Java Code to Understand Command-Line Arguments

Do you want to understand the command line input in Java? Then, you first need to create a file: CommandLine.java. There, write the code (as mentioned below) to display the arguments that pass via the command line:

//Display all command-line arguments.
class CommandLine
{
public static void main(String args[ ])
{
        System.out.println(“The command-line arguments are:\n”);
     for (int x = 0; x < args.length; x++)
            System.out.println("args[" + x + "]: " + args[ x ]);
}
}

 

How to Run the Program

You must follow a few steps to compile and run the Java program in the command prompt. Here’s a list of steps to follow:

  • First, save this program as the CommandLine.java
  • Now, open the command prompt window, and there, compile this program- javac CommandLine.java
  • After you have completed compiling it successfully, you now need to run the command by writing arguments- java CommandLine argument-list (for instance – java CommandLine upGrad Java Tutorial)
  • Now, click on enter to get the desired output

In console

java args1 args2 args3 …

 

As a result, we will get an output with these arguments, which we passed as an input. This program will print all these arguments separated by a new line:

args1
args2
args3 

 

As we can see, command-line arguments can only be of String type. What if we want to pass numbers as arguments? Let’s say you want to add something to the argument you pass. If you do it with the above program, it will be something like:

In the program

class test
{
    public static void main(String[] args)
    {
        for(int i=0;i< args.length;++i)
        {
            System.out.println(args[i]+1);
        }
    }
}

 

Check out upGrad’s Advanced Certification in DevOps 

In console

java test 11 12 13

 

Output

111
121
131

 

You can see that it appends the characters to the “String” of numbers. To add a number to them, we need to convert the arguments into integer form. To do so we use the parseInt() method of the Integer class. The implementation will be like –

In the program

class test {
    public static void main(String[] args) {
     for (int i = 0; i < args.length ; ++i ) {
     int arg = Integer.parseInt(args[i]);
     System.out.println(arg + 1);
     }
    }
}

 

In console

java test 11 12 13

 

Output

12
13
14

 

As you can see how we get our desired results. We can also do the same with double() and float() using parseDouble() and parseFloat().

Sometimes, the arguments that are provided cannot be turned into the specific numeric type, which will result in an exception called NumberFormatException.

Now you might think that we are passing these arguments to our application. Will it affect the performance of the application in any way? The answer to that is no. Passing arguments won’t slow down your application or have any other performance hits on it. Even if it does, it is very minimal and should not be noticeable.

How to Calculate Factorial of Any Number through the Command-Line?

If you wish to use command line arguments in Java in different calculations, let’s first calculate the factorial of any number through the command-line argument:

public class Factorial
{
public static void main(String[] args)
{
     int i , fact = 1;
     int number = Integer.parseInt(args[0]);
     for(i = 1; i<= number ; i++)
     {
         fact = fact * i;
     }
        System.out.println("The factorial of " + number + " is " +fact);
}
}

 

Passing Numeric Command-Line Arguments in Java: Steps to Follow

It is noteworthy to state that the main() method of the Java program accesses data with string type arguments. So, you cannot pass numeric arguments through the command-line. If done so, they will be converted into the string. As a result, they cannot be used as numbers and fail to perform numeric operations. But there is one method to use them. Simply convert the string(numeric) arguments into the numeric values. Here’s the example:

public class NumericArguments
{
public static void main(String[] args)
{
     // convert into integer type
     int number1 = Integer.parseInt(args[0]);
        System.out.println("First Number: " +number1);
     int number2 = Integer.parseInt(args[1]);
     System.out.println("Second Number: " +number2);
     int result = number1 + number2;
        System.out.println("Addition of two numbers is: " +result);
}
}

 

In this program, you may use the parseInt()of the Integer class that converts the string argument into the integer.

Alternatively, you can also use the parseDouble() to convert the string into the double value or parseFloat()to convert it into the float value.

Read: Java Project Ideas & Topics

Variable Arguments in Java

In JDK 5, Java included a new feature that simplifies creating methods that need a variable number of arguments. This feature is called varargs which means variable-length-arguments. The method which takes the variable arguments is called a varargs method.

Before this feature had been implemented in Java, there were two possible ways to pass variable arguments in an application. One of them was using an overloaded method, and another involved passing the arguments in an Array and then passing that array to a method. Both of these methods were error-prone. Varargs solved all the problems that came with the previous methods with the added benefit of clean and less code to work with.

The variable-length-arguments are specified with three periods (…), below is the full syntax for the same –

public static void varMethod(int ... x) 
{
   // body of the method
}

 

The above syntax tells the compiler that varMethod() can be called with zero or more arguments.

Varargs can also be overloaded.

There are some rules for using varargs:

  • There can only be one variable argument in the method.
  • Variable arguments must be the last argument.

An Error Occurring on Using Two Arguments in a Varargs Method

void method(String... str, int... a)
{
    // Compile time error as there are two varargs
}

 

An Error Occurring When We Specify Varargs as the First Argument Instead of the Last One

void method(int... a, String str)
{
    // Compile time error as vararg appears 
    // before normal argument
}

 

So, if you want to pass variable arguments, you can use the varargs method.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Upskill, Upgrade and Update

Java is indeed an exceptional language and is being used by various multinational corporations and companies to develop large-scale applications. 

The scope for such skills can really upscale your career. upGrad has been providing exceptional courses in Machine Learning, Coding in many languages such as Java, C++, C, AI, Natural Language processing, and much more. Brighten up your career by upgrading to the language of the future: Java! 

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. How to run a Java class using the command line?

To run a Java class using command line i.e. from shell prompt simply type the command java -jar jar_file.jar where jar_file.jar is the name of your JAR file (e.g. QuoraAnswerManager.jar). The simplest way to run a Java class in the command line is to compile it and provide a classpath to it. Compile your Java class with the following command: javac -classpath classpathMainFolder myClass.java. Then run the compiled class with the following command: java -classpath classpathMainFolder myClass.

2. What are jar files in Java?

In Java there are many types of jar files. Jar files are simply packages. The JAR file format was originally created for Java and was intended for software distribution. JAR files are sometimes called JAR archives because they function similarly to a ZIP file, in that they store multiple files and directories within a single file for easy distribution. A JAR file is sometimes referred to as a Java Archive. This is not technically correct, but is often used in the Java community where both the word archive and packaging are sometimes used to refer to JAR files.

RELATED PROGRAMS