Friday, August 6, 2010

Multi-dimensional Arrays: Comp2.java

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 4, Exercise 2

Given


And the following five code fragments

F1. if(f1 == f2)

F2. if(f1 == f2[2][1])

F3. if(x == f2[0][0])

F4. if(f1 == f2[1,1])

F5. if(f3 == f2[2])

What is true:

A. One of them will compile, only one will be true 
B. Two of them will compile, only one will be true 
C. Two of them will compile, two will be true 
D. Three of them will compile, only one will be true 
E. Three of them will compile, exactly two will be true 
F. Three of them will compile, exactly three will be true

Answer is D:

F1. if(f1 == f2)

This is a type mis-match because f1 is a float and f2 is a two-dimensional array that holds floats

F2. if(f1 == f2[2][1])

This compiles and runs

F3. if(x == f2[0][0])

This compiles, runs, and evaluates to TRUE. x is unboxed and evaluated against f2[0][0]

F4. if(f1 == f2[1,1])

f2[1,1] is incorrect syntax to access an element in a two-dimensional array

F5. if(f3 == f2[2])

Compiles and runs. This is a comparison between a single element, f3, and a single element of a two-dimensional array. Or rather, a comparison between two memory references, each which point to a single element of type float.

Below is code to help further understanding of this concept




















Below is the output
Is f3 == f2[2]?
false
f3 is [F@1bc4459
f2[2] is [F@12b6651
Assign f2[2] to f3
Is f3 == f2[2]?
true
f3 is [F@12b6651
f2[2] is [F@12b6651

No comments:

Post a Comment