Now we see how to accept values as arguments from command prompt ( cmd ) and use those values in the program. Let see how to use values given from cmd to use in the concerned program.
Open the command prompt (cmd) and enter "javac" command to test whether the java path is added. If the path is added, then you can see the output as shown below.
Now Create a java file with the name you want to create it as
"notepad <your filename.java> " in cmd as shown below.
Write the java code in the notepad file you created it before. Before execution, check out errors in the program.
1 2 3 4 5 6 7 8 | class sample{ public static void main(String [] args){ int a,b; a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); System.out.println("Sum of two numbers is "+(a+b)); } } |
After completely writing the code it's time to execute it. Go to cmd and enter the command "javac <your filename>.java" and press enter. The above code gets executed correctly as there are no errors and it's a simple program.
After getting correctly compiled without errors, now we have to execute it for output. To run the code we have to type the command "java <your filename> 10 20" .
Here 10,20 are the values that are passed to the program as arguments.