How To Run Java Application From Command Line with java Command with Command Line Arguments? – POFTUT

How To Run Java Application From Command Line with java Command with Command Line Arguments?


Java is popular programming language used by a lot of developers in different cases on different platforms. We can use Java applications from command line or from GUI but in the start we generally use command line to start the application. In this tutorial we will learn how to compile and start a Java application by providing arguments.

Example Java Application

We will use following Java code during this tutorial. This code will get some argument from command line and print to the standard output which is generally a command line or terminal.

class HelloWorldApp { 
   public static void main(String[] args) { 
       System.out.println("Hello World "+args[0]); //Display the string. 
   } 
}

Compiling Java Application

We will compile our Java application with javac tool. javac means Java Compiler. If we do not need special compile options like 3rd party libraries or compile features we can simply compile our application by providing the source code file which is generally expected with java extension. The code file we want to compile is named as HelloWorld.java

$ javac HelloWorld.java

Running Java Application with Arguments

We can provide arguments with args parameter. args is a String array which provides ability to use multiple arguments. In this example we will provide only single argument which is POFTUT . We will use java command in order to run Java application named HelloWorldApp.

$ java HelloWorldApp "POFTUT"
Running Java Application with Arguments
Running Java Application with Arguments

Running Java Application with Multiple Arguments

As we have seen in previous example we can provide multiple arguments to the Java application by using args array. In this example we will provide 3 arguments to our application but we will make a little change which will look like below.

class HelloWorldApp { 
   public static void main(String[] args) { 
       System.out.println("Hello World "+args[0]+" "+args[1]+" "+args[2]); //Display the string. 
   } 
}

We need to compile again like above with javac command to make affect changes.

$ java HelloWorldApp "POFTUT" "ISMAIL" "AHMET"
 Running Java Application with Multiple Arguments
Running Java Application with Multiple Arguments

LEARN MORE  Php - Functions

Leave a Comment