This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array element

 
Rob Petterson
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Brusk Baran
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 7319
45
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu, can you tell me why/how the char val is imlicitly promoted to an int please?
 
Francisco A Guimaraes
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rob Petterson
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tahnks Francisco, it's clear now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic