File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Arithmetic promotion

dhruv simaria

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

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

"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.
I agree. Here's the link:
subject: Arithmetic promotion
It's not a secret anymore!