byte plus byte ?Automatically convert to int for all operands? - java

Here are codes,the last second row couldn't compile out cause of the result is int?So,can I
solve that every non integer type in java process as integer in arithmetic?
And I am learning English from all guys,thank you.
byte a=0;
for(int i=0;i<128;i++){
a=(byte)i;
}
byte b=1;
byte c=0;
c=b+a;
System.out.println(b);

Addition operation in java between two shorts or bytes happens after converting both the operands to int and results in an int. So you need to cast your result to byte as it is a lossy conversion. See this

You have to cast a or the result of the addition of a and b to a byte, since a is an integer and it's value might not fit into a byte.
Example:
c = (byte) ((byte) a + b);
or
c = (byte) (a + b);
This way, b gets implicitly converted to an integer, the result is then casted to a byte again.

Related

Cannot assign 128 to byte, why does it error out instead of overflowing?

Bytes in Java range from -128 to 127. If over 127 they overflow. So I assigned 128 to a byte variable to know how overflow work, but the compiler shows a error message: "Type mismatch: cannot convert from int to byte".
Why do I get a compiler error instead of it overflowing?
javac will let you assign values within range to bytes. When you go out of range, the value needs to be explicitly cast.
byte b = (byte)128;
Would work with the compiler. To see overflow you might try
byte b = 127;
b += 1;
System.out.println(b);
-128
The nuts and bolts can be found in the JLS. Java will do arithmetic as int, or long.
byte a = 1;
byte b = 2;
//byte c = a + b; //fails because the operation is performed as an int.
byte c = (byte)(a + b);
A byte is an 8-bit signed integer value that can hold values between -128 and 127.
You can cast 128 into a byte 'byte b = (byte)128;', but then b will just equal -128 because of how twos-complement numbers work.
Integer constants like 1, -32, 128, or 7654321 have int type in Java. Assigning an int value to a byte variable is simply not allowed. This is why you get the error cannot convert from int to byte. To get around it, you have to convert the int value to byte with a type cast, b=(byte)128.
The real question should be, why do you not get an error for this code?
byte b = 100; // !!!! ASSIGNING int TO byte !!!!
You don't get an error here because of this a special "assignment conversion" rule that only applies for compile time constant expressions:
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Type
byte B = (byte)128;
instead of byte B = 128;

Can we convert int to Byte using wrapper class, without type casting?

I was learning wrapper class, here I learned how to convert int to Interger wrapper class.
But I want to convert int to Byte using Byte wrapper class.
I have tried
int a =10;
Byte c = Byte; //(Not getting suggestion in eclipse)
for example, I know how to convert int to Interger refer code below.
int a =10;
Integer b = Integer.valueOf(a);
You could add an additional cast to the integer like this:
int a = 10;
Byte c = Byte.valueOf((byte)a);
Try it online.
Btw, going from a primitive to an Boxed value is done implicitly by the compiler. So the code above doesn't necessary need the .valueOf:
int a = 10;
Byte c = (byte)a;
Try it online.
But, when you're explicitly casting values, always keep in mind that it can hold unexpected results when doing it wrong. In this case for example, the size of a a byte is smaller than an integer (the range of a byte is [-128, 127] and of an int is [-2147483648, 2147483647]), so something like this wouldn't give the expected result:
int a = 200;
Byte c = Byte.valueOf((byte)a); // Results in -56
Try it online.
This is also the reason why you usually can't go to a smaller type, since it might not fit, but you can go to a larger one without needing the cast:
byte a = 10;
Integer c = Integer.valueOf(a);
Try it online.
int x=30;
Byte c = (byte)x; // Java has auto boxing for wrapper class Byte to byte and opposite automatically
You can cast the same way you normally do with Integer wrapper.
int a =10;
Byte b = Byte.valueOf((byte)a);
//b = 10
An int is 4 bytes. So you can't convert an integer to a byte without losing some data.
int a =1000;
Byte b = Byte.valueOf((byte)a);
//b = -24
You can, however, convert an int to an array of bytes.
Java - Convert int to Byte Array of 4 Bytes?
Same you can do for Byte too:
1. autoboxing
Byte b = (byte) a;
2. valueOf(byte b)
Byte b = Byte.valueOf((byte)a)
Returns a Byte instance representing the specified byte value. If a new Byte instance is not required, this method should generally be used in preference to the constructor Byte(byte), as this method is likely to yield significantly better space and time performance since all byte values are cached.
From JLS 5.0-2. Conversions In Various Contexts so you can't perform 5.1.3. Narrowing Primitive Conversion without cast operator.
// Casting conversion (5.4) of a float literal to
// type int. Without the cast operator, this would
// be a compile-time error, because this is a
// narrowing conversion (5.1.3):
int i = (int)12.5f;

Type promotion in Java [duplicate]

This question already has answers here:
Multiplying two bytes
(2 answers)
Closed 4 years ago.
I have a problem with the below Java statements:
byte b = 10;
byte r = (byte) (b * b); // Giving correct result
byte r = (byte) b * b; // Giving error " POSSIBLE LOSS OF PRECISION"
Why is it mandatory to give parentheses to b * b?
(byte) b * b casts the value of the first b to byte (which is redundant since it was already byte), and multiples it by the value of the second b. Multiplying two bytes promotes them to int first, since there is no * operator for bytes. Therefore the result is int, and cannot be assigned to a byte variable.
On the other hand, (byte)(b * b) casts the int multiplication result to byte, which can be assigned to a byte variable.
This is covered in the JLS in 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 that is convertible to a numeric type, the following rules apply, in order:
If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
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.
Casting problem
byte r = (byte) (b * b);
It casts the (byte) type to the result of (b * b)
byte r = (byte) b * b;
It casts the (byte) type to the first b only, therefore it will become ((byte) b) * b
By the precedence rule you are casting only the first b to byte instead of the whole result.
And Java follow some rules, as you can see here
All integer values (byte, short and int) in an arithmetic operations (+, −, *, /, %) are converted to int type before the arithmetic operation in performed. However, if one of the values in an arithmetic operation (+, −, *, /, %) is long, then all values are converted to long type before the arithmetic operation in performed.
So, by just casting the first b you are doing this:
byte = byte * integer
Hence:
byte = integer
Thus, raised error.
Variables of type byte must be [-128,127], that is why the compiler must not accept any operation, b*b;b+b;b-b;b/b without a cast on the result of operation, like: (byte)(b*b).
In the code below, when you change the result type to int it compiles.
byte b=10;
byte c=(byte)b*b; //incompatible but correct when c is int
byte d=((byte)b)*b; //incompatible but correct when d is int
byte r=(byte)(b*b);
byte t= b*b; //incompatible but correct when t is int
byte e=(byte)b/b; //incompatible but correct when e is int
byte f=((byte)b)/b; //incompatible but correct when f is int
byte o=(byte)(b/b);
byte w=b/b; //incompatible but correct when w is int
byte g=(byte)b+b; //incompatible but correct when g is int
byte p=((byte)b)+b; //incompatible but correct when p is int
byte q=(byte)(b+b);
byte x=b+b; //incompatible but correct when x is int
byte h=(byte)b-b; //incompatible but correct when h is int
byte v=((byte)b)-b; //incompatible but correct when v is int
byte s=(byte)(b-b);
byte y=b-b; //incompatible but correct when y is int
byte k=(byte)b;
byte u=b;
NOTE
As #andy Truner pointed out in comments, when b is final, all the previous instructions compile!!, except for the following set up:
final byte fn=-120;
byte z=fn-b; //this does not compile even when both final, because the result would be -130, out of the byte type interval!!

confusing in type conversion and giving unexpected result

public class Multicast {
public static void main(String[] args) {
System.out.println((int) (char) (byte) -2);
}
}
I am confuse about the type conversion and also giving unexpected result (it prints 65534, not -2 as expected).
The confusing result is due to the fact that char is an unsigned type. When -2 is converted to char, its bit representation becomes 1111111111111110 in binary, because two's complement representation is used. That representation becomes a positive 65534 when converted to decimal - the result you see printed by your program.
In Java, char is an unsigned type (and byte is a signed type). So (char)-2 is 65534. Then you widen that to be an int.
your confusion on the results of your code is partly due to sign-extension. I'll try to add a more detailed explanation that may help with your confusion.
char a = '\uffff';
byte b = (byte)a; // b = 0xFF
this DOES result in the loss of information. This is considered a narrowing conversion. Converting a char to a byte "simply discards all but the n lowest order bits".
The result is: 0xFFFF -> 0xFF
char c = (char)b; // c = 0xFFFF
Converting a byte to a char is considered a special conversion. It actually performs TWO conversions. First, the byte is SIGN-extended (the new high order bits are copied from the old sign bit) to an int (a normal widening conversion). Second, the int is converted to a char with a narrowing conversion.
The result is: 0xFF -> 0xFFFFFFFF -> 0xFFFF
int d = (int)c; // d = 0x0000FFFF
Converting a char to an int is considered a widening conversion. When a char type is widened to an integral type, it is ZERO-extended (the new high order bits are set to 0).
The result is: 0xFFFF -> 0x0000FFFF. When printed, this will give you 65535.

Byte typecasting in java

the program gives me loss of precision error but i cant think of any precision loss since numbers are small
This is the code ##
class Demo
{
public static void main(String args[])
{
byte b1=3;
byte b2=2;
byte b3=b1+b2;
System.out.println(b3);
}
}
The addition expression b1 + b2 is of type int - there aren't any addition operators defined on smaller types than int. So in order to convert that back to a byte, you have to cast:
byte b3 = (byte) (b1 + b2);
Note that although you happen to know that the values are small, the compiler doesn't care about the values you've set in the previous two lines - they could both be 100 for all it knows. Likewise although you know that the int you're trying to assign to a byte variable is only the result of adding two byte values together (or rather, two values promoted from byte to int), the expression as a whole is just int and could have come from anywhere as far as the language is concerned.
(The fact that the addition can overflow is a separate matter, but that would be an inconsistent argument - after all, you can add two int values together and store the result in an int variable, even though the addition could have overflowed easily.)
Because 127 is the last value of byte.
Assume b1 = 127 and b2 = 2
now what happends b = b1+b2 = 129 [which is out of byte range, i.e. it's in int range]
now if you cast it b = (byte)(b1+b2), you will get -127 this is due to rounding of the value to byte.
byte b1=3;
byte b2=2;
byte b3=b1+b2; // you can't use byte here, Every time addition will result
int value
Because, If you trying to cast an int which is larger than byte range, there is a loss part of that value. So addition will not allow to use byte here.
when ever you do +,-,*,/,%
java internally uses a function
ex: max(int,dataType of operand 1,dataType of operand 2);
here in your code
max(int, byte,byte) ==> which one is bigger ? ==> int is bigger
so you may get POSSIBLE LOSS OF PRESSION
found :int
required : byte
Another Example
short a =10;
byte b=20;
short c = a+b;
now:
internally: max(int,OP1,OP2);
ie max(int,short,byte) ==> which is bigger Data Type? int
so java excepts int
int c = a+b; (works fine)
Another Example :
long a =10;
byte b=20;
short c = a+b;
now:
internally: max(int,OP1,OP2);
ie max(int,long,byte) ==> which is bigger Data Type? long
so java excepts long
long c = a+b;(works fine)
Another Example:
byte b = 10;
b = b+1;
now,
max(int,byte)==> which is bigger Data Type ? int
so,
int c = b+1;(works fine) or b = (byte) b+1;
hope you understand

Categories

Resources