Why i don't get an error? [duplicate] - java

This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 5 years ago.
In Java if I do the following I get an error
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
Ok I understood why I got that error .
But now if I do b*=2 I don't get any error. Why?

Because when you make b *= 2; in fact this operation *= will cast your int to byte.

The reason is simply because there are different rules for narrowing conversions for = and *=.
See here for details on widening in general; and then you go here to understand the difference for those *= operations.
You, see
b *= 2
works out as
b = (byte) ( (b) * 2 )
and that narrowing conversion doesn't play a role here.

Related

Assigning int to byte in java [duplicate]

This question already has an answer here:
Implicit narrowing when summing constants vs explicit narrowing when summing variables
(1 answer)
Closed 1 year ago.
In java, it is fine to have:
byte b = (int) 2;
where java automatically convert int to byte. On the other hand, if we do:
int a = 2;
byte b = a;
this will give an error saying that the required type is byte but int is provided.
May I ask how to understand the reason why automatic conversion works when literal number of type int is assigning to a variable of type byte while it doesn't work when the literal number is replaced by a variable of type int?
Thanks in advance!
It is fine to have
byte b = (int) 2;
Because 2 is casted into int and than it is the same as
byte b = 2;
The following also works
int a = 2;
byte b = (byte) a;

Why plus operator in Java always produces Integer? [duplicate]

This question already has answers here:
Promotion in Java?
(5 answers)
short plus short is an int [duplicate]
(2 answers)
Closed 9 years ago.
I have code like this
short a = 1;
short b = 2 ;
short c = a + b; // dosen't compile
What is the reason for compilation failure? x + x always produces Integer or bigger Number, but why?
None of the binary operators will produce an Integer. However, it will use an int instead of shorter types, byte, short and char If the compiler can inline the value it can cast the value for your. e.g.
final short a = 1;
final short b = 2;
short c = a + b; // does compile, because of constant inlining.
The only operator which produces an Integer is a cast.
Integer i = (Integer) 1;
BTW: On oddity is that Java defines the 32-bit float as being "wider" than the 64-bit long value. This has the downside that float has much less precision. Consider this.
long l = 7777777777777777777L;
l += 0.0f;
System.out.println(l);
prints
7777777579364188160
Even though 0.0F was added to l it was implicitly cast to float (as float is wider) and then cast back (as an operator assignment was used) resulting in a error of ~20 billion.

Java int += double syntax surprise [duplicate]

This question already has answers here:
Varying behavior for possible loss of precision
(1 answer)
Why does Java perform implicit type conversion from double to integer when using the "plus equals" operator? [duplicate]
(2 answers)
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 9 years ago.
I have run into the following surprising line:
int x = 7;
x += 0.5;
is apparently legal syntax! After the addition, x is still 7, so the double is being cast to an int and rounded down to 0, but this is done without any explicit cast in the code. Is anyone else surprised by this? What's the rationale here?
edit to clarify my question: Can anyone give a good reason for this decision? It strikes me as a terrible decision to require explicit casting everywhere else, but have this one spot in the language where you silently throw away data. Am I missing something?
x += 0.5;
is equivalent to:
x = (int) (x + 0.5)
In general:
x += y is equivalent to x = (type of x) (x + y)
See 15.26.2. Compound Assignment Operators
x += 0.5; is the same as x = (int) (x + 0.5);.
This is because compound assignment operators puts an implicit cast (automatic cast):
So
x+=0.5 => x =(int)(x + 0.5) => x = (int)(7.5) => x = 7

Byte arithmetic: How to subtract to a byte variable? [duplicate]

This question already has answers here:
Promotion in Java?
(5 answers)
Closed 9 years ago.
I'm getting an error when I'm trying to do somethink like this:
byte a = 23;
a = a - 1;
The compiler gives this error:
Test.java:8: possible loss of precision found : int required: byte
a = a - 1;
^
1 error
Casting doesn't solve the error...
Why the compiler don't let me do it?
Should I need to transform the variable 'a' into an int?
Do like this.
a = (byte)(a - 1);
When you subtract 1 from a then its integer value. So to get assign the result in byte you need to do explicit type casting.
In Java math, everything is promoted to at least an int before the computation. This is called Binary Numeric Promotion (JLS 5.6.2). So that's why the compiler found an int. To resolve this, cast the result of the entire expression back to byte:
a = (byte) (a - 1);
a = a - 1; // here before subtraction a is promoted to int data type and result of 'a-1' becomes int which can't be stored in byte as (byte = 8bits and int = 32 bits).
Thats why you'll have to cast it to a byte as follows :
a = (byte) (a - 1);
Do this:
a -= 1;
You even don't need explicit cast, compiler/JVM will do it for you.
Should you change the variable type to int nobody can say, having only information you provided.
A variable type is defined by the task you are planning to perform with it.
If your variable a counts fingers on someone's hands, why would you use int? Type byte is more than enough for that.

Java implicit casts that can lead to precision or magnitude loss? [duplicate]

This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 5 years ago.
I recently learned, while converting some Java code to C#, that Java's increment operator '+=' implicitly casts to the type of LHS:
int i = 5;
long lng = 0xffffffffffffL; //larger than Int.MAX_VALUE
i += lng; //allowed by Java (i==4), rejected by C#
is equivalent to: (details here)
int i = 0;
long lng = 0xffffffffffffL;
i = (int)(i + lng);
thus silently causing the opportunity for loss of magnitude.
C# is more conscientious about this at compile-time:
Cannot convert source type long to target type int.
Are there other similar situations allowed by Java?
A long can be promoted to a float or double, which results in a loss of accuracy:
public static void main(String[] args) {
float f = Long.MAX_VALUE;
double d = Long.MAX_VALUE;
System.out.println(Long.MAX_VALUE);
System.out.println(f);
System.out.println(d);
}
prints
9223372036854775807
9.223372E18
9.223372036854776E18
I suspect C# does this the same way, though.
Aside from the compound assignment operators you already mentioned, I believe those to be all cases where an implicit conversion can change the value.

Categories