Menu
Topics Index
...
`

Print Characters From Array


If you need explanation Read this topic

If you need Answer Take test on this topic

Print Characters From Array
What will be the output of the following program?
class PrintName
{
    public static void main(String[] args)
    {
        char chars[] = {'a', 'd', 'e', 'i', 'k', 'n', 'V', 'v'};
        char moves[] = {6, 5, 4, 3, 10, 4, 5, 3, 5, 3, 1, 7};
        int j = 0;
        for (char move : moves)
        {
            j += move;
            j %= chars.length;
            System.out.print(chars[j]);
        }
    }
}

A. ananda
B. Viveka
C. Vivekananada
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 C.
It prints Vivekananda as the output by taking values from moves[] one by one and adding it to the 'j' then getting the remainder by dividing it with the length of chars[] then getting the character from chars[] at that position.

Posted by Gopinath Manchikanti    2014-12-09 08:51:43


ans is C

Posted by Raju VarshnEy    2014-12-09 10:49:54


Ans is C..here we have the Arrays Concept..Arrays can hold the similar type of data elements in adjacent memory locations..arrays can store only homogeneous elements..Arrays are fixed in the size..
when we initialize the arrays when we declare it than specifying the size of an array is optional..
here we chars array and moves(int aray)

here we have the for-each loop which is used to travel the arrays..for-each loop is safe Bcz no chances of getting the ArrayBounds exception..

here we are iterating through the int  array ..every time we are adding the received int value to the the variable j..

Execution:
j=0;
initially we received the value 6
here are performing % with size of char array Bcz to avoid the ArrayBounds Exception..performing % with x means output always less than x only..so here we will get j with in the limit of the char array..
j%=char.length;
j=j%8;
j=6..so here 6th letter in the char array is V..it will printed
now 5 will come so j will become 11
j=j%8;
j=3
so i get printed similar for all other values..

Posted by Uday Kumar    2014-12-09 13:03:21


This dose is now closed and the winners are Gopinath Manchikanti,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Uday Kumar. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-12-10 04:45:25


© meritcampus 2019

All Rights Reserved.

Open In App