Challenge - 5 Problems
Argument Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Java program?
Consider the following Java program that accesses command-line arguments. What will it print when run with arguments:
java Main Hello World?Java
public class Main { public static void main(String[] args) { System.out.println(args[0] + " " + args[1]); } }
Attempts:
2 left
💡 Hint
Remember that args is an array of strings passed from the command line.
✗ Incorrect
The program prints the first and second command-line arguments separated by a space. Since args[0] is "Hello" and args[1] is "World", the output is "Hello World".
❓ Predict Output
intermediateWhat happens if no arguments are passed?
What will be the output or result of running this Java program with no command-line arguments?
Java
public class Main { public static void main(String[] args) { System.out.println(args.length); System.out.println(args[0]); } }
Attempts:
2 left
💡 Hint
Check what args.length is and what happens when accessing args[0] if no arguments exist.
✗ Incorrect
args.length is 0 because no arguments are passed. Accessing args[0] causes ArrayIndexOutOfBoundsException because the array is empty.
🔧 Debug
advancedIdentify the error in accessing arguments
This Java program tries to print all command-line arguments but throws an error. What is the cause?
Java
public class Main { public static void main(String[] args) { for (int i = 1; i <= args.length; i++) { System.out.println(args[i]); } } }
Attempts:
2 left
💡 Hint
Remember array indices start at 0 and go up to length-1.
✗ Incorrect
The loop uses i from 1 to args.length inclusive, but valid indices are 0 to args.length-1. Accessing args[args.length] causes ArrayIndexOutOfBoundsException.
📝 Syntax
advancedWhich option correctly accesses the last argument?
Given a Java program with command-line arguments, which code snippet correctly prints the last argument?
Attempts:
2 left
💡 Hint
Array indices start at 0 and end at length-1.
✗ Incorrect
args.length is the number of arguments, but the last index is args.length - 1. Accessing args[args.length] or args[args.length + 1] causes errors. Negative indices are invalid in Java.
🚀 Application
expertWhat is the output of this program with arguments: java Main 5 10 15?
This Java program sums integer command-line arguments. What does it print when run with arguments
5 10 15?Java
public class Main { public static void main(String[] args) { int sum = 0; for (String arg : args) { sum += Integer.parseInt(arg); } System.out.println(sum); } }
Attempts:
2 left
💡 Hint
Integer.parseInt converts strings to numbers before adding.
✗ Incorrect
The program converts each argument to an integer and sums them: 5 + 10 + 15 = 30. It then prints 30.
