This question already has answers here:
Meaning of *= in Java
(4 answers)
Closed 4 years ago.
Hello everyone I have a very simple question that I just don't understand. I've tried googling it but haven't found a clear answer.
What is x after the following statements?
int x = 2;
int y = 1;
x *= y + 1;
I know that the answer is 4 but I don't understand why it is 4. Just need some clarity on what x* means exactly. Thanks!
I think this line is the one why you ask
x *= y + 1;
This is a shorthand for
x = x * (y + 1);
This works also with other operators like - and +, when the first variable is the same as the variable on the left side (which will be assigned).
Of course x is 4, if you don't understand the last statement, you can read it like this
x = x * y + 2
The x*= symbol means x=x* the result of whatever you put after the equals symbol.
x*= y+1 will turn to x = x * (y+1). The expresion you put after equals is evaluated first and then multiplied with x. The result will be cast to the type of the assignment variable (x).
Related
This question already has answers here:
Is there a difference between x++ and ++x in java?
(18 answers)
Java: pre-,postfix operator precedences
(5 answers)
Closed 6 years ago.
Say we have Java code below:
int x = 1;
int y = x + x++;
'Cause the precedence of "postfix-increment" operator is higher than "add" operator. I think x++ should be calculate and evaluated first. Then it comes to x + (x++). So the y should be "new_x(2) + 1 = 3".
Though it turns out "2" instead of "3". Any ideas? Thanks.
This question is greatly different from Is there a difference between x++ and ++x in java?. That question mentions nothing about the operator precedence.
Someone has explained that expression is read from left to right. Does it conflict with the precedence of those operators?
Just as I mentioned before, I think x++ should be calculated first. It seems that I mess up with the "evaluation" and "calculation".
The difference between x++ and ++x is quite evident and known. ++ can be used as preadd (Add 1 and then use x ) or postadd (use x and add 1).
Check this out.
As tested and seen
1. x + x++ will give 2
2. x + ++x will give 3
3. x++ + x will give 3
4. ++x + x will give 4
Now the interesting case here is 2nd and 4th which basically explains pre-add operator.
In these cases, the value of x is incremented first and then used in both the places.
However in case of test 2 the first operand i.e. x is already used up for addition so the answer is 3
while in the test 4 the operand x is first incremented and used in both the operands. This happens because the expressions are evaluated from left to right.
x++ would first return x then increment x.
++x would increment x first then return x.
Therefore :
int y = x + x++; //y (2) = x(1) + x(1, then becomes 2 right after)
int y = x + ++x; //y (3) = x(1) + x(becomes 2 before being returned)
This question already has answers here:
Java two equal signs in one statement? [duplicate]
(5 answers)
Closed 8 years ago.
What does this do?
int x = 1;
int y = 2;
int z = 3;
x = y = z;
I have come across multiple of this type of thing in a few open source projects and have always been confused by them. By them I mean the = operator being used twice on three integers i.e. x = y = z;. I need to understand this. Thanks!
The operator = evaluates the right hand side and assigns the result to the variable on the left hand side. The expression returns this value.
For this to work, evaluation proceeds from right to left:
x = (y = z);
y becomes 3 and the value returned is 3. Thus, x is assigned 3 as well.
= is evaluating right to left
x = y = z will make x and y equal to z, i.e = 3
= operator will assign value of right side expression to the variable on left side.
So in x=y=z,first value of z will be assigned to y and then it is assigned to x.
STEP 1 : x=(y=z) /assign value of z to y.
STEP 2 : x=y /assign value of y to x.
So value of x will be 3.
The assignment operator always evaluate right side expression so your statement equivalent to
//this expression is equal to
x=y=z;
y=z;
x=y;
//so first y becomes 3 and the value assign to x
//means first assign the value of z to y than assign the value of y to x
x = y = z is same as x=(y=z)
so, first y is assigned the value of z , i,e 3 and then the result is assigned to x.
At the end of it, values will be x = 3, y = 3 and z = 3
The = operator evaluated from right to left.
So, when you write x=y=z it works form right hand side ti left hand side as
1. y=z i.e value of z assign to y
2. then x=y i.e new value of y now assign to x
for example,
if x=1,y=2 and z=3 then after x=y=z value of x=3,y=3 and z=3
value assign this way
x=y=z <-------------
In most of the language = stands for assignment operator and the rule is lefthand side of assignment operator must be variable/object. (You can also do it like this object1=object2 but object2's reference will be the value here )
You can't do 2=3 or 2=2 what happening here is you are first assgning value of z to y
x=y=z
y=z
x=y
Here it's evaluated from right to left so y takes value of z and than x takes value of y
Probably here want to note you can't do x=4=5 directly.
It must be variable=variable=(value/variable)<------------------
So during this your z must have been initialized
Please read some specifications:
There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.
See also:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26
http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html
https://stackoverflow.com/a/12850755/1834700
This question already has answers here:
Weird Integer boxing in Java
(12 answers)
Closed 8 years ago.
I am confuse about autoboxing unboxing in java. Please see my following two progarm.
Integer x = 400;
Integer y = x;
x++; x--;
System.out.println((x==y));
The output is false.
I known why the output is false. Because of autoboxing x.
Integer x = 100;
Integer y = x;
x++; x--;
System.out.println((x==y));
The output is true.
But the program is same as the upper. Why the output is true?
Please explain me detail.
Thank you very much.
This is because Integers -128 to 127 are cached, so in second example x and y refer to the same Integer instance.
Integer x = 100; // x refers to cached 100
x++;
is equivalent to
int var = x.intValue();
var++;
x = Integer.valueOf(var); // returns cached 100
See Integer.valueOf(int) API.
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
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I was going through a programming class and was asked this tricky question which was left unanswered till the end of the class.
Question:
How can I multiply any input(Float,int etc) by 7,
without using the * operator
in TWO steps.
If anyone can give me the answer for this question with the explanation , that would be very helpful.
With TWO STEPS I mean suppose you are running a loop (i=0;i<7;i++) in
that case number of steps will be >2, also TYPE CONVERSION,
DIVISION,ADDITION etc ( Counts for steps ).
Assuming float x or double x is defined in the scope. Then I see the following possibilities to multiply it by 7 without using the * operator:
In C++, you can use the standard functors (first step: create functor, second step: call functor):
x = std::multiplies<float>()(x, 7.0f); // if x is a float
x = std::multiplies<double>()(x, 7.0); // if x is a double
Or only use division (Since the compiler already evaluates 1.0 / 7.0, this is only one step):
x = x / (1.0f / 7.0f); // if x is a float
x = x / (1.0 / 7.0); // if x is a double
Or use the *= operator (technically, it's not the * operator, but it's only one single step):
x *= 7.0f; // if x is a float
x *= 7.0; // if x is a double
Or use addition in the logarithmic scale (this is not to be taken very serious, as well as this requires more than two "steps"):
x = exp(log(x) + log(7.0));
Another option is to use an assembly instruction, but I don't want to write that now, since it's overly complicated.
If x is an integer, bit shifting is another option, but not recommended:
x = (x << 3) - x; // (x * 8) - x
You could simply use division by a seventh:
x / (1.0 / 7)
Whether this counts as "two steps" is entirely up to your definition.
add it
//initialise s as the number to be multiplied
sum=0
for(i=0;i<7;i++)
sum+=s
In C, the following hack should work for floats stored in IEEE single precision floating point format:
#include <stdint.h>
float mul7 (float x) {
union {
float f;
uint32_t i;
} u;
u.f = x;
u.i += (3 << 23); /* increment exponent by 3 <=> multiply by 8 */
return u.f - x; /* 8*x - x == 7*x */
}
That's two steps (one integer addition, one float subtraction), sort of, depending on what you count as a step. Given that C++ is more or less backwards-compatible with C, I believe a similar trick should be possible there too.
Note, however, that this hack generally won't give correct results for subnormal, infinite or NaN inputs, nor for inputs so large in magnitude that multiplying them by 8 would overflow.
Adjusting the code to use doubles instead of float is left as an exercise for the reader. (Hint: the magic number is 52.)
You may also do the following for integers:
( x<< 3) - x
// String num = "10";
// int num = 10;
float num = 10;
BigDecimal bigD = new BigDecimal(num);
BigDecimal seven = new BigDecimal(7);
System.out.println(seven.multiply(bigD));
You could use the BigDecimal & its multiply method. Works for pretty much everything.
Define "two steps"...
float result = 0.0f;
float input = 3.14f;
int times = 7;
// steps
while (times--)
result += input;
Edit: dividing by (1 / 7) won't work with int type. Also in some languages for it to work with float type, you'd have to mark them as floats:
result = input / (1.0f / 7.0f);
Add 7 by x times.
for(int i=0; i<10; i++)
result = result+7;