Full byte type cast

Asked

Viewed 498 times

3

I have the following code:

public class Principal {
     public static void main(String[] args){

      int i = 10;
      byte b = 5;
      b = (byte)i;
      b += i;
      i = b;

      System.out.println( i );
      }
}

I know the value returned in b = 20.

But why? I would like to understand what happens when I put the cast(byte) in the int.

Question 127 page 4 contest

  • 1

    Questão 127 do concurso, coincidentally, the maximum possible value to store in the byte :D

  • @Bia, I updated my answer based on the issue you asked the question.

  • @Bia what does this "judge" mean? Is it to say what you think of each statement? It is to say if she is wrong?

  • @bigown judge whether the statement is correct or not.

4 answers

4


Before answering the question itself, it is important to mention that this instruction byte b = 5 is not changing the result at all. It could have been done directly byte b = (byte)i.

About the result, it is necessary to understand the types involved in the question, especially the type byte.

In Java, the type byte has signal size and 1 byte, therefore 8 bits. Using 8 bits it is possible to map 256 characters, in this case, integers. Since the variable has signal, then the interval goes from [-128,127].

That said, if the whole you’re doing cast for byte is in this range, then it will be printed correctly, if it is not, an overflow will occur in the type variable byte and what will be printed will be a number in that interval, but not the int to which you are doing cast.

Look at this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Updating

The question was significantly changed which made me edit the answer.

The result was not 10 as mentioned earlier, but 20, since a sum of b+=i after the cast. However, this does not change the explanation, since 20 is a number that is in the range of one byte in Java.

3

Whenever a cast is made from a numeral to byte type, understand the bits that are involved, in the case of your example happens this:

00000000 00000000 00000000 00001110 00001110

It will simply discard everything left that is beyond the first byte. Note also that the Java byte has signal, so the first bit helps to identify the signal.

And on your example of code, run in whatever version of java you are, the result will always be 10 as well. This generates a very strange behavior, because, for example, 127 in int is 127 in byte, but 128 in int is -128 in byte.

I recommend experimenting with bit shift commands to better understand how data structure works at the bit level.

3

Note that the original question gives a misleading hint of what was actually asked in the contest. Now it’s not very accurate either. In anything, but especially in contests it is essential to have precision in the interpretation or communication of what the problem is. Otherwise errors will occur because of communication failure more than lack of knowledge.

In the case the statement of question 127 is true. 20.

int i = 10; // i está valendo 10
byte b = 5; // b está valendo 5
b = (byte)i; // agora b passa valer 10, o cast não o afeta, dentro dentro da capacidade do tipo
b += i; //agora b vale o seu próprio valor mais o de i, então 10 de b e 10 de i = 20
i = b; // agora i passa ter o mesmo valor de b, ou seja, 20.

I put in the Github for future reference.

The cast did not affect at all the value. It could have affected if the value i was out of the range accepted by the type byte (-128 to 127). The same applies to the addition of the value of i in b. The value of i that has 4 bytes of storage "fit" inside b which has only 1 byte. The type byte 256 distinct numbers (2 to 8) while the type int (from -2.147.483.648 to 2.147.483.647 4.294.967.295 - 2 to 32).

  • Importantly, the sum of the integer in the byte also did not affect since the bits of the integer did not pass the byte limit, nor did it use the last bit that is used for byte negative.

  • @Darkhyudra true, I’ve improved, thank you.

0

If we run the code below:

public class HelloWorld{
    public static void main(String []args){
        int i = 10;
        byte b = 5;
        b = (byte) i;
        System.out.println(b); // esta linha irá imprimir 10
     }
 }

The value "10" will be printed. Because it is a value that fits in a byte type variable. But if I change the code to:

public class HelloWorld{
    public static void main(String []args){
        int i = 300;
        byte b = 5;
        b = (byte) i;
        System.out.println(b); // esta linha não irá imprimir 10
     }
 }

300 will not be printed. It is a value that does not fit in a variable of this type.

If you look at the Java documentation : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

you will see that the byte is an integer data type but quite limited. It accepts values from -128 to 127. That is, values outside this margin will be lost.

  • 1

    And what will print the last System.out.println(b);? I was curious :P

  • in the example I used prints 44. See @Darkhyudra’s reply that it explains why this happens

Browser other questions tagged

You are not signed in. Login or sign up in order to post.