• 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
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Casting Primitives - Parentheses

 
Greenhorn
Posts: 12
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I can’t remember where I saw this code but I don't remember it giving me a reason why something didn’t compile.
I understand that when we use arithmetic operators in Java, it will promote short data types, like byte, short & char to an int first then do the operation.
And we need to use explicit casting when going a larger data type to a smaller data type.
With the code below, we assign the byte and add a and b, why doesn’t c compile?
As in, why do we need parentheses around the a + b?



Thanks in advance.
 
Greenhorn
Posts: 19
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
On line 3 variable a is first cast to byte and then the add takes place. Since the result of adding a and b is promoted to int this will not compile.
At line 4 you first add a and b and the result of this is then cast to a byte.
 
Enthuware Software Support
Posts: 4318
35
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In other words, casting operator has higher precedence than + operator
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!