Pre and Post Increment and Decrement in Java [duplicate] - java

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 5 years ago.
Day after tomorrow is my exam for Computers (JAVA) and I have a big problem in the above title. I understood what does post and pre increment and decrement means. But I can no understand what to do when the matter comes to a complex, long statement. One example for such question is below.
class java_1
{
public void main()
{
int x = 4;
x += x++ - --x + x + x--;
}
}
You see what I meant by complex statements. The statement contains only one variable being incremented and decremented again and again, and I get confused over here. Can you please help me clear my confusion. Also, kindly give the answer to the above code.

a += b; is similar to a = a + b. Using this assumption we can rewrite
x += x++ - --x + x + x--;
as
x = x + (x++ - --x + x + x--);
Lets now have x = 4 and evaluate right side (from left to right)
x + (x++ - --x + x + x--)
4 + (x++ - --x + x + x--)
^ //still x = 4
4 + (4 - --x + x + x--)
^ //x++ use current value (4), then increment x to 5
4 + (4 - 4 + x + x--)
^ //--x decremented to 4, then use current value (4)
4 + (4 - 4 + 4 + x--)
^ //still x = 4
4 + (4 - 4 + 4 + 4)
^ //x-- read current value (4), then decrement x to 3
So we are getting
x = 4 + (4 - 4 + 4 + 4);
which means
x = 12;

Related

java expression calculation and operator precedence

i have problem to step by step java expression calculation
System.out.println(++x + x++ * y-- - --y);
I know this precedence:
1. postfix unary
2. prefix unary
3. multiplicative
4. additive
but when i calculate with this precedence the result is below:
// 12 + 11 * 19 - 18
can some one help me
You can understand it from the example given below:
public class Main {
public static void main(String[] args) {
int x = 5, y = 10;
System.out.println(++x + x++ * y-- - --y);// 6 + 6 * 10 - 8 = 58
}
}
Steps in this calculation:
++x = 6
6 + x++ * y-- = 6 + 6 * 10 = 6 + 60 = 66 (after this y will become 9 because of y-- and x will become 7 because of x++ but this increased value of x has never been used in subsequent calculation)
66 - 8 = 58 (before y gets subtracted from 66, it will become 8 because of --y)
Postfix unary is applied after the variable evaluation, opposite to prefix, which is applied before evaluation, your expression can be rewrited:
int x_prefix = x + 1; // ++x
int y_prefix = y - 1; // --y
System.out.println(x_prefix + x * y - y_prefix);
int x = x + 1; // x++
int y = y - 1; // y--
You write operators precedence, it's right but every operator has own behavior, in case of postfix increment, of course has to be evaluate before others, but its behavior is return the current variable and after increment its value.
NOTE: I just rewrited your expression as is, if you use in the same expression the variable postfix incremented, the next access see the variable incremented:
int x = 1;
System.out.println(x++ + x++); // 1 + 2
System.out.println(x) // 3
For completeness:
int x = 1;
System.out.println(++x + ++x); // 2 + 3
System.out.println(x) // 3

What is returned by the call wacky 4,6? also how to calculate this recursion?

public static int wacky (int x , int y){
if(x <= 1){
return y;
}
else{
return wacky(x - 1, y - 1) + y;
}
}
I had a test a while but I still don't know how to do a recursion step by step and I remember this question by memory and I guess on the test thinking that you maybe calculate this way...
public static = 4 + 6 + 1 + 4 + 4 - 1 + 6 - 1 + 6
but was not of the answer choice I realize i was doing something wrong...
my teacher doesn't help me and don't even care I try to get help but he does not how to explain this...
When you call a function recursively, they add the new function to a stack until have a final result (return). When it occurs, you go back return by return in the stack.
An Execution example:
First Round wacky(4, 6):
4 <= 1? No, so call wacky(4 - 1, 6 - 1)
Second Round wacky(3, 5):
3 <= 1? No, so call wacky(3 - 1, 5 - 1)
Third Round wacky(2, 4):
2 <= 1? No, so call wacky(2 - 1, 4 - 1)
Fourth Round wacky(1, 3):
1 <= 1? Yes
return 3;
return 3 + 4;
return 3 + 4 + 5;
return 3 + 4 + 5 + 6;
Why not let Java tell you what is going on? Insert some print statements so you can see the values when the code runs:
private static int indent = 1;
public static int wacky(int x , int y) {
System.out.printf("%" + (indent++ * 2) + "swacky(%d, %d)%n", "", x, y);
int result;
if (x <= 1)
result = y;
else
result = wacky(x - 1, y - 1) + y;
System.out.printf("%" + (indent-- * 2) + "s-> %d%n", "", result);
return result;
}
Test
wacky(4, 6);
Output
wacky(4, 6)
wacky(3, 5)
wacky(2, 4)
wacky(1, 3)
-> 3
-> 7
-> 12
-> 18

Incorrect subtraction results: 3.999999, not 4 [duplicate]

This question already has answers here:
Adding and subtracting doubles are giving strange results [duplicate]
(2 answers)
Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?
(14 answers)
Closed 9 years ago.
So I narrowed down a bug in my application to java messing up a simple subtraction calculation. I can't figure out why exactly. Here is the bit of code:
for (double x = (((double)bdl.length())-1)/10; x > 0; x--) {
int count;
System.out.println("x = " + x);
if (x >= 1) {
System.out.println("X = " + x + " so count = 20");
count = (20);
} else {
count = (int)(x*20);
System.out.println("X = " + x + " so count = "+count);
}
}
The variable bdl is just a JSONArray, which I am only concerned with its length at this point. As bdl comes in initially it has length 15, so x will equal 1.4 . The first time through the loop the first println says "X = 1.4 so count = 20" which is correct. The second time through however when x should = 0.4, it instead says "X = 0.3999999999999999 so count = 7". I understand that casting (x*20) to an int at that point and time will give me 7, but my question is Why is x not equal to 0.4 .
You're using a double, which is a floating-point number. This is not meant for presision, moreover, it is meant for speed and non-precision. So instead, you should be using an int, like this:
for (int x = ((bdl.length())-1)/10; x > 0; x--) {
This will keep your numbers precise.
Actually, your 'x' does equal 0.4, it's only a matter of precision.
All floating point comparison operations should be executed with a certain precision (delta or epsilon in some implementations).
Refer to this post.

Quick little puzzle-y Java thing

Sorry, I couldn't think of a better title.
Anyway, when I compile the following code:
class Example{
public static void main(String[] args) throws Exception {
int x = 3;
x -= 2 + x++ == 4 ? x++ : ++x;
System.out.println("x = " + x);
}
}
I get the answer -2.
Now I would really like to know how it comes to this answer, as I can't find it.
It would be amazing if I could get an answer to this, as this may be on a exam that I'll have somewhat soon.
Note: Of course I wouldn't ever code out something like this myself, this is just an exercise.
Thanks so much if you can help me out!
Edit: answer to fge's answer:
Okay, thanks! but now if I change it up a little and make it like so:
x = 2;
x += 3 + ++x == 6 ? x-- : x--;
System.out.println("x = " + x);
I would think that you would get the following:
++x == 6
is not true, as x is now 3. this means we get x--, making it now 2 again.
then we get 3 + 2 = 5, so the expression can be evaluated to:
x += 5
because x is now 2, we get 2 + 5 = 7.
When you create such code example
int x = 3;
System.out.println(2 + x++ == 4 ? x++ : ++x);
you will see that the output is 5. It is because it is equivalent to
(2 + x++) == 4 ? x++ : ++x
so first Java will evaluate (2+ x++). Since we have x++ value of x will be returned first creating (2+3) and then incremented, so x will be now 4 after it.
Since (2+3) == 4 is false because (5 == 4) we will execute this part ++x, first incrementing x to 5 and then returning it.
Now lets go back to your example
int x = 3;
x -= 2 + x++ == 4 ? x++ : ++x;
You may know that x -= y is in fact x = x - y so it can be written as
x = x - (2 + x++ == 4 ? x++ : ++x);
So, since Java evaluates from left to right it will be
x = 3 - (2 + x++ == 4 ? x++ : ++x);
We know now that (2 + x++ == 4 ? x++ : ++x) is in fact 5 so
x = 3 - 5; // == -2

What is the XOR operator evaluating when switching the int values of two variables? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does XOR variable swapping work?
I found a solution to switching the values of two variables, without creating a third variable, which is as follows:
x ^= y;
y ^= x;
x ^= y;
This is using the exculsive-or operator ("XOR"), in a way other than boolean (I'm assuming it's bitwise?). Having learned some Discrete Mathematics recently, I can understand the usage of the XOR operator with a truth-table:
.......................
x y (x XOR y)
.......................
T T F
T F T
F T T
F F F
The expression (x XOR y) evaluates to false when both variables are equivalent, and to true otherwise. But WTF when the values are not boolean?
Anyway, if I set x and y equal to int values instead of boolean values, the operations are not very straightforward. So, for example let x = 3, and y = 5:
public class SwitchValues
{
// instance methods
public void SwitchBoolean(boolean x, boolean y)
{
System.out.println("The variable \"x\" is initially: " + x + ".\n" +
"The variable \"y\" is initially: " + y + ".");
x ^= y;
System.out.println("x ^= y is equal to: " + x + ".");
y ^= x;
System.out.println("y ^= x is equal to: " + y + ".");
x ^= y;
System.out.println("x ^= y is now equal to: " + x + ".");
System.out.println("The variable \"x\" is now: " + x + ".\n" +
"The variable \"y\" is now: " + y + ".\n");
} // end of SwitchBoolean
public void SwitchInts(int x, int y)
{
System.out.println("The variable \"x\" is initially: " + x + ".\n" +
"The variable \"y\" is initially: " + y + ".");
x ^= y;
System.out.println("x ^= y is equal to: " + x + ".");
y ^= x;
System.out.println("y ^= x is equal to: " + y + ".");
x ^= y;
System.out.println("x ^= y is now equal to: " + x + ".");
System.out.println("The variable \"x\" is now: " + x + ".\n" +
"The variable \"y\" is now: " + y + ".\n");
} // end of SwitchInts
// main method
public static void main(String[] args)
{
SwitchValues obj = new SwitchValues();
obj.SwitchBoolean(true, false);
obj.SwitchInts(3, 5);
} // end of main method
} // end of class SwitchValues
... and the results printed out for the int values are as follows:
The variable "x" is initially: 3.
The variable "y" is initially: 5.
x ^= y is equal to: 6.
y ^= x is equal to: 3.
x ^= y is now equal to: 5.
The variable "x" is now: 5.
The variable "y" is now: 3.
This is how the operations works. First we will write your numbers in binary:
3 = 011, 5 = 101
Now, when we xor them we got a number which represent which bits are different between the two original numbers.
011 xor 101 => 110 which is 6 in decimal.
Now we take the second number and xor with the difference we just got
101 xor 110 => 011 (3 in decimal) and we get the difference between these numbers and we are back with the original first number. Now we again take this new number and xor it with the difference we originally got
011 xor 110 => 101 (5 decimal) and we have gotten back the original second number.
On XOR Swap wiki you can see a clearer description and also reasoning why this is slower than using a temporary variable on most modern architectures and compilers.
Actually you gave the answer yourself. You assumed xor on int is bitwise and thats correct. Transform the numbers to bit representation and then apply the xor bit by bit.
3 is 11 in binary. 5 is 101 in binary
011
101
--- xor
110
110 is 6 in decimal.
If you want to know how to calculate the binary represantation of a number you should look up Horner's method. Its quite easy to do.
XOR when applied to a numeric type is a bit-by-bit exclusive or. So you can take your original truth table and apply it to each of the bits in parallel. That should help understand what's happening.

Categories