• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Assignment

 
R Kumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all. I came across the following code in one of the mock tests

public class Testing123 {

public static void main(String... args)
{
Number[]na = new Integer[3];
System.out.println(na[0]);
}
}

a)0
b)some garbage
c)3
d)compilation fails

the correct answer is supoosed to be compilation fails but when i tried this code it simply works fine and prints null..

could anyone tell wots wrong?
 
B Misra
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

As far as i know this looks completely fine & should print null.(I'm new here though & this is my first post )

When the array of objects is constructed the individual elements get default null.
[ July 27, 2007: Message edited by: B Misra ]
 
James Hambrick
Ranch Hand
Posts: 282
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see anything wrong with it either, the public static void main(String... args) looks a little funny having the ....

What version of JDK are you using. The exam is for 1.4 and if you are using 1.5 then some example may work when they are not supposed to. I heard on here somewhere to make sure and use the version JDK that you are testing for.
 
B Misra
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question should be of some scjp5 exam itself, cause otherwise the var-arg declaration would not have been there & even if the main declaration have been wrong (it is right here) it would not have had produced any compilation error.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're just right it will print null.

Normally the System.out.println(object) will print the value object.toString() which will go wrong because there is no object. It's a null-reference.

but when the value of the reference is null the method will just print null.

You will get an error if you change the code like this.

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15459
42
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that with Remko's change (adding toString()) you will not get a compiler error; a NullPointerException will be thrown at runtime because you are trying to call a method on a null reference.
 
R Kumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all. This question is from the John Meyer's mock exam for scjp5. I guess there is some mistake in the question itself because the null option has not even been specified
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic