This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 9 years ago.
I encountered someting unexpected with the java += operator.
Apparently, this compiles:
int a = 0;
a += 3/2.0;
System.out.println(a); // outputs "1"
While, this doesn't
int a = 0;
a = a + (3/2.0); // eclipse compiler error "Type mismatch: cannot convert from double to int"
System.out.println(a);
Is this expected behaviour? I find it strange that the += operator does not report a "Type mismatch", because it is an 'add and assign' operator, where you add a double, which gives a double result, and is then assigned to an int variable. Instead it silently casts (and truncates) the result.
This is the way += has worked from C. It's "feature" not a bug
See Java's +=, -=, *=, /= compound assignment operators
BTW You can try this
char ch = '0';
ch *= 1.1; // ch = '4'
Also see a post of mine http://vanillajava.blogspot.com/2012/11/java-and-implicit-casting.html
int a = a + (3/2.0); doesn't compile since:
int + double leads to a double
a is referenced as an int
cast from double to int missing
int a += 3/2.0; compiles since:
int + double leads to a double
a is referenced as an int
double is castable to an int and luckily, compiler adds an implicit cast similar to:
int a = (int)(a+ 3/2.0);. This is due to the special op= notation that is interpreted more cleverly from compiler than the basic assignment operator: =.
This is not a bug , its a implicit conversion happened.
for eg.
Byte b=3;
b+=5; //compiles
b=b+5; //doesnt compiles
Here what happens is
a=a+3/2.0; // 3/2.0 produces double , it add int to double but cant convert it implicitly to int.
a += 3/2.0; // here implicit conversion after addition of a to 3/2.0 happends from double to int
Related
This question already has answers here:
In java why we can't assign int to char directly??? but vice-versa is true?
(4 answers)
Closed 10 months ago.
I tried
int a = 100;
char c = a; //doesn't work
but
char c = 100; //does work
Does anybody know why?
Sentence
char a = 100;
will work, as every number in char stands for symbol in Unicode, from 0 to 65,536
For example
char a = 435;
System.out.println("Output: " + a);
gives output
Output: Ƴ
As mentioned in answer below, type cast needed, when assigning int value to char, as int has wider values range (from -2147483648 to 2147483647) than char
For example,
long a = 1;
int b = a;
also impossible
The reason why char c = a; does not work is since char and int are incompatible types.
char can store 2 bytes where as int can store 4 bytes. And so the java compiler does not allow the above operation since it can probably result in data loss while type conversion takes place.
To avoid the above issue, we can simply typecast int to char before assigning char c = (char) a;.
compiler won't do 'Widening or Automatic Type Conversion' for int to char.
Reference
This question already has answers here:
Why can't you add an int and a char in some cases?
(1 answer)
Java - char, int conversions
(4 answers)
Integer arithmetic in Java with char and integer literal
(6 answers)
Closed 1 year ago.
Why can't i do this?
public class test123 {
public static void main (String [] args) {
char c = 34;
char a = c + 10;
}
}
new to java, so sorry if this question is actually stupid.
When you add numbers, they undergo binary numeric promotion. That is, the operands are widened to allow them to be added.
When you add a char to an int, the char is widened to an int, and the result is an int.
As such, you would have to cast the int back to a char:
char a = (char) (c + 10);
However, even when adding a char to another char, both are widened to int, and the result is again an int, and so cannot be assigned to a char variable. The rules are basically:
If either operand is a double, widen both to double
Else, if either operand is a float, widen both to float
Else, if either operand is a long, widen both to long
Else, widen both to int
So, even if you were adding a byte to a byte, both are widened to int, added, and the result is an int.
The exception to this is if you made c final:
final char c = 34;
In that case, c has a compile-time constant value, so c + 10 is a compile-time constant expression. Because it's a compile-time constant expression, the compiler knows its value, and knows that it fits into the range of char; so it would be allowed:
final char c = 34;
char a = c + 10;
As per the JLS, int is the narrowest type for arithmetic. Narrower values are widened to int, and the result is int.
You would get the same error even if you coded:
char a = c + c; // error
The Java char is a primitive data type. It is used to declare the character-type like char char1='a';
But you can add an int to a char, but the result is an int - you'd have to cast back to char
char a = 'a';
char b = (char)(a+4);
System.out.println(b);// print "e"
This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Adding int to short [duplicate]
(3 answers)
short plus short is an int [duplicate]
(2 answers)
Closed 4 years ago.
I just can't understand the difference between this:
short d = 0;
//some code
node.accessible = d + 1;
and this
short d = 0
//same code here
node.accessible = d;
node.accessible += 1;
the second thing is working, but the 1st one is't inteliji showes "incompatiable types" error.
p.s. node class:
public class Node {
int n;
short accessible;
Node(int n){
this.n = n;
this.accessible = -1;
}
}
In the first version :
node.accessible = d + 1;
d + 1 produces a int as summing an int and a short produces an int.
The JLS states indeed that (look at the last case, emphasis is mine) :
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.
But you cannot assign a int to the accessible field that is a short without explicit cast as int has a broader range than short.
While in the second version, a Compound Assignment Operators is used (+=):
node.accessible += 1;
As a consequence, in your case the result of the operation is converted to short : the type of the left-hand variable as the JLS states :
15.26.2. 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 Evaluations only once.
And more specifically in your case :
Otherwise, the result of the binary operation is converted to the type
of the left-hand variable, subjected to value set conversion (§5.1.13)
to the appropriate standard value set (not an extended-exponent value
set), and the result of the conversion is stored into the variable.
That's because 1 in your + 1 expression is of type int. Adding short to int results in int which can't be assigned without a narrowing cast back to node.accessible.
In the second sample,
node.accessible += 1;
is actually
node.accessible = (short)(node.accessible + 1);
so it works without problem.
But in the first one
node.accessible = d + 1; is actually node.accessible = d + 1; and it doesn't automatically cast as short and thus gives error as (d + 1) is of type int
This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 7 years ago.
I wrote two versions of Java code to increment a char variable by 1:
version1:
char c = 'a';
c = c + 1;
version2:
char c = 'a';
c += 1;
To my surprise, the second version compiles and runs successfully but the first one shows an error, which says incompatible types: lossy conversion from int to char. Why are they different?
The second version involves a cast, and is equivalent to:
c = (char) (c + 1);
See JLS section 15.26.2 (Compound 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.
This question already has answers here:
Why can not I add two bytes and get an int and I can add two final bytes get a byte?
(3 answers)
Java - char, int conversions
(4 answers)
Closed 8 years ago.
The following segment of code issues a compile-time error.
char c = 'c';
char d = c + 5;
The error on the second line says,
possible loss of precision
required: char
found: int
The error message is based on the NetBeans IDE.
When this character c is declared final like as follows.
final char c = 'c';
char d = c + 5;
The compiler-time error vanishes.
It is unrelated to the case of final strings
What does the final modifier make a difference here?
The reason is that the JLS #5.2 (Assignment conversion) says so:
If the expression is a constant expression (§15.28) of type byte, short, char, or int, 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.
In your example, char c = 'c'; is not a constant but final char c = 'c'; is.
The rationale is probably that the addition operator + first converts its operands to integers. So the operation could overflow unless everything is constant in which case the compiler can prove that there is no overflow.
When you apply the + operator to integral types
Binary numeric promotion is performed on the operands (§5.6.2).
In this case, the char values are promoted to int values.
Here
char c = 'c';
char d = c + 5;
because c is not a constant expression, the compiler cannot determine if the value of c + 5 which is an int will be able to fit in a char.
In this
final char c = 'c';
char d = c + 5;
where c is a constant expression, the compiler can determine that the value of c, which is 99, added to 5, which is 104 does fit in a char. Because of this guarantee, Java can safely perform a narrowing conversion from int to char.
If instead you had
final char a = Character.MAX_VALUE;
char b = (a + 5);
you would see the similar behavior as your first test case as the value of a + 5 does not fit in a char. The compiler determines that the int value resulting from a + 5 would not fit in a char.