wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array element Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array element" Watch "Array element" New topic
Author

Array element

Rob Petterson
Ranch Hand

Joined: Jan 23, 2002
Posts: 149
public class Default {
static boolean [] ba = new boolean [1];
static char ch;
public static void main (String []args){
System.out.println(ba[ch]);
}
}
Why does it print false?
I didn't think that the default of char '\u0000' which is unicode for null would be an suitable array element for a boolean array.


Rob Petterson
SCJP
Brusk Baran
Ranch Hand

Joined: Nov 15, 2001
Posts: 132
Instance variables :
chars are instantiated to �\u0000'� automatically..
and booleans to false , the same way..
Arrays' elements are automatically instantiated always( instance or automatic does not differ)
if array elements are Objects then --> null
primitives are behaved the same way as the instance primitives.
ps: null IS NOT THE SAME AS '\u0000'
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 5298
    
  10

The char will be implicitly promoted to an int. Since chars are initialized to '\u0000' it has the equivalent int value of 0. That's why you get the value of the first array element which was initialized to false.
Note that if you initialize the char to anything else, say '\u0001', you will get a RuntimeException (ArrayIndexOutOfBoundsException).
Rob Petterson
Ranch Hand

Joined: Jan 23, 2002
Posts: 149
Junilu, can you tell me why/how the char val is imlicitly promoted to an int please?
Francisco A Guimaraes
Ranch Hand

Joined: Mar 20, 2002
Posts: 182
From the JLS 15.13 - Array Access Expressions:

The index expression undergoes unary numeric promotion (�5.6.1); the promoted type must be int.
�5.6.1:
If the operand is of compile-time type byte, short, or char, unary numeric promotion promotes it to a value of type int by a widening conversion

so, since the index is a char, it is promoted to an int and '\u0000' becomes 0.
Francisco
[ June 14, 2002: Message edited by: Francisco A Guimaraes ]

Francisco<br />SCJP<br />please use the [code][/code] tags when showing code.Click <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=ubb_code_page" target="_blank" rel="nofollow">here</a> to see an example.
Rob Petterson
Ranch Hand

Joined: Jan 23, 2002
Posts: 149
Tahnks Francisco, it's clear now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array element