• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

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

 
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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • 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
 
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!
 
You are HERE! The other map is obviously wrong. Better confirm with this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic