Topics Index

Animal Colors

If you need explanation Read this topic

If you need Answer Take test on this topic

Animal Colors
What will be the output of the following program?
public class AnimalColors {
    public static void main(String[] args) {
        String[] animals = { "Crow", "Cow", "Parrot", "Pig"};
        String[] colors = { "Black", "White", "Green"};
        int map[] = { 1, 2, 3, 1};
        for (int i = 0; i < animals.length; i++) {
            System.out.println(animals[i] + " is " + colors[map[i]]);

A. Crow is Black
Cow is White
Parrot is Green
Pig is Black
B. Crow is White
Cow is White
Parrot is White
Pig is White
C. Some other output
D. Compilation Error or Runtime Error
Topic: Java String Arrays - String Arrays In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

option D some other output
animals[0] is colors[1]  as map[0]=1
prints Crow is White
in next iteration
animals[1] is colors[2]  as map[1]=2
prints Cow is Green
in next,
animals[2] is colors[3]  as map[2]=3
colors[3] is raises array out of bound exception.

Posted by Sasikanth Sharma    2014-07-02 03:38:27


Posted by Neha Chaudhari    2014-07-02 04:02:30


Posted by Shashi Kumar    2014-07-02 04:03:13


Posted by Naga Siddu    2014-07-02 04:28:12


Posted by Yogesh Sachan    2014-07-02 04:33:27

Ans is 'A' because it just accessing array elements as per the index of array...

Posted by Abhijit Bhusare    2014-07-02 04:43:22


Posted by Raj Vaibhav Singh    2014-07-02 04:50:55


Posted by Rishav Seksaria    2014-07-02 04:57:07

C - colour should be WHITE then GREEN like that

Posted by Mani Deep    2014-07-02 06:34:26

D and also it prints Some output, finally shows ArrayIndexOutOfBoundsException:

Posted by Rajashekar Jadala    2014-07-02 07:49:21

C    first- crow is white   is printed  then cow is green is  printed after that array index out of bounds because when i is 2,map[2] is 3  then colors[3] is not present in the array so ArrayIndexOutOfBoundsException  is raised.

Posted by Aparna Lakshmi    2014-07-02 07:55:12


Posted by Vijay Raichura    2014-07-02 12:55:17

I think C... crow is black. cow is white. parrot is green

Posted by Muhamad Noor Hariz    2014-07-02 21:50:07

Congratulations Rajashekar Jadala. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-07-03 04:11:24

© meritcampus 2019

All Rights Reserved.

Open In App