• 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
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

Arithmetic promotion

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Simon Roberts in his book Java @ certification guide mentions with refernce to Unary operators that
There are 2 rules that apply depending on the type of the operand
1)If one of the oprtnad is a byte, a short or a char,itis converted to an int
using this rule the code given below when compiled should give a type mismatch error as converting an int to a char requires a cast.Surprisingly not only does this code compile but when it is run,The output is - The character is now b
Why does this hapen ?
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
These operators use the native CPU increment or decrement which is unsigned. You will note a similar operation using byte does not require a cast.

However, this topic is unrelated to the assignments here in the cattle drive so I am moving it to Java In General (Beginning)
 
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I don't think char is actual converted to a int during any arithmetic operation.
According to Peter van der Linden in Just Java 2 page 96,
char is an integer-based type with all arithmetic operators available. The code above will first produce an 'a' since x is assigned 97 (the decimal value of 'a' in the ASCII table).
The char casting for x is required since char is a unsigned 16-bit type and int is a signed 32-bit type so the result of the assignment will be smaller. If y is then cast to int it will print 97. Any arithmetic done to y is performed as if y were an integer(char is a integer-base type).
Hope this is right, makes sense and helps.
 
reply
    Bookmark Topic Watch Topic
  • New Topic