Java quiz 42: Array of strings

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
Select    31   32   33   34   35   36   37   38   39   40   41   42   43   44   By title 
>

Here is a simple array of Strings with the length of 5.

Java quiz 42: Array of strings

Level: Normal

What happens if the following code is compiled and run?

public class ListCompany
{
  public static void main(String[] args)
  {
    String[] companies = 
      {"Alibaba", "HP", "", "IBM", "Amazon"};
    for(int i = 0; i < companies.length; i++)
    {
      if(i >= 3)
      {
        companies[i] = "Microsoft";
      }
      else
      {
        companies[i] = "Oracle";
      }
    }
    System.out.println(companies[2]);
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “Microsoft” to the standard output.
b. This program writes “nothing” to the standard output.
c. This program writes “Oracle” to the standard output.
d. This program writes “HP” to the standard output.
e. This program writes “Amazon” to the standard output.
f. This code fails to compile.

Answer explanation

  • We have assigned the values “Alibaba”, “IBM”, “HP”, “”, “Amazon” to the elements of the array. The foruth element value
    is empty “”, which is the element of the index 2.
  • The statement if(i >= 3){ companies[i] = “Microsoft”;} changes the values of the elements with indexes 3 and 4 to microsoft.
  • The else statement changes the values of the elements with indexes 0, 1, and 2 to Oracle. Therefore, this program writes Oracle to the standard output.

The correct answer is: c.




Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *