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.
Related
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.
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.
I was asked a question what the difference is between having counter += 5 and counter + 5 in the java programming language. I said they essentially do the same thing but I did not know how to explain why. I felt one was considered a shorthand representation of the same problem but now thinking about it more, I feel I am not correct. Can anyone give me a simple explanation the difference between them?
counter += 5 modifies counter. counter += 5 can be used as a statement (e.g. line of code) on its own, because it does something (increments counter by 5).
counter + 5 does not modify anything. counter + 5 can only be used as an expression within a statement, because it doesn't do anything on its own.
Here is some code that demonstrates the difference:
int counter = 1;
System.out.println(counter + 5); // 6
System.out.println(counter); // 1
// counter + 5; // not a valid statement
counter += 5; // counter is now 6
System.out.println(counter); // 6
System.out.println(counter += 5); // 11
System.out.println(counter); // 11
counter += 5 is assigning the value of whatever counter was plus 5 to the counter variable while counter+5 is return the result of 5 plus counter but the counter variable stays the same.
+= operator
For example you have a a variable counter that equals 3. When you do counter += 5, you are actually assigning a new value to the variable counter. so if counter was 5 and you do counter+=3, counter will now equal 8.
+ operator without the equal
In this case if your counter equals 3. when you do counter+3 it will return 8 for that instance but your counter will still be 3.
Code to demonstrate the differences:
int counter = 3;
counter += 5;
int y = 0;
/*this will return 8, since the result of 5 and counter was newly assigned to
counter*/
System.out.println(counter);
//resetting counter value.
counter =3;
y = counter+5;
//here counter still remains at 3, because there wasn't anything assigned to it
System.out.println(counter);
//will return 8, because you assigned the result of counter and 5 to y.
System.out.println(y);
Only the JLS holds the true answer!
(Assuming count is a numeric type. If it's a String, for example, then everything everyone told you above is wrong at the time I wrote this.)
+= operator
JLS 15.26.2 Compound Assignment Operators:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
following,
[...] the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator.
[...] the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.
(emphasis mine). In the above above notation, E1 and E2 will perform the operation indicated by += (meaning E1 + E2). The result is stored in E1.
+ operator
JLS 15.18.2. Additive Operators (+ and -) for Numeric Types:
The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.
Note that there is no assignment here.
counter += 5 is the one that is shorthand, but it's shorthand for counter = counter + 5. counter + 5 is just an expression, what you get is a value that is 5 greater than the value of counter, but this value is just left behind and nothing is done with it. In order for something else to happen, an additional operator needs to be present, such as the =, or assignment operator. This operator takes an expression on the right hand side and an identifier on the left, evaluating the expression and assigning the result to the identifier. Without assignment, values don't change, and even when you use methods that seem to change values without assignment (String.append() for example) there is an assignment hidden in the code of the function. As an added fact, counter += 5 can be reduced (if you really want to call it reducing it) to counter++ used 5 times.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to understand how can the int x be incremented inside an if (Boolean expression) for every loop iteration
How is that possible?? How does it work?
public class MethodsTest {
public static void main(String[] args) {
int x= 0;
for (int z = 0; z < 5; z++)
{
if(x++ > 2){
}
System.out.println(x);
}
}
}
the output will be
1
2
3
4
5
x++ is a compound assignment operator, which is equivalent to x = x + 1, with the side effect taking place after the evaluation. Therefore, the if statement is equivalent to a pair of statements like this:
if(x > 2) {
x = x + 1;
// At this point, the side effect has taken place, so x is greater than it was before the "if"
...
} else {
// The side effect takes place regardless of the condition, hence the "else"
x = x + 1;
}
Note that this code is forced to repeat the x = x + 1 part. Using ++ lets you avoid this repetition.
There is a pre-increment counterpart of x++ - namely, ++x. In this form the assignment takes place before the expression is evaluated, so the condition becomes
if ((x = x + 1) > 2) {
// Note that the condition above uses an assignment. An assignment is also an expression, with the result equal to
// the value assigned to the variable. Like all expressions, it can participate in a condition.
}
To break your notion that the condition of an if can't "do things", imagine that you have a function that returns a boolean, like:
boolean areThereCookies(int numCookies)
{
return numCookies > 0;
}
then you could use it in your if statement:
if (areThereCookies(cookies))
{
eatCookies(cookies);
}
However the method areThereCookies(int) that we are calling to evaluate the if condition could be making anything in the world. It could change variable values, read input, write output, steal cookies...
So the language is perfectly capable of "doing things" in the if evaluation. The other answers explain what your code was specifically doing.
Cheers.
You are allowed to have expressions inside a if statement as long as the expression resolves to a boolean. For example,
int i = 0
if (i = i + 1)
is not a valid expression inside an if statement because the expressions resolves to 1, which is an integer.
However,
int i = 0
if (2 == i = 2)
is a valid expression because 2 is first assigned to the variable i and then is compared to 2, and thus the expression resolves to “true”.
In your example if statement, you have a post-incremented variable x that is compared against 2 with the greater than operator, resulting in a boolean value, and thus it is a valid expression. Hotlinks has described what a post-incremented variable is in the comments.
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.