Topics Index

Foreach loop for Arrays773

If you need explanation Read this topic

If you need Answer Take test on this topic

Foreach loop for Arrays773
What will be the output of the following program?
class ForEachloop
    public static void main(String args[])
        int[] scores = new int[10];
        scores = new int[] {215, 234, 218, 189, 221, 290};
        for(int score : scores)
            System.out.print(score + "  ");

A. 215 234 218 189 221 290
B. 215 234 218 189 221 290 0 0 0 0
C. Compilation Error 
D. Throws ArrayIndexOutOfBoundsException
Topic: For-each Loop In Core Java Programming

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.

Ans is A..
Array is collection of similar data elements which will store in adjacent locations...
here initially we create the array with size 10 and next we create an array with initilization and assigned to the previous reference

Posted by Uday Kumar    2014-11-24 12:36:27

Ans is A. Initially length of scores[] is 10. Now using new operator we redefined length of scores[] to be 6... Now this will not throw ArrayIndexOutOfBondException error and will print the elements of the array... :)

Posted by Ankur Verma    2014-11-24 12:39:16

a. for each loop is used to display elmts of array.... so it dsplys elemnts of array

Posted by Asma Mujtaba Khan    2014-11-24 12:42:40

Answer is A
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created.
Each item in an array is called an element, and each element is accessed by its numerical index
int[] scores = new int[10];
this statement in main would allocate the memory for 10 integers and by default all the values in the array are initialised to 0.
scores = new int[] {215,234,218,189,221,290};
Now,scores is a reference to an array of integers of length 6 and they are initialised in the order in which they are declared.
for(int score : scores ){
System.out.print(score + " ");
for each loop in java is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.We actually use it if we don't know in advance how many elements are there in an array or a collection.
In the above statement,for each loop prints all the elements in the array until there are no elements in the array

Posted by Shashanka Mogaliraju    2014-11-24 18:12:52

This dose is now closed and the winners are Ankur Verma,  for 'First Correct Comment', Shashanka Mogaliraju,  for 'Best Comment' and Shashanka Mogaliraju for the 'Popular Comment'. The 'lucky liker' is Ankur Verma. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2014-11-25 02:46:21

© meritcampus 2019

All Rights Reserved.

Open In App