Java Command Line Arguments

 Java Command Line Arguments:-

  • Passed at the time of running the java program.

  • The arguments passed from the console can be received in the java program and it can be used as an input.
  • it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java:-

class Example

   {  public static void main(String args[])

{  

System.out.println("Your first argument is: "+args[0]);  

}  

}  


compile by > javac Example.java  

run by > java Example hii  

Output: Your first argument is: hii


Example of command-line argument that prints all the values:-

class A{  

public static void main(String args[]){  

  

for(int i=0;i<args.length;i++) { 

System.out.println(args[i]);}  

  }  

}


compile by > javac A.java  

run by > java A sonoo jaiswal 1 3 abc  

    Output: sonoo  jaiswal  1  3  abc


Write a program in to input 3 numbers on command line argument and find maximum of them

public class Max { public static void main(String[] args) { // Check if exactly 3 arguments are passed if (args.length != 3) { System.out.println("Please provide exactly 3 integer numbers as command line arguments."); return; } // Convert command line arguments to integers int num1 = Integer.parseInt(args[0]); int num2 = Integer.parseInt(args[1]); int num3 = Integer.parseInt(args[2]); // Find the maximum int max = num1; if (num2 > max) { max = num2; } if (num3 > max) { max = num3; } // Print the maximum System.out.println("Maximum of the three numbers is: " + max); } }



Comments

Popular posts from this blog

Java Package

Life cycle of a Thread and creating thread class

Inheritance in Java