Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to take input from user through command-Line Argument.

Java Code Example — Input/Output Programs

ADVERTISEMENT

Java Program to take input from user through command-Line Argument.

Objective

Write a Java program to read input directly from Command-Line Arguments.

Algorithm / Approach

  1. In the main(String[] a) method, access the array a (or args).
  2. Read the first argument at index 0 (a[0]) as a String name.
  3. Read the second argument at index 1 and convert it to an int using Integer.parseInt(a[1]).
  4. Read the third argument at index 2 and convert it to a double using Double.parseDouble(a[2]).
  5. Print the variables.
InputDemo.java
class InputDemo{
 public static void main(String[] a)
 {
  String n = a[0];
  int age = Integer.parseInt(a[1]);
  double m = Double.parseDouble(a[2]);
  System.out.println("Name- "+n);
  System.out.println("Age- "+age);
  System.out.println("Marks- "+m);
 }
}

Expected Output

// Run as java InputDemo Alok 24 73.4
Name- Alok
Age- 24
Marks- 73.4

Explanation of the Program

  • Command-line arguments allow you to pass data into a Java program at the exact moment you run it from the terminal (e.g., java InputDemo Alok 24 73.4).
  • The JVM automatically takes those space-separated values and packs them into the String[] array parameter of the main method.
  • Because everything from the command line is strictly considered text (String), you must use wrapper classes like Integer and Double to parse the text back into numbers if you want to do math with them.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT