• 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

OCP Certification Q  RSS feed

Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
  I a just have a simple q regarding the following:

The bit that interests me is that (char)'0' prints 0 and not 48. Yet when I switch on ii (set to '0') I get the label for 48 - which is what I was expecting. Single quotes around a letter/digit translates into the ASCII value. On the JavaDocs it says "a switch statement tests expressions based only on a single integer, enumerated value, or String object.". So I suspect there is an implicit cast in the background for the case labels i.e. the char ii is upcast to an int?
However, I am still not sure why (char)'0' just didn't output the ASCII also?

Posts: 63795
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look in the Java® Language Specification (=JLS), you will find that your cast is called an identity conversion, whihc always succeeds, and you will see that is a reminder of what type you ahve already. If you look up the different overloadings of the println() method (e.g. PrintStream.#println(char), you will find that behaves like the write() method, and the char is converted by the system's default character encoding. There is therefore no difference between println(c) and printn((char)c) if c is a char all along. So in both cases the character 0 is displayed, not the number 48.
Now, what happens if you try System.out.println(+c);?
The classic (Java1.0‑Java1.4.2) form of the switch statement implicitly casts its arguments and labels to ints. So you can mix chars and ints as long as the casting goes the right way. Write a class with one method containing a switch not using enums nor Strings. Use ints or chars. Compile it: javac SwitchDemo.java and inspect the bytecode with javap -c SwitchDemo You will see the lookup table uses only ints.

Please avoid abbreviations like Q. Please always tell us whenever you copy code, to reduce copyright problems. Most of what you showed looks like our own code, however.
passwords must contain 14 characters, a number, punctuation, a small bird, a bit of cheese and a tiny ad.
global solutions you can do in your home or backyard
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!