How increment and decrement with if condition - java

I have this code:
class Example {
public static void main(String args[]) {
int x = 99;
if (x++ == x) {
System.out.println("x++==x : " + x);
}
if (++x == x ) {
System.out.println("++x==x : " + x); // ++x == x : 101
}
if (x == x++) {
System.out.println("x==x++ : " + x); //x==x++ : 102
}
if (x == ++x) {
System.out.println("x==++x : " + x);
}
if (++x == ++x) {
System.out.println("++x==++x : " + x);
}
if (x++ == x++) {
System.out.println("x++==x++ : " + x);
}
if (++x == x++) {
System.out.println("++x==x++ : " + x); // ++x==x++ : 109
}
}
}
and this is the output -->
++x==x : 101
x==x++ : 102
++x==x++ : 109
I want to figure out how the java compiler handles this code. I could figure out how it came up with this part of the output:
++x==x : 101
x==x++ : 102
But I couldn't with this part of the output:
++x==x++ : 109
How does this code work? And most importantly how does the last output work?

You just need to know 3 things and use logic to put it together:
x++ means: "Increment x, but the expression's value is what x was before you increment".
++x means: "Increment x, and the expression's value is what x is after you increment".
Things resolve left to right for the == operator. So, java 'resolves' the thing on the left, then the thing on the right, then does the calculation.
Thus, given: ++x==x++, and let's say x starts out as 107. Let's break it down:
First, resolve the left side, which is ++x. To do that, increment (x is now 108), then resolve the expression as the value after increment. So, the left hand side is 108.
Next resolve right side, which is x++. To do that, increment (x is now 109), then resolve the expression as the value before increment. So, the right hand side is 108.
Now do the operation. 108 == 108. That's true, so the if 'passes', and the result is printed. Given that x is now 109, it would print "++x==x++ : 109".
Which is exactly what it does.

++x is pre-increment
x++ is post-increment
Even if your condition gets a false, the incrementing will be done.

Related

java - Which has greater precedence, + or -

Considering this expression:
x1 = ++x - x++ + --x
if the value of x is entered 5
What will be the output of such expression in java, and why?
There is no greater precedence in + or -.
Without parentheses they are just executed in the order of apperance, lets consider your example:
public class Test {
public static void main(String[] args) {
int x = 5;
int x1 = ++x - x++ + --x;
System.out.println(x1);
}
}
will print 6
There are four operations of pre/post incrementation/decrementation:
++x will increment before evaluation (before using its value in the expression)
--x will decrement before evaluation
x++ will increment after evaluation (after using its value in the expression)
x-- will decreemnt after evaluation
Breaking the expression to parts:
1) "++x" the x will be incremented by 1 before using its value in the expression, so for now it is:
6 -
2) "- x++" the x will be incremented by one after using its value in expression, so it is:
6 - 6 , but now x=7
3) "+ --x" the x will be decremented by one, before its value will be used, so it finally translates to:
x1 = 6 - 6 + 6;
This will be executed as:
x1 = 0 + 6;
x1 = 6;
Obviously, there is no greater precedence in + or -, as it is just subtracted and added in the order of apperance.

When exactly does postfix unary operator happen?

I read a few post regarding unary operator:
What is the Difference between postfix and unary and additive in java
"C - C++" joke about postfix/prefix operation ordering
And a few more.
However, I still don't understand exactly when the value is changed.
For example:
int x = 1;
x = x++;
System.out.print("x = x++ ==> ");
System.out.print(" x = " + x);
System.out.println();
int x = 1;
x = x++ + x++;
System.out.print("x = x++ + x++ ==> ");
System.out.print(" x = " + x);
System.out.println();
The output is:
x = x++ ==> x = 1
x = x++ + x++ ==> x = 3
So in the first block x is assigned to x and afterwards incremented, but the value is never used, otherwise the output would have been x = 2.
In the second block, if I understand correctly, the first x++ is evaluated before the assignment and the second x++ is evaluated afterwards but is never used.
If in the second block both x++ would have been evaluated after the assignment but never used, the output would have been x = 2. If both have been used, the output would have been x = 4.
My IDE also indicated that the first x++ is used, but the second is not used:
So to conclude - I'm still confused about when and how exactly the increment is done.
At the line
x = x++ + x++;
Assuming x = 1, the first x++ returns "1" as the value, and then it increments x to 2. So basically, it's assigning the old value back to x.
The second x++ does the same; it returns the value of x, which is now 2, and only then increments its value to 3 - that value, is not used.
Your code is equivalent to:
tmp = x;
x = x + 1;
tmp2 = x;
x = x + 1; // not used
x = tmp + tmp2;
Links that may help you:
JSL - 15.14.2. Postfix Increment Operator ++
JLS - 15.15.1. Prefix Increment Operator ++
What is x after “x = x++”?

Java Ternary operator syntax [duplicate]

This question already has answers here:
Ternary operator, syntax error when using assignment
(4 answers)
Closed 8 years ago.
I have the following piece of code. This is how I understand it.
In the first case, the ternary operator returns the value of y because x=4 and the print statement prints 5, as expected.
In the 2nd case, the ternary operator first assigns the value of y to x and then returns that value. Again, it prints 5, as expected.
In the 3rd case, the ternary operator has x=y to the left of the : and x=z to the right of the :. I would expect this to behave much like the 2nd case. However, this statement does not even compile.
Any help in understanding this will be much appreciated.
public class Test {
public static void main(String[] args) {
int x = 4;
int y = 5;
int z = -1;
x = (x == 4) ? y : z; // compiles and runs fine
System.out.println(x + " " + y + " " + z);
x = (x == 4) ? x = y : z; // compiles and runs fine
System.out.println(x + " " + y + " " + z);
x = (x == 4) ? x = y : x = z; // Does not compile
System.out.println(x + " " + y + " " + z);
}
}
Assignment has lower precedence than a ternary expression, so this expression:
(x==4)?x=y:x = z;
can be thought of as:
((x==4)?x=y:x) = z;
Which obviously won't compile because you can't assign a value to something that isn't a variable.
Add parenthesis to control the order of evaluation
x = (x == 4) ? (x = y) : (x = z); // Does compile.
Note the above is equivalent to
if (x == 4) {
x = (x = y);
} else {
x = (x = z);
}
Which will (as a side effect) of assigning a value to x assign the value assigned to x to x. In other words, your ternary is equivalent to
x = (x == 4) ? y : z;
or
if (x == 4) {
x = y;
} else {
x = z;
}
The ternary is specified in JLS-15.25. Conditional Operator ? :.

Understanding a for loop and if condition

Below is come code that I am having trouble understanding. The output is 13 15 x=6. I understand how we get the number 13 because when we go through the loop the value of x is 5 and its corresponding y value is 12. So if x > 4 we then increment y which gives u the value of 13. The next number printed out then should be 14 because the next value of x is 6 and its corresponding y value is 13 so when you increment that it will be 14. However when I run the code its gives a different answer. Can anyone please help? Thanks
public class Output {
public static void main(String[] args) {
Output o = new Output();
o.go();
}
void go() {
int y = 7;
for (int x = 1; x < 8; x++) {
y++;
if (x > 4) {
System.out.print(++y + " ");
}
if (y > 14) {
System.out.println(" x = " + x);
break;
}
}
}
} ​
The reason is because ++y increments y before printing it.
y++ would do what you are expecting
When entering the loop iteration where x is 6, y is 13, as you said. Then y is immediately incremented to 14. x is greater than 4, so System.out.print(++y + " "); is executed. ++y increments y to 15 before it is printed.

fault or error in this method

I am revising for a software testing exam. One of the questions gives this method and asks to identify the fault as well as produce a test case (if one exists) which does not execute the fault.
Here is the code:
public static int oddOrPos(int[] x) {
//Effects: if x==null throw NullPointerException
// else return the number of elements in x that
// are either odd or positive (or both)
int count = 0;
for (int i = 1; i < x.length; i++)
{
if (x[i]%2 == 0 || x[i] > 0)
{
count++;
}
}
return count;
}
I have identified two problems. One being that i is initialised to 1 in the for loop so x[0] doesn't get tested. Also x[i] % 2 == 0 should be x[i] != 0
Are these problems faults or errors? I ask this because the question makes it appear that there is only one fault.
Also, I assume that because the for loop will always be executed, there is no test case which will not execute the fault.
Actually x[i] % 2 == 0 should be x[i] % 2 != 0 (if we want to detect odd values along with the positive ones. The existing code will detect even values instead).
The test case is just { -2 } - this element is even and negative, so should not get counted, and the method will return 0 even though it is faulty. { 1 } will also give 0, which is wrong.
If you want to detect odd negative values you'll have to look for -1 and not for 0 as it's done right now.
For odd positive values it will be 1. So basically you want anything but 0.
The % operator is a remainder operator, not really a modulo operator, it returns a negative number if the first given number is negative:
class Test1 {
public static void main(String[] args) {
int a = 5 % 3; // 2
int b = 5 / 3; // 1
System.out.println("5%3 produces " + a +
" (note that 5/3 produces " + b + ")");
int c = 5 % (-3); // 2
int d = 5 / (-3); // -1
System.out.println("5%(-3) produces " + c +
" (note that 5/(-3) produces " + d + ")");
int e = (-5) % 3; // -2
int f = (-5) / 3; // -1
System.out.println("(-5)%3 produces " + e +
" (note that (-5)/3 produces " + f + ")");
int g = (-5) % (-3); // -2
int h = (-5) / (-3); // 1
System.out.println("(-5)%(-3) produces " + g +
" (note that (-5)/(-3) produces " + h + ")");
}
}
Another "small" fault is the way the condition is done. Instead of checking for odd or positive, looking for positive or odd will be slightly faster. It's only because it's easier to check if a number is positive or not than getting its remainder.
Resources:
15.17.3. Remainder Operator %
The major thing here is that your for loop is starting at 1, and it should start at 0. You will always miss the first element of the array. Also x[i]%2 == 0 returns true for even numbers, not odd. So change that to x[i]%2 != 0.
public class test{
public static void main(String[] args){
int[] x = {3, 5, -1, -14}
if( 3 == oddOrPos(x)){
System.out.println("Working");
else
System.out.println("Test Fail");
}
public static int oddOrPos(int[] x) {
//Effects: if x==null throw NullPointerException
// else return the number of elements in x that
// are either odd or positive (or both)
int count = 0;
for (int i = 0; i < x.length; i++)
{
if (x[i]%2 != 0 || x[i] > 0)
{
count++;
}
}
return count;
}
}
As I understand it, you are right in your assumption. The first position of the array should be tested, hence the i[0] you pointed out.
However, x[i]%2 == 0 should instead be x[i]%2 == 1 for an odd number.

Categories

Resources