Java OCA OCP Practice Question 330

Question

Consider the following code:

public class Main{ 
  public static void main (String [] args){ 
    for(int i = 0; i < args.length; i++)   
       System .out.print (i == 0 ? args [i]  : " " + args [i]); 
   } 
 } 

What will be the output when it is run using the following command:

java Main good bye Sunday! 

Select 1 option

A. good bye Sunday! 
B. good good good 
C. goodgoodgood 
D. good bye 
E. None of the above. 


Correct Option is  : A

Note

The arguments passed on the command line can be accessed using the args array.

The first argument (i.e. good) is stored in args[0].

The second argument (i.e. bye) is stored in args[1] and so on.

Here, we are passing 3 arguments.

args.length is 3 and the for loop will run 3 times.

For the first iteration, i is 0 and

so the first operand of the ternary operator (?) will be returned, which is args[i].

For the next two iterations, " "+args[i] will be returned.

The program will print three strings: "good", " bye", and " Sunday" on the same line.




PreviousNext

Related