java variable holds wrong value after increment in loop [duplicate] - java

This question already has answers here:
For loop execution, increment confusion
(3 answers)
Closed 4 years ago.
int x;
for(x=1;x<10;x++);
System.out.println(x);
The output is 10 and I think that for loop should give the x a value of 9 since the condition of the loop is x<10. What am I missing?

The loop ends when x < 10 is false. This happens when x is 10. Remember that the loop does the following:
Initializes x=1
Checks x < 10:
if true then execute the loop body and increment x
if false then break out of the loop, retaining the current value of x
Repeats (2.)
So the value of x that causes the loop to exit is 10 because this is first value of x in your loop where x < 10 is false.

Related

I can not figure out why am i getting the result 2 [duplicate]

This question already has answers here:
How is that x=20;x= ++x + ++x + x++ ;final value of x in java is 65 [duplicate]
(8 answers)
Closed 5 years ago.
Maybe I'm missing out but I can't figure out why I am getting the result 2 in this code:
i = 1;
i = i-- - --i;
System.out.println(i);
In i = i-- - --i you have:
i--, a post-decrement, which retrieves the current value of i (1) and then decrements i to 0
-
--i, a pre-decrement, which decrements i again and retrieves the updated value, -1
So you end up with i = 1 - -1 which is 2.
Needless to say, this sort of thing shows up on (silly) Java tests and such, but should never appear in production code.

Missing update statement in if statement makes infinite loop [duplicate]

What happens (behind the curtains) when this is executed?
int x = 7;
x = x++;
That is, when a variable is post incremented and assigned to itself in one statement? I compiled and executed this. x is still 7 even after the entire statement. In my book, it says that x is incremented!
x = x++;
is equivalent to
int tmp = x;
x++;
x = tmp;
x does get incremented. But you are assigning the old value of x back into itself.
x = x++;
x++ increments x and returns its old value.
x = assigns the old value back to itself.
So in the end, x gets assigned back to its initial value.
The statement:
x = x++;
is equivalent to:
tmp = x; // ... this is capturing the value of "x++"
x = x + 1; // ... this is the effect of the increment operation in "x++" which
// happens after the value is captured.
x = tmp; // ... this is the effect of assignment operation which is
// (unfortunately) clobbering the incremented value.
In short, the statement has no effect.
The key points:
The value of a Postfix increment/decrement expression is the value of the operand before the increment/decrement takes place. (In the case of a Prefix form, the value is the value of the operand after the operation,)
the RHS of an assignment expression is completely evaluated (including any increments, decrements and/or other side-effects) before the value is assigned to the LHS.
Note that unlike C and C++, the order of evaluation of an expression in Java is totally specified and there is no room for platform-specific variation. Compilers are only allowed to reorder the operations if this does not change the result of executing the code from the perspective of the current thread. In this case, a compiler would be permitted to optimize away the entire statement because it can be proved that it is a no-op.
In case it is not already obvious:
"x = x++;" is almost certainly a mistake in any program.
The OP (for the original question!) probably meant "x++;" rather than "x = x++;".
Statements that combine auto inc/decrement and assignment on the same variable are hard to understand, and therefore should be avoided irrespective of their correctness. There is simply no need to write code like that.
Hopefully, code checkers like FindBugs and PMD will flag code like this as suspicious.
int x = 7;
x = x++;
It has undefined behaviour in C and for Java see this answer. It depends on compiler what happens.
A construct like x = x++; indicates you're probably misunderstanding what the ++ operator does:
// original code
int x = 7;
x = x++;
Let's rewrite this to do the same thing, based on removing the ++ operator:
// behaves the same as the original code
int x = 7;
int tmp = x; // value of tmp here is 7
x = x + 1; // x temporarily equals 8 (this is the evaluation of ++)
x = tmp; // oops! we overwrote y with 7
Now, let's rewrite it to do (what I think) you wanted:
// original code
int x = 7;
x++;
The subtlety here is that the ++ operator modifies the variable x, unlike an expression such as x + x, which would evaluate to an int value but leave the variable x itself unchanged. Consider a construct like the venerable for loop:
for(int i = 0; i < 10; i++)
{
System.out.println(i);
}
Notice the i++ in there? It's the same operator. We could rewrite this for loop like this and it would behave the same:
for(int i = 0; i < 10; i = i + 1)
{
System.out.println(i);
}
I also recommend against using the ++ operator in larger expressions in most cases. Because of the subtlety of when it modifies the original variable in pre- versus post-increment (++x and x++, respectively), it is very easy to introduce subtle bugs that are difficult to track down.
According to Byte code obtained from the class files,
Both assignments increment x, but difference is the timing of when the value is pushed onto the stack
In Case1, Push occurs (and then later assigned) before the increment (essentially meaning your increment does nothing)
In Case2, Increment occurs first (making it 8) and then pushed onto the stack(and then assigned to x)
Case 1:
int x=7;
x=x++;
Byte Code:
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iload_1 [x] //Push 7 onto stack
4 iinc 1 1 [x] //Increment x by 1 (x=8)
7 istore_1 [x] //Pop 7 and store in x
8 return //x now has 7
Case 2:
int x=7;
x=++x;
Byte Code
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iinc 1 1 [x] //Increment x by 1 (x=8)
6 iload_1 [x] //Push x onto stack
7 istore_1 [x] //Pop 8 and store in x
8 return //x now has 8
Stack here refers to Operand Stack, local: x index: 1 type: int
Post Increment operator works as follows:
Store previous value of operand.
Increment the value of the operand.
Return the previous value of the operand.
So the statement
int x = 7;
x = x++;
would be evaluated as follows:
x is initialized with value 7
post increment operator stores previous value of x i.e. 7 to return.
Increments the x, so now x is 8
Returns the previous value of x i.e. 7 and it is assigned back to x, so x again becomes 7
So x is indeed increased but since x++ is assigning result back to x so value of x is overridden to its previous value.
It's incremented after "x = x++;". It would be 8 if you did "x = ++x;".
The incrementing occurs after x is called, so x still equals 7. ++x would equal 8 when x is called
When you re-assign the value for x it is still 7. Try x = ++x and you will get 8 else do
x++; // don't re-assign, just increment
System.out.println(x); // prints 8
because x++ increments the value AFTER assigning it to the variable.
so on and during the execution of this line:
x++;
the varialbe x will still have the original value (7), but using x again on another line, such as
System.out.println(x + "");
will give you 8.
if you want to use an incremented value of x on your assignment statement, use
++x;
This will increment x by 1, THEN assign that value to the variable x.
[Edit]
instead of x = x++, it's just x++; the former assigns the original value of x to itself, so it actually does nothing on that line.
What happens when int x = 7; x = x++;?
ans -> x++ means first use value of x for expression and then increase it by 1.
This is what happens in your case. The value of x on RHS is copied to variable x on LHS and then value of x is increased by 1.
Similarly ++x means -> increase the value of x first by one and then use in expression .
So in your case if you do x = ++x ; // where x = 7
you will get value of 8.
For more clarity try to find out how many printf statement will execute the following code
while(i++ <5)
printf("%d" , ++i); // This might clear your concept upto great extend
++x is pre-increment -> x is incremented before being used
x++ is post-increment -> x is incremented after being used
int x = 7; -> x get 7 value <br>
x = x++; -> x get x value AND only then x is incremented
So this means:
x++ is not equal to x = x+1
because:
int x = 7; x = x++;
x is 7
int x = 7; x = x = x+1;
x is 8
and now it seems a bit strange:
int x = 7; x = x+=1;
x is 8
very compiler dependent!
Most simplest explanation!
This is because ++ after the operand makes post increment it, means first the value got assigned to the variable & then incremented. While if you're expecting x value to be 8 then you should pre increment it like the way mentioned below:
x = x++;
This is the post-increment operator. It should be understood as "Use the operand's value and then increment the operand".
If you want the reverse to happen i.e "Increment the operand and then use the operand's value", you must use the pre-increment operator as shown below.
x = ++x;
This operator first increments the value of x by 1 and then assigns the value back to x.
I think this controversy can be resolved without going into code & just thinking.
Consider i++ & ++i as functions, say Func1 & Func2.
Now i=7;
Func1(i++) returns 7, Func2(++i) returns 8 (everybody knows this). Internally both the functions increment i to 8 , but they return different values.
So i = i++ calls the function Func1. Inside the function i increments to 8, but on completion the function returns 7.
So ultimately 7 gets allocated to i. (So in the end, i = 7)
This is because you used a post-increment operator.
In this following line of code
x = x++;
What happens is that, you're assigning the value of x to x. x++ increments x after the value of x is assigned to x. That is how post-increment operators work. They work after a statement has been executed. So in your code, x is returned first after then it is afterwards incremented.
If you did
x = ++x;
The answer would be 8 because you used the pre-increment operator. This increments the value first before returning the value of x.

Iterator variable in Java for loops

Say I have this code
for (int i = 0; i < 6; i++) {
// do something in here
}
Will the variable i increment 5 times or 6 times? I had this question on an exam and wrote 6 because I thought that since i started at 0, it would need to be incremented 6 times in order to break the loop conditional.
The variable i will be incremented 6 times and the loop will run 6 times. After the last increment i will be equal to 6, the loop will see that the condition i < 6 is not met, and therefore will break out of the loop.
You should see the difference between an increment and an iteration.
i=0 at the beginning, the loop runs for the 1st time and i increments to 1
i=1 now, the loop runs for the 2nd time and i increments to 2
i=2 now, the loop runs for the 3rd time and i increments to 3
i=3 now the loop runs for the 4th time and i increments to 4
i=4 now, the loop runs for the 5th time and i increments to 5
i=5 now, the loop runs for the 6th time and i increments to 6
i=6 now, the loop does not run because i < 6 is not true and no increment happens
As you can see above, there were 6 iterations and 6 increments. Note that this may not always be the case where the number of iterations is equal to the number of increments/decrements.
If you define the variable i outside of the for loop and then print its value out after the loop is finished, you will see that i will be equal to 6.
Check this out:
int i;
for (i = 0; i < 6; i++) {
// do something in here
}
System.out.println(i);
as long as i = 0,1,2,3,4,5 the condition is true, so it should be 5 iterations.
(6 cycles)
You can also add System.out.print(i); to see the output.

Please explain why this code results in infinite loop [duplicate]

This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 7 years ago.
for (int i = 0; i < 10;) {
i=i++;
System.out.println("Hello World" );
}
Basically the value of i remains unchanged, and stays 0, so it is infinite. But Why doesnt it change?
If I changed i=i++ to i++, it works. (not infinite loop).
Because i++ increments i after the expression is evaluated so you are basically saying i = i. If you do i = ++i then it will work because it increments i before the expression is evaluated.
Logically, the assignment is done after evaluation of the right hand side, as for any other Java assigment. However, "The value of the postfix increment expression is the value of the variable before the new value is stored." (JLS, 15.14.2. Postfix Increment Operator ++)
The value of i before the incremented value is stored stays zero, because of the assignment.

I don't know why my variables are getting these values [duplicate]

This question already has answers here:
Java: Prefix/postfix of increment/decrement operators
(11 answers)
Closed 9 years ago.
public int Gauss_Jordan(double[][] matrix, int numOfRows, int numOfCols) {
for (int col_j = 0; col_j<numOfCols; col_j++) {
row_i = nonzeros ++;
System.out.println(row_i+" and "+nonzeros);
}
//return matrix;
return 0;
}
up above in the method called "Gauss_Jordan", you can see a for loop where it iterates until a certain condition is met. (duh.. lol sorry).
so i set row_i = nonzeros++ but here's the thing, when I print out each iteration i get
0 and 1,
1 and 2,
2 and 3
. I would expect the output to be:
1 and 1,
2 and 2,
3 and 3.
How come this is not the case?
You'd need ++nonzeros instead of nonzeros++ to get what you expect.
Thats called post-increment;
When you say row_i = nonzeros ++;
first the row_i will get assigned with the value of nonzeros and the nonzero will get incremented.
try pre-increment
row_i = ++nonzeros;
If pre-increment is not what you wanted. Check the initialization of nonzeros and change it into '1` for it to show up as you want. Your codes are functioning as they should.

Categories