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

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.

Related

Why I get -2 if I add 2147483647 to itself in java for int and long type? [duplicate]

This question already has answers here:
Java long assignment confusing
(9 answers)
Double Integer value overflow
(3 answers)
Closed 3 years ago.
For integer datatype 2147483647 number is withing the range.
I tried a small program as below,
int a = 2147483647;
int b = 2147483647;
int c = a + b;
When i print c it prints as -2. I changed the type of c to long and double still same result.
Why is this beahvior ?
I am using java 12.
Edit: live demo
Here's what's going on when you add those numbers:
int a = 2147483647;
int b = 2147483647;
In binary:
a = 0b01111111111111111111111111111111
b = 0b01111111111111111111111111111111
Adding those numbers together gives a number larger than Integer.MAX_VALUE (obviously):
long c = a + b; // -2
In binary:
0b01111111111111111111111111111111
+ 0b01111111111111111111111111111111
------------------------------------
0b11111111111111111111111111111110
== -2 when taking into account 2's complement
The result is then upcast to a long.
To ensure the numbers are added as longs and not ints, make a and b both longs.
Change int a , b , c to long a , b , c . Here, a and b were int and when they are added the number is int too. But it goes out of scope of int. So, change them to long to get correct answer.
The two ints are being added together as ints. The result is an int that is implicitly cast to a long or double, if c is a long or double. To avoid this, change the types of a and b to longs, so the addition is long addition.

Java - Why floats require cast or 'f' suffix whereas long does not? [duplicate]

This question already has answers here:
Why is the letter f used at the end of a float no.?
(10 answers)
Closed 6 years ago.
Why do I need to cast a float or put an 'f' suffix whereas long doesn't?
Why is the default data type for floating point numbers is double and not float?
For eg:
float foo = 0.5; //compilation error
float foo = 0.5f; //works
float foo = (float)0.5; //works
whereas
long bar = 10; //works
Why is Java designed in such a way?
The first one doesn't work because a double (0.5 is a double literal) is wider than a float: it has more bits of data, so the assignment needs to throw away some of that data. You can explicitly cast it, but you have to make it clear that you intend to lose that extra data via the (float) cast.
The last one works because 10 is an int literal, and int is narrower than long: it has fewer bits of data, so you can assign an int to a long without losing data.

Java casting (cast operator expressions) [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14

Assigning a value to long and float primitive types in Java [duplicate]

This question already has answers here:
Java's L number (long) specification
(7 answers)
Closed 6 years ago.
I have a question about declaring a long variable in Java:
This compiles: long x = 10;
This gives a compiler error: long x = 1000000000000
This compiles: long x = 1000000000000L
Why don't i need to put a L after the number in the first case? How does this relate to the compiler automatically casting a long to an int value (because Iguess that is what's happening in the first example) ?
Also the same question about float's:
This doesn't compile: float f = 10.1;
This compiles: float f = 10;
This compiles: float f = 10.1f;
Why does the first example not compile? Why is the f-prefix not needed in the second example? And how does this relate with the complier automatically casting to a double?
Thanks in advance!
Numeric constants without any postfix have default types. If they are integer (i.e. they have no floating point), the default type is int. If they have a floating point, the default type is double.
Therefore an integer constant without the L suffix (which denotes a long literal) can't be larger than Integer.MAX_VALUE, and the double constant 10.1 can't be assigned to a float variable without an explicit cast.
On the other hand, the int 10 can be assigned to a float variable, as well as the float 10.1f.

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