Incompatible types: possible lossy conversion from int to byte

I tried to code something for school but I keep getting this compilation error:

error: incompatible types: possible lossy conversion from int to byte

A = (byte)C / (byte)B;

System.out.println("Aufgabe 4");

byte A=11; int B, C;
B = A + A;
C = B * (int)1.0;
A = (byte)C / (byte)B;

Upvotes: 0

Views: 6665

Answers (5)

Divya Jha
Divya Jha

Reputation: 21

When we try to assign a variable of large-sized type to a smaller sized type, Java will generate an error, incompatible types: possible lossy conversion, while compiling the code.

When we perform arithmetic operation on primitive types smaller than Integer, Java automatically converts it into Integer. For larger primitives type does not change.

byte A=11; int B, C;    //line 1
A = (byte)C / (byte)B;  //line 2

In line 2(code mentioned above) right hand side is converted to Integer as division operation is performed on byte values. You can try below mentioned code:

Object obj = (byte)C / (byte)B;
System.out.println(((Object)obj).getClass().getName());

This will print java.lang.Integer.

To solve it you can cast whole result to byte:

A = (byte) (C / B);

Upvotes: 0

umar wani
umar wani

Reputation: 1

Type promotion in expression(study this topic)

Upvotes: 0

DCruz22
DCruz22

Reputation: 806

Your result is coming as an integer. You should cast it instead of the variables:

A = (byte) (C / B);

Upvotes: 0

Mark
Mark

Reputation: 1498

From the JavaSpec:

5.6.2 Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value of a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

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.

Meaning the following: (byte)C / (byte)B => Since you don't have double, float or long, both are converted to int. Which makes the result an int. And you can't call byte A = SomeInt; You must cast it again first.

So something like A = (byte)(C / B); would be better.

Upvotes: 2

AdamSkywalker
AdamSkywalker

Reputation: 11609

The reason is you do not cast integer result of division operation to byte:

A = (byte) C / (byte)B; // you cast C to byte, cast B to byte and then make division

Instead, cast only the result

A = (byte) (C / B);  // this is casting result to byte

Upvotes: 4

Related Questions