This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 8 years ago.
Take these two snippet for example:
Case 1:
Scanner s = new Scanner(System.in);
int n = s.nextInt(); /** take user input **/
n *= Double.NEGATIVE_INFINITY;
and
Case 2:
int k=10;
double kk = 10.10;
int rst = k*kk;
In both the cases, I am not doing any typecasting from my side, but Case 1 executes and prints value of n correctly but Case 2 throws an error, can not convert from double to int. Why this difference?
The first works and the second doesn't because the *= += -= etc add an automatic cast.
If, for example, you were to change your second example to;
int k=10;
double kk = 10.10;
k*= kk;
It should work. Alternatively you could just add an explicit cast like so rst = (int)(k*kk);
The arithmetic promotion in Java happens when you apply an arithmetic
operation on two variables with different data-types. In this case the
compiler will convert the data type of one operand in the binary
arithmetic operation to the type of the other operand.
In your case, for multiplying an int and a double, the int is promoted to double, and the result is double. So, it can't be stored into an int.
See more at: http://www.codemiles.com/java/arithmetic-promotion-t3487.html#sthash.sdHtt7pG.dpuf
The result of the multiplication of an integer (int) and a floating point in java will always result in a floating point (double). You are assigning this result to the integer rst which requires casting.
Related
This question already has answers here:
why explicit type casting required from double to float but not from int to byte?
(4 answers)
Closed 1 year ago.
I'm not sure if my question is clear enough, so I will give examples. Let's think we have the next expression:
byte byteNumber = 10 * 10;
I understand the literal number 10 is an integer by default, so the expression 10 * 10 also results in an integer, BUT Java "demotes" it to a byte value since the variable (where the result is stored) is a byte.
However, why this works different?
int x = 10;
int y = 10;
byte byteNumber = x * y;
The line byte byteNumber = x * y; is marked as an error. I understand the expression x * y results in an integer but is not "demoted" as with the literals. Even if there is only one variable, like x * 10, the result won't be demoted. Why exactly? I believe it has something to do with the variables type, but literals are integers by default and they can get "demoted".
Another example I am struggling with is: we can assign integers literals to variables of type byte, short or char, and Java will automatically convert the integer into the type of variable we have declared, like:
short a = 10;
byte b = 12;
On the other hand, why can't we do something like this?
float c = 12.0;
Yes, 12.0 is a double, but why can't it be "demoted" to float and forces us to declare the literal as a float 12.0F? I understand this would represent a lose of information. However, converting an integer to a short or byte also represents a lose of information, isn't it?
Finally, why can we assign a integer literal to a variable of type short or byte...
short a = 10;
byte b = 12;
but we cannot pass an integer as argument to a method that expects a short/byte parameter?
public void newMethod(short x, byte y){
...
}
.
.
.
newMethod(10, 2)
It would be great if you could search some links where I can read this kind of stuff (since I'm not really sure how to search for these specific issues I have).
Thank you all in advance.
You could check the following two links out:
Why explicit type casting required from double to float but not from int to byte?
(the one I have already shared in a comment)
Implicit type cast not working for method parameters?
By the way, both of those questions were answered by the #1 StackOverflow contributor Jon Skeet :)
I was going through some java interview questions MCQ where I found this code snippet, of which I didn't understand the output, though its only a 2 line code.
int a = 8;
System.out.println(((a<8)? 9.9 : (int)9));
Output is 9.0
I didn't understand why it is not 9 ?
Ternary operator has return type that is defined before the calculation of the value.
So, if the operator can return both float and int, then the both values are upcasted to the float.
Your answer is casted in this way:
(int)9 -> (int)9 -> (float)9.
Other situation: If you add float and int, you get float
int a = 2;
float b = 4.3f;
float c = a + b;
Because you are not casting all of them . you are just casting second result to int.
But don't forget first result is float so all of structure must be same type.
You need to cast all of them as same type like int or float.
int a = 8;
System.out.println(""+ (int)( (a<8)? 9.9 : 9));
output :
9
The return type of the ternary operator is determined according to quite complicated rules:
Java Language Specification. Specifically, in your case:
Otherwise, binary numeric promotion (ยง5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
So in your case you get return type double.
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 6 years ago.
I'm a high school student currently getting ready for a state academic meet(UIL). I have a problem and I've looked everywhere and can't seem to find an answer! Why does this print out 0.0?
double d = 1/2;
System.out.println(d);
It's because of the data type.
When you do 1/2 that is integer division because two operands are integers, hence it resolves to zero (0.5 rounded down to zero).
If you convert any one of them to double, you'll get a double result.
double d = 1d/2;
or
double d = 1/2.0;
1 and 2 are both integers, so 1 / 2 == 0. The result doesn't get converted to double until it's assigned to the variable, but by then it's too late. If you want to do float division, do 1.0 / 2.
It's because 1 and 2 are int values, so as per the java language spec, the result of an arithmetic operation on int operands is also int. Any non-whole number part of the result is discarded - ie the decimal part is truncated, 0.5 -> 0
There is an automatic widening cast from int to double when the value is assigned to d, but cast is done on the int result, which is a whole number 0.
If "fix" the problem, make one of the operands double by adding a "d" to the numeric literal:
double d = 1d/2;
System.out.println(d); // "0.5"
As per the language spec, when one of the operands of an arithmetic operation is double, the result is also double.
Cause result of 1/2 = 0 and then result is parsing to double. You're using int instead of double.
I think it should be ok:
double d = 1/2.0;
System.out.println(d);
Sorry for weak english
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 8 years ago.
I tried of finding answer by googling as well as debugging variable behavior, but unfortunately I dint find any proper answer. Its a question related to Java for instance.
Question :
Why 'double' type variable behaves like 'int' type in below condition :
double PI = 22/7 which returns 3
but, double PI = 22.0/7 or 22/7.0 returns 3.14xxxxxxx ?
Help appreciated...Thanks.
Because that's how Java (and some other programming languages) have been implemented.
Since both are integers, the expected result will be an integer as well:
int/int = int
In the other hand, when one operator is double, the result will also be double
double/int = double
int/double = double
Because in java arithmetic operations output gives the result in terms of highest data type among all involved variables or constants(Applied only on primitive data types).
For example if in any arithmetic operation like below:
Scenario 1=> var1 is int, var 2 is float, var3 is double: You will get result in double
Scenario 2=> var1 is short, var2 is long and var3 is float: you will get result in float
Scenario 3=> var1 is int, var2 is long, var3 is double: you will get result in double
Note: float family data type(float & double) always dominate to int family data types even both have same size, like in case of long and float output will be in float.
Because by default in java numerals are integer data type, so, when you are doing numeric operation with integers, the result also will be integer. When you assign that integer to a double variable, it is promoted to a double, but its value is kept. So you end up with a double with the exact same value as the result integer -- in this case, 3.0.
In your first case, both are integers, so the result also an integer, and you have assigned to double. But the conversion(integer to double) happened before assignment to double.
In the second or third case, one in double, so the operation done on double, So the result also a double value.
Or 'Pi= 22D / 7D' does it too. Here 22 and 7 are declared as 'double', not 'int'.
public static void main(String[] args) {
double d = 22 / 7; // same as double d = (int)22 / (int) 7
System.out.println(d); // so prints 3.0
double dd = 22.0/7; // same as double dd = (double)22 / (int) 7
System.out.println(dd);//prints 3.14xxxx
}
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));