Bird
0
0

You want to write a Java program that sums two numbers given as command line arguments. Which code snippet correctly converts the arguments and prints the sum?

hard📝 Application Q15 of 15
Java - Command Line Arguments
You want to write a Java program that sums two numbers given as command line arguments. Which code snippet correctly converts the arguments and prints the sum?
public class Sum {
    public static void main(String[] args) {
        // Fill in the blanks
    }
}
Aint a = Integer.valueOf(args); int b = Integer.valueOf(args); System.out.println(a + b);
Bint a = args[0]; int b = args[1]; System.out.println(a + b);
CString a = args[0]; String b = args[1]; System.out.println(a + b);
Dint a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println(a + b);
Step-by-Step Solution
Solution:
  1. Step 1: Convert command line arguments from String to int

    Use Integer.parseInt(args[0]) and Integer.parseInt(args[1]) to convert the first two arguments to integers.
  2. Step 2: Add the integers and print the result

    Sum the two integers and print the result using System.out.println(a + b).
  3. Final Answer:

    int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println(a + b); -> Option D
  4. Quick Check:

    Convert args to int then add [OK]
Quick Trick: Use Integer.parseInt to convert args before math [OK]
Common Mistakes:
  • Trying to add strings directly without conversion
  • Using args as int without parsing
  • Using Integer.valueOf with wrong parameter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes