I've found that java compile has a non-expected behavior regarding assignment and self assignment statements using an int and a float.
The following code block illustrates the error.
int i = 3;
float f = 0.1f;
i += f; // no compile error, but i = 3
i = i + f; // COMPILE ERROR
In the self assignment i += f the compile does not issue an error, but the result of the exaluation is an int with value 3, and the variable i maintains the value 3.
In the i = i + f expression the compiler issues an error with "error: possible loss of precision" message.
Can someone explain this behavior.
EDIT: I've posted this code block in https://compilr.com/cguedes/java-autoassignment-error/Program.java
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2
The Java Language Specification says:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
So i += f is equivalent to i = (int) (i + f).
i believe that the explicit i+f fails because of Narrowing primitive conversion. While in the first case the conversion on the right side passes because it is done according to Compound Assignment rules.
Related
Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5;
long j = 8;
Then i = i + j; will not compile but i += j; will compile fine.
Does it mean that in fact i += j; is a shortcut for something like this
i = (type of i) (i + j)?
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
An example cited from §15.26.2
[...] the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
In other words, your assumption is correct.
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'
Very good question. The Java Language specification confirms your suggestion.
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
Yes,
basically when we write
i += l;
the compiler converts this to
i = (int)(i + l);
I just checked the .class file code.
Really a good thing to know
you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like
i = i + (int)l;
or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
The problem here involves type casting.
When you add int and long,
The int object is casted to long & both are added and you get long object.
but long object cannot be implicitly casted to int. So, you have to do that explicitly.
But += is coded in such a way that it does type casting. i=(int)(i+m)
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
Sometimes, such a question can be asked at an interview.
For example, when you write:
int a = 2;
long b = 3;
a = a + b;
there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.
So to avoid it, you must write your code like this:
int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting
The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do
int a=5;
long b=10;
a+=b;
System.out.println(a);
What you're really doing is:
int a=5;
long b=10;
a=a+(int)b;
System.out.println(a);
Subtle point here...
There is an implicit typecast for i+j when j is a double and i is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j where i is an integer and j is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j to (int) in this case for clarity.
Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.
This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 6 years ago.
This Java code
public class test{
public static void main(String[] args){
byte[] a = new byte[1];
a[0] = 1;
byte x = 1;
x = x + a[0];
System.out.println(x);
}
}
throws the following compile error:
test.java:10: possible loss of precision
found : int
required: byte
byte y = x + a[0];
^
1 error
huh? What is going on here? all variables are declared as byte. Explicitly casting the 1's to byte doesn't make any difference. However, change to
public class test{
public static void main(String[] args){
byte[] a = new byte[1];
a[0] = 1;
byte x = 1;
x += a[0];
System.out.println(x);
}
}
and everything compiles fine. I'm compiling with java version 1.6.0_16, build-b01. My questions are: Is this a bug or a feature? Why does += perform differently than + ?
You will find this answer of great help.
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
Notice the explicit cast that is introduced when using the compound assignment operator.
In the first case the result is int. so you need to cast it explicitly for byte. But in the second case, java will convert the value automatically to byte. So casting is not needed and no exception.
This is the result of a quirk in the Java Language Specification. The default type of an integral expression (such as x + a[0]) is int, and the compiler then complains when you try to assign the result to a byte without a cast. Technically speaking, of course, it's correct, and you could easily overflow the byte precision. Using the += syntax avoids the separate x + a[0] expression and its implicit widening conversion:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
I have been working with Java's byte primitive lately, and I came across a silly problem:
byte a = 10;
byte b = 9;
byte c = 8;
b += b*c; // how come this statement is correct without any explicit type casting
b = b*c; // while this statement is incorrect; it requires explicit cast, of course
b = b+(b*c); // this is wrong too.
So my question is, does += specify any assignment other than just add and assign, or is this a bug in Java (which I am almost sure is not)?
Because b += b*c is equivalent to b += (byte) ((b) + (b*c)).
From the Java language specification on compound assignment operators:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
All compound assignment operators not only performs the operation, but also cast automatically their result to the type of the left-hand side variable.
So your += not only adds variables and assign the result - it also cast the result to the right type.
I've found that java compile has a non-expected behavior regarding assignment and self assignment statements using an int and a float.
The following code block illustrates the error.
int i = 3;
float f = 0.1f;
i += f; // no compile error, but i = 3
i = i + f; // COMPILE ERROR
In the self assignment i += f the compile does not issue an error, but the result of the exaluation is an int with value 3, and the variable i maintains the value 3.
In the i = i + f expression the compiler issues an error with "error: possible loss of precision" message.
Can someone explain this behavior.
EDIT: I've posted this code block in https://compilr.com/cguedes/java-autoassignment-error/Program.java
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2
The Java Language Specification says:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
So i += f is equivalent to i = (int) (i + f).
i believe that the explicit i+f fails because of Narrowing primitive conversion. While in the first case the conversion on the right side passes because it is done according to Compound Assignment rules.
I have seen this symbol/operator in a block of code:
a+=1;
But I cannot figure out what it does. Can someone help me please?
It is equivalent to
a = a + 1;
From the Java Language Specification:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
The last phrase is important if the left-hand side has side effects:
array[i++] += 1;
This is not equivalent to:
array[i++] = array[i++] + 1;
The first expression will increment i once. The second will increment i twice and will assign the right-hand value to a different element of array than will the first expression.
I should note that these kind of side-effect statements are not good programming form, despite the fact that you often find them used.
The cast is also important because the type of (E1) op (E2) may not be assignment-compatible with E1. For example, if a is of type short, then a++ is not equivalent to a = a + 1. The latter will not compile because the type of a + 1 is int and cannot be assigned to a short variable without a cast. That's why the spec in this case says that a++ is equivalent to a = (short) ((a) + (1)). The same thing goes if a is of type char or byte.
x += y;
is equivalent to
x = x + y;
There are similar operators for the other mathematical operations: -=, *=, /=. For example:
x *= y;
is equivalent to
x = x * y;
(EDIT: The above assumes there are no 'side-effects' in x; ie, preincrement or postincrement operators. Edited to reflect Ted Hopp's point)
It is shorthand for the following:
a = a + 1;
It means a = a + 1 i.e increment a.