Consider the following Java program. What will it print if run with arguments apple banana?
public class Main { public static void main(String[] args) { System.out.println(args[0] + " and " + args[1]); } }
Remember that args holds the command line arguments as strings in order.
The args array contains the command line arguments. args[0] is "apple" and args[1] is "banana". The program prints them joined by " and ".
What will this Java program print if run without any command line arguments?
public class Main { public static void main(String[] args) { if (args.length == 0) { System.out.println("No arguments"); } else { System.out.println(args[0]); } } }
Check the length of args before accessing elements.
If no arguments are passed, args.length is 0, so the program prints "No arguments".
What will this Java program print if run with arguments one two three?
public class Main { public static void main(String[] args) { for (String arg : args) { System.out.print(arg + "-"); } } }
Notice the use of System.out.print inside the loop.
The loop prints each argument followed by a dash without a newline. So the output is "one-two-three-" all on one line.
What error will this Java program throw if run without any command line arguments?
public class Main { public static void main(String[] args) { System.out.println(args[0]); } }
Accessing an array element that does not exist causes an exception.
Since args is empty, accessing args[0] causes an ArrayIndexOutOfBoundsException.
You want to read two integer numbers from command line arguments and add them. Which code snippet correctly does this?
Remember to convert strings to integers properly.
Integer.parseInt converts a string to a primitive int. Casting strings directly or assigning strings to int variables causes errors. Integer.valueOf returns an Integer object, not int, so option C is invalid without unboxing.
