Hong
Hong

Reputation: 18521

How can a Java byte variable be 128?

I probably miss some fundamental understanding of byte in Java. The following is a simplified excerpt from an app to illustrate the problem:

public class Foo
{
 byte b1;
 byte b2;
 byte bProblem;
}

foo is an instance of Foo. The following has puzzled me for hours:

Log.d("Debug", "Before: " + String.valueOf(foo.bProblem));
if (foo.bProblem != (byte) 0x80) {
    foo.bProblem = (byte) 0x80;
    Log.d("Debug", "After: " + String.valueOf(foo.bProblem));
}

LogCat shows the following:

03-17 21:58:46.590: D/Debug(2130): Before: 128    
03-17 21:58:46.590: D/Debug(2130): After: -128

Eclipse's debugger always shows -128 (0x80) for foo.bProblem. This means the debugger cannot see what String.valueOf() reveals. How can a Java byte be 128?

I noticed this when adding foo.bProblem to a List caused: Java.lang.ArrayIndexOutOfBoundsException: length=256; index=256

Could anyone offer some hint for me to understand this?

Edited:

I found later this happens only on an Intel Android emulator as I wrote in my comment following Joop's answer.

Upvotes: 2

Views: 2251

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109603

In the java virtual machine, the byte field bProblem will use an int. Now, String.valueOf(int) is used, as there is no byte variant. So (erroneously?) the field is taken as int, so unsigned, 128.


Sorry, I tried to achieve a 128 but did not succeed (Java 7, Linux)

I already became paranoid, you using a child class with an int field bProblem. Or more likely a compiled class being used with a java source not up-to-date compiled. Maybe you could try another compiler than that of eclipse.

Upvotes: 4

ToddR
ToddR

Reputation: 800

A Java "byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)." So when you assign a byte to +128 it essentially wraps back around to the lowest value of -128

See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for details.

Upvotes: 4

bclymer
bclymer

Reputation: 6771

String.valueOf does not take a byte, it takes one of the following:

boolean char char[] double float int long Object

In your implementation you are actually calling String.valueOf(int value) It does not actually contain the value of 128. Try printing

Log.d("Debug", "" + bProblem)

That should work.

EDIT--

What I'm trying to say is that String.valueOf is not actually looking at the value of the byte. It's looking at the same bits that make up the byte as an int and printing that.

Upvotes: 4

Related Questions