aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can default value of char be used as an index of array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "can default value of char be used as an index of array?" Watch "can default value of char be used as an index of array?" New topic
Author

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

Angela Xia
Greenhorn

Joined: Jan 03, 2002
Posts: 10
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


Angela
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
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


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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.


SCJP2. Please Indent your code using UBB Code
Angela Xia
Greenhorn

Joined: Jan 03, 2002
Posts: 10
Thank you all!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can default value of char be used as an index of array?