Java Programming - Declarations and Access Control - Discussion

9. 

What will be the output of the program?

public class ArrayTest 
{ 
    public static void main(String[ ] args)
    { 
        float f1[ ], f2[ ]; 
        f1 = new float[10]; 
        f2 = f1; 
        System.out.println("f2[0] = " + f2[0]); 
    } 
}

[A]. It prints f2[0] = 0.0
[B]. It prints f2[0] = NaN
[C]. An error at f2 = f1; causes compile to fail.
[D]. It prints the garbage value.

Answer: Option A

Explanation:

Option A is correct. When you create an array (f1 = new float[10];) the elements are initialises to the default values for the primitive data type (float in this case - 0.0), so f1 will contain 10 elements each with a value of 0.0. f2 has been declared but has not been initialised, it has the ability to reference or point to an array but as yet does not point to any array. f2 = f1; copies the reference (pointer/memory address) of f1 into f2 so now f2 points at the array pointed to by f1.

This means that the values returned by f2 are the values returned by f1. Changes to f1 are also changes to f2 because both f1 and f2 point to the same array.


Ayas said: (Oct 20, 2012)  
Local variable has to be initialized other than it gives compile time error.

Shadab Khan said: (Sep 27, 2015)  
As array declared in java they first form its object. How its possible to refer one object to other, pointer IC not allowed.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.