• Post Reply Bookmark Topic Watch Topic
  • New Topic

byte behavior vs integer behavior  RSS feed

 
Ramniv Lenisov
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I coded the following:
byte byteOne, byteTwo;
int intOne, intTwo;
byteOne = 1;
byteTwo = byteOne + 1; //compile error
intOne = 1;
intTwo = intOne + 1; // no compile error
why the difference between the two?
Please help
 
Jean-Francois Briere
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the statement:
byteTwo = byteOne + 1;
there is an automatic casting of byteOne to ant int, and the result of the addition is an int.
So when the int is assigned to a byte, there may be a loss of information (from 4 to 1 bytes).
To make it compile, just cast the result of the addition:
byteTwo = (byte)(byteOne + 1);
 
Ayukawa Madoka
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jean-Francois Briere:
In the statement:
To make it compile, just cast the result of the addition:
byteTwo = (byte)(byteOne + 1);

is this the method that adds the two byte values and unifies the result into byte instead of int?
 
Gabriel White
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, this is the method. By telling Java we want to change the type temporarily: byteTwo = (byte)(byteOne + 1); This says we want the value of byteOne+1, but represented as a byte.
HTH
Gabe
 
Davy Kelly
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you have a aritmetic problem like this and you know that it will fit into a byte, what you have to do is cast it back to a byte.

hope this helps.
Davy
[ March 05, 2004: Message edited by: Davy Kelly ]
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that for a long, you can do
long longOne = 5;
long longTwo;
longTwo = longOne + 1L;
Can you do something similar for byte, such as
byteTwo = byteOne + 1B;
?
Layne
 
Jean-Francois Briere
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Can you do something similar for byte, such as
byteTwo = byteOne + 1B;
?

In JAVA, when you have an operation upon a pair of operands:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.
 
Ramniv Lenisov
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot everyone, for your inputs. I got it now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!