简体   繁体   中英

Type casting needed with byte datatype when doing addition?

I have the problem with following code:

     byte b=34;  //successfully compiled
     b=b+10;     //compile time error
     int x=34;   //success
     b=x;        //compile time error

Why is b=34 compiled successfully, while integer literal is by default int but b=x gives compile time error while x is int ?

The problem is that byte b is a byte of 8 bits and int x is a 32 bits integer value.

Therefore, your code b=b+10 can be translated as

b = 00100011b + 00000000000000000000000000001010b;

As you can see, the JVM will cannot force byte b to an int (by shoving 32 bits value into an 8 bit registry), so there's type incompatibility, if typecasting is not done (the same applies for b=x ).

With out casting it's not possible, see The Elite Gentleman answer.

do casting this way

byte b=34;
b=(byte)(b+10);
int x=34;
b=(byte)x;

due to possibly loss of precision you should code as follows

 byte b=34;
b=(byte)(b+10);
int x=34;
b=(byte)x;

In your code-snippet the b=x; is not assignable .

From the JLS 5.2 Assignment Conversion .

If the type of the expression cannot be converted to the type of the variable by a conversion permitted in an assignment context, then a compile-time error occurs.

Narrowing primitive conversion may be used if all of the following conditions are satisfied:

  1. The expression is a constant expression of type byte, short, char or int.
  2. The type of the variable is byte, short, or char.
  3. The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

When you add int to byte , the byte will be implicitly converted into int but the conversion int to byte will not be done implicitly, it should be done explicitly.

byte b=34;
b=(byte)(b+10);
int x=34;
b=(byte)x;

Because integer datatype can hold much bigger values than byte and there is no trivial rule to convert int yo byte.

In your case:

b = (byte)x;

will help,

well byte range is -128 to 12y so you are able to set the value in the while the arithemetic operation you need to convert that byte to integer bcoz it will consider as integer value not as byte value.

you can't directly type cast from integer to byte bcoz integer size is larger than the byte that's why you getting compile time error

check this link for result how the effect on conversion from integer to byte How does Java convert int into byte?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM