Win a copy of Machine Learning with R: Expert techniques for predictive modeling this week in the Artificial Intelligence and Machine Learning forum!
  • 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
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

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: 4351
39
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In other words, casting operator has higher precedence than + operator
 
All of the following truths are shameless lies. But what about this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!