• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

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

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you all!
reply
    Bookmark Topic Watch Topic
  • New Topic