• Post Reply Bookmark Topic Watch Topic
  • New Topic

Loss of Precision  RSS feed

 
Marianne Rivera
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am reading head first java and I am trying to understand one question regarding this line.

Q: Do i have to return the exact type I declared?

A: You can return anything that can be be implicitly promoted to that type. So you can pass a byte where an int is expected. The caller won't care, because the byte fits just fine into he int the caller will use for assigning the result. You must use an explicit cast when the declared type is smaller than what you're trying to return.


So I tried to verify this by doing a simple program so that I will learn faster.



But when I tried to compile this java file using javac, it says possible loss of precision , found int required byte.

I thought I could return a byte when an int is expected because a byte can fit perfectly on an int type.

Kindly help me understand this as I am new to Java in general and just started learning.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

Arithmetic operations aren't carried out with "byte" operands, but with "int" or "long" operands. So in this case the "byte" values are promoted to "int", giving an "int" result of the addition. When trying to assign that to "byte Sum", the error occurs. If you're certain that the result will fit into a "byte" -as it would in this case- you can cast the result to "byte":

byte Sum = (byte) (numOne + numTwo);
 
Marianne Rivera
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sir,

I do not know yet about this rule in java arithmetic but certainly would like to thank you for letting me know the reason behind the error.

I will just continue to learn and hopefully would progress even more as I read this book.

I love this book though.. full of colors and pictures, I sometimes think that this book isnt something to be taken seriously but I am learning..

..... I think..
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that book is meant to be taken seriously. It is specifically designed for beginners, hence the many pictures.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!