Bird
0
0

How can you modify the main method to accept command line arguments and also handle the case when no arguments are passed, printing "No args" in that case?

hard📝 Application Q9 of 15
Java - Command Line Arguments
How can you modify the main method to accept command line arguments and also handle the case when no arguments are passed, printing "No args" in that case?
Apublic static void main(String[] args) { if(args.length == 0) System.out.println("No args"); else System.out.println(args[0]); }
Bpublic static void main(String args) { if(args == null) System.out.println("No args"); else System.out.println(args); }
Cpublic static void main(String[] args) { if(args == null) System.out.println("No args"); else System.out.println(args[0]); }
Dpublic static void main(String[] args) { if(args.length < 0) System.out.println("No args"); else System.out.println(args[0]); }
Step-by-Step Solution
Solution:
  1. Step 1: Check parameter type and null safety

    Main method must accept String[] args. args is never null but can be empty.
  2. Step 2: Check condition for no arguments

    args.length == 0 means no arguments. public static void main(String[] args) { if(args.length == 0) System.out.println("No args"); else System.out.println(args[0]); } correctly checks this and prints "No args".
  3. Final Answer:

    public static void main(String[] args) { if(args.length == 0) System.out.println("No args"); else System.out.println(args[0]); } -> Option A
  4. Quick Check:

    Check args.length == 0 for no arguments [OK]
Quick Trick: args array is never null; check length for no args [OK]
Common Mistakes:
  • Checking args == null
  • Using wrong parameter type
  • Checking length < 0 which is impossible

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes