Conversion of Command-line Arguments

  • Command line arguments are stored as String in the args array. If your application needs a numeric value then it must be converted to the required type.
  • Here’s the code that converts a command-line argument to an integer,
public class Conversion {
	public static void main(String[] args) {
		int number = 0;
		if (args.length > 0){
			number = Integer.parseInt(args[0]);
		}
		System.out.println(number + 4);
	}
}

Test Case 1:
Input: 1951
Output: 1955

Test Case 2:
Input: abc
Output:
Exception in thread “main” java.lang.NumberFormatException: For input string: “abc”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Conversion.main(Conversion.java:5)

The parseInt() method in the Integer class throws a NumberFormatException if the String is not in proper format i.e.) not a number.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.