Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incompatible types error Java between short and int. Unsure of cause

In the following code I have an error "possible loss of precision found : int required: short". I understand what the error means but I'm just wondering why I'm getting it. Surely the function should return a type of short (I can't see how there could be any loss of precision, the code should return a 16 bit integer). Can anyone clear up for me why the following code seems to require the type int?

static short a() {
    short[] payload = {
            100, 200, 300,
            400, 500, 600,
            700, 800, 900, 1000
    };
    short offset = 2;
    return (payload[offset - 2] << 8 & 0xff00) + (payload[offset - 1] & 0xff);
}

Thanks!

like image 888
xcvd Avatar asked Apr 14 '12 22:04

xcvd


People also ask

How do I fix incompatible type error?

Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b). Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4].

How do you fix a string that Cannot be converted to int?

The most direct solution to convert a Java string to an integer is to use the parseInt method of the Integer class: int i = Integer. parseInt(myString); parseInt converts the String to an int , and throws a NumberFormatException if the string can't be converted to an int type.

Can short be negative Java?

Short values are stored in 2 bytes and contains positive or negative integer numbers.

What is type error in Java?

There are three types of errors in java 1.Compile-time errors. 2.Run time errors. 3.logical errors.


1 Answers

Java arithmetic operations on short always return int, partly to help prevent overflow, and partly to reflect the underlying JVM bytecode, which doesn't distinguish between arithmetic operations on int, short, or byte. But basically, (payload[offset - 2] << 8 & 0xff00) is an int, and it wants you to cast it back down to a short.

like image 85
Louis Wasserman Avatar answered Oct 27 '22 11:10

Louis Wasserman