• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can default value of char be used as an index of array?

 
Angela Xia
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
uestion ID :1003502809546
What will the following program print?
public class TestClass
{
static boolean b;
static int[] ia = new int[1];
static char ch;
static boolean[] ba = new boolean[1];
public static void main(String args[]) throws Exception
{
boolean x = false;
if( b )
{
x = ( ch == ia[ch]);
}
else x = ( ba[ch] = b );
System.out.println(x+" "+ba[ch]);
}
}
answer : false false
My question is: the index of an array should be int, so can char value be used in ba[ch] ? I chose the code will not compile because of this thinking. Thanks
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
values for char range from 0 to 65535 so they are acceptable values for array indexes. the char is first promoted to an int, though.
HIH
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from JLS 10.4
Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (�5.6.1) and become int values. An attempt to access an array component with a long index value results in a compile-time error.
 
Angela Xia
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic