aspose file tools*
The moose likes Beginning Java and the fly likes Arithmetic promotion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arithmetic promotion" Watch "Arithmetic promotion" New topic
Author

Arithmetic promotion

dhruv simaria
Greenhorn

Joined: Mar 26, 2001
Posts: 6
Simon Roberts in his book Java 2 certification guide mentions with reference to Unary operators that
There are 2 rules that apply depending on the type of the operand
1)If one of the operand is a byte, a short or a char,it is 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 ?

[This message has been edited by dhruv simaria (edited March 27, 2001).]
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9052
    
  12
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)


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Richard Boren
Ranch Hand

Joined: Mar 01, 2001
Posts: 233

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.
 
 
subject: Arithmetic promotion