Menu
Topics Index
...
`

Array Output


If you need explanation Read this topic

If you need Answer Take test on this topic

Array Output
What will be the output of the following program?
class ArrayOutput
{
    public static void main(String s[])
    {
        int i[] = {12, 15, 16, 17, 19};

        for(int i = 0; i < 5; i++)
        {
            System.out.println(i[i]);
        }
    }
}

A. 12
15
16
17
19
B. 12
15
16
17
C. 15
16
17
19
D. Compilation Error
E. Throws ArrayIndexOutOfBoundsException
Topic: Learn Arrays And Loops

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 D..here we have the concept of the Arrays...which can store the similar type of elements in the Adjacent memory locations...

here we create the Array with 5 elements and here we create the loop control with the same name...so here conflict occur in variable names...so JVM will raise an erro sayinf i is already defined..in a method we cant have the 2 local variable with same name,wecan have same variables in different methods..

we can have the same variable names to the instance variables and local varaibles..we can differeniate using the this keyword..when we write normaly it will prefer local variable...if we use this than it will prefer instance varaible

Posted by Uday Kumar    2014-12-23 12:12:39


ans d. the Java VM has more lenient rules for variable naming than the Java language itself. For instances, a valid class file can have several variables named 'a', as long as they have different types. If you decompile such a class, the source code you get will not be valid. You cannot have variables having same name (but different type) to exist in the same scope. Consider if it was possible then how would the java compilr determine which one is correct. The java compiler cannot understand which x you are actually referring to. So such a code is not syntactically correct and not compilable.  It is a compile-time error for the body of a class declaration to declare.coming to this program ,here initially we defined array with 5 elements, array variable name we givn is i.thn for loop we again defined variable i,so compilr throws errors, java not allowed 2 variable with same name in same scope

Posted by Maheshwari Natarajan    2014-12-24 00:19:46


This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Maheshwari Natarajan,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Shubham Bansal. 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-24 03:57:11


© meritcampus 2019

All Rights Reserved.

Open In App