How does the following statement work? - java

int x = 10;
x += x++;
System.out.println(x);
why the answer of above statement is 20 ?

The operator += is an addition assignment operator. Like Alya said above, x += x++ is equivalent to x = x + x++, which in your case is x = 10 + 10. However, it's a very messy statement and I'll explain why towards the end of this post.
Now, you're probably thinking "Why is it 20 and not 21 (10 + 11) since you have the ++?" and that's valid. There's actually a difference between a post-increment and a pre-increment. x++ is the post-increment and will actually evaluate the value of x first and THEN increment x, while ++x is the pre-increment which will increment x and THEN evaluate the value of x.
For example, x = 10; System.out.println(x++); System.out.println(x); will print 10 and then print 11 because the first print line prints x and THEN performs the ++ calculation, making x 11 which the next line prints. Conversely, x = 10; System.out.println(++x); System.out.println(x); will print 11 on both print statements.
Going back to why I said x += x++; is very messy is because technically the ++ operator isn't performed in this case. x++ is technically the same as x=x+1 and remembering that x+=y is the same as x = x+y) , the line x += x++; is kind of like saying x = x + (x = x + 1); which is kind of weird looking because you do 2 assignment statements in one and won't actually "work how you want it". Back to your example int x = 10; x += x++; if you print x, you will get 20 even though you could look at it as: x is now the value of x + the value of x, then finally + 1 to it. But unfortunately, that's not how it works.
To solve your problem, if you change your code from a post-increment to a pre-increment, then it should work, ie: x+=++x; will print your 11 but I would argue the that's quite unreadable and a bit confusing. x+=x; x++; System.out.println(x); is easier to follow.

x++ will execute first. It returns x and then increments x by 1.
Finally, the += operator will add to x the return value of x++, which was 10.
Thus, x will be 20 and it will overwrite the changes to x by the statement x++.

So first x is initialized to be 10. Then the x++ has higher precedence so that gets carried out first. the "++" is a post-increment in this case (because it is after the variable as opposed to pre-increment which would be ++x). Post-increment means "first use the variable then increment it by one" so in this case it first uses x to be 10 then increments it to 11 after it is used. Then we look at the "+=" which is short hand for "x = x+x++". so we have x = 10+10 which = 20. If you were to carry this out again it would equal x = 20+20 = 40.
In this particular case, the x++ isn't necessary as x is reassigned the value after it is incremented each time.

int x = 10; x += x++;
will equal to x=x+x
where x++ mean use the x value then increament it , so it's value will be 10
so the result will equal 20
if you want to see the change of the x , see this example:
int x = 10;
int y = 10;
y +=x++;
System.out.println(y);
System.out.println(x);
will print :
y=20
x=11////////////according to x++ and without to overwrite it

//
// Shows how increments work.
//
int i = 0;
System.out.println(i);
i++; // Add one
System.out.println(i);
i += 2; // Add two
System.out.println(i);
i += 3; // Add three
System.out.println(i);
++i; // Add one
System.out.println(i);
i += i; // Added itself
System.out.println(i);
//
// Uses increments and assigns.
//
int v = 0;
v = i++; // Increment after value copy
System.out.println(v);
System.out.println(i);
v = ++i; // Increment before value copy
System.out.println(v);
System.out.println(i);
//Output
0 -
1
3
6
7
14
14
15
16
16

x+=x++ first assigns the value to x and then increments (post-increment)
x+=++x first increments then assign the value to x (pre increment)
there are two types of increments/decrements in programming
1. pre-increment/decrement
2. post-increment/decrement
In programming both of these have same operations but differ in there nature as they both used for increment or decrement; they can be written as,
x+=1; (increment by 1)
x-=1; (decrement by 1)
you can use a variable instead in the above cases as well

Related

Possible incorrect operators priority

Consider the following pseudo-code:
int x = 10;
int y = 10;
x = x + x++;
y = y++ + y;
print(x); // 20
print(y); // 21
C-like programming languages like C# or Java say that increment has higher precedence, than + operator. So it should be 21 in both cases.
Why does it print two different results?
Remember we work from left to right.
Let's deal with x first then y.
x
x = x + x++;
We are going from left to right...
x = 10 + (10++)
Note: As we go from left to right the post increment operator on x on the far right has no effect on the x which appears first on the RHS.
x = 20
y
y = y++ + y;
y = 10++ + 11;
Again we go from left to right, the increment operator post increments y from 10 to 11, hence the y on the far right becomes 11, thus yielding (10 + 11) = 21.
When y++ + y is evaluated, y++ is evaluated before y. So the left hand side is evaluated to 10, and the right hand side will be evaluated to 11 due to the previous incrementation.
When x + x++ is evaluated, x is evaluated before x++. So both sides will be evaluated to 10, then x will be evaluated to 11 just before the = operand will evaluate x to 20.
I believe the + operator has higher precedence than ++, so the + operator is evaluated first, but in order to evaluate it - it must evaluate the left and right operators of it.
In the second example the left operator is evaluated first so y increments before the right hand is evaluated.
In the Precedence and Order of Evaluation documentation, you can see that + is above += which is basically what ++ is. Above the + is the prefix ++ which is not to be confused with the postfix ++.

Java Increment / Decrement Operators - How they behave, what's the functionality?

It's been 3 days since I start to learn Java.
I have this program and I don't understand code in main method with ++ and -- operators. I don't even know what to call them(name of these operators)
Can anyone explain me what's all about.
class Example {
public static void main(String[] args) {
x=0;
x++;
System.out.println(x);
y=1;
y--;
System.out.println(y);
z=3;
++z;
System.out.println(z);
}
}
These are called Pre and Post Increment / Decrement Operators.
x++;
is the same as x = x + 1;
x--;
is the same as x = x - 1;
Putting the operator before the variable ++x; means, first increment x by 1, and then use this new value of x
int x = 0;
int z = ++x; // produce x is 1, z is 1
int x = 0;
int z = x++; // produce x is 1, but z is 0 ,
//z gets the value of x and then x is incremented.
++ and -- are called increment and decrement operators.
They are shortcuts for writing x = x+1 (x+=1) / x = x-1 (x-=1). (assumed that x is a numeric variable)
In rare cases you could worry about the precedence of the incrementation/decrementation and the value the expression returns: Writing ++x it means "increment first, then return", whereas x++ means "return first, then increment". Here we can distinguish between pre- and post increment/decrement operators.

Loops in Java not adhering to the condition?

I've been scratching my head over why Java will go beyond a specified condition in some loops, while seemingly adhering to the condition in other loops. I know it's a lack of understanding on my part, but I'm confused as to when I should go over or adhere to the condition when I'm manually calculating code.
As an example, I've put in a short for loop which has an end result of 15 in iTotal, and 0 in iNumber. When I originally did the calculation on paper step by step, I ended up with the answers of 14 in iTotal, and 1 in iNumber. I assumed that the code would not go below one, as the condition was greater than zero, not equal to or greater than zero.
My original attempt -
iTotal
0
5
9
12
14
iNumber
5 4 3 2 1
int iTotal = 0;
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
In comparison, the below code snippet will at 19 with a condition of less than 20, with the last statement being value of x : 19. I calculated that correctly, but I'm not sure why the above code ignores the condition and goes to zero, while the below code adheres to the condition and stops at 19.
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
Could anyone clarify how java interprets when to go over or stop at specified conditions?
In comparison, the below code snippet will at 19 with a condition of
less than 20, with the last statement being value of x : 19. I
calculated that correctly, but I'm not sure why the above code ignores
the condition and goes to zero, while the below code adheres to the
condition and stops at 19.
What you said is incorrect. The last statement printed is 19 but the last value of x is 20. This loop that you have given does in fact execute 20 times. A for loop in Java like the one you given has 3 components an integer to use as a count, a condition to test, and how to transform the count variable. In a general form it looks like this:
for(count variable, condition, transformation){
//Code goes here
//End loop
}
This for loops executes until the condition is no longer true, which is caused by applying a transformation of some sort the count variable.
Using the for loop you gave as an example:
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
We create the count variable (int x) and set it equal to 10.
We check the count variable (int x) against the condition ( x<20 ) and evaluate the result, x < 20 == true so the code within the loop is run. At the end of the code, which I have marked "End Loop" above the transformation (x + 1) is applied to the count variable before the condition is tested again to see if the loop should proceed.
x = 11 now because x was equal to 10 but we added one as specified at the end of last loop. x < 20 == true is still true so the code within the loop will be executed again. This is continued in this way until the last number.
When x = 19 we test against the condition as we have been doing and see if x < 20 == true is still true, which it is so the code is executed. When the code execution ends, the count variable is again incremented, so x = 20.
With x = 20we once again test against x < 20. This time x < 20 == false so the code inside the loop is not executed nor is another transformation applied to the variable. At this point, when the condition becomes false the loop ends. So because we said x < 20 and not x <= 20 on the 20th loop, when x = 20, this code:
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
will not run. This means that the final output of the program would occur when x = 19 not when x=20 although if you were still able to access the count variable after the loop ends (which I believe you can do with a debugger) you would see x=20
The first loop does this:
iTotal = 0
iTotal = 5
iTotal = 9
iTotal = 12
iTotal = 14
iTotal = 15
Loop end
also as the first loops transformation is written as x-- instead of x - 1 the second loop can be rewritten as:
for(int x = 10; x < 20; x++) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
in Java the ++ operator increments by 1, it is the same as x+1.
Your first loop
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
is 5+4+3+2+1 = 15 (you must have printed iTotal before you added the first iNumber). Your second loop is similar the loop body isn't entered when the condition evaluates to false.
int x = 10;
for(; x < 20; x = x+1) {
System.out.print(x + " ");
}
System.out.println(x); // x is 20
as 10,11,12,13,14,15,16,17,18,19,20 but at twenty the loop terminates.
The condition is checked before each loop, not after. So in your first example, the logic would go:
iNumber = 5
first loop iteration
check iNumber > 0. 5 > 0, so continue the loop
add 5 to iTotal (iTotal=5 after this)
decrement iNumber
second loop iteration
check iNumber > 0. 4 > 0, so continue the loop
add 4 to iTotal (iTotal=9 after this)
decrement iNumber
...
fifth loop iteration
check iNumber > 0. 1 > 0, so continue the loop
add 1 to iTotal (iTotal=15 after this)
decrement iNumber
sixth loop iteration
check iNumber > 0. 0 > 0 is false, so break out of the loop
A similar process happens with the second loop.

Increment X Mod N in One Line

I have several small programs that require infinitely looping over the integer set Z sub n. I often write the code in this manor:
int x = 0;
int n = 13; //or some other prime
while(1) {
//do stuff dependent on x
++x;
x %= n;
}
I write code mostly in C/C++ & Java so I was wondering:
Is there a way to increment x mod n in one line rather then two in either language?
Have you considered:
x = (x + 1 == n ? 0: x + 1);
The chances are the x + 1 will optimise to one instruction and at least you are guaranteed to never use division (which a bad optimiser might use when % is involved).
x = (x + 1) % n;
Not terribly surprising.
Another alternative is this
x = ++x % n; // Java
if (++x == n) x = 0;
Using x = (x + 1 == n ? 0 : x + 1); requires two additions: one for the comparison and another when the value of x is set to x + 1.

Is there a difference between x++ and ++x in java?

Is there a difference between ++x and x++ in java?
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
yes
++x increments the value of x and then returns x
x++ returns the value of x and then increments
example:
x=0;
a=++x;
b=x++;
after the code is run both a and b will be 1 but x will be 2.
These are known as postfix and prefix operators. Both will add 1 to the variable but there is a difference in the result of the statement.
int x = 0;
int y = 0;
y = ++x; // result: x=1, y=1
int x = 0;
int y = 0;
y = x++; // result: x=1, y=0
Yes,
int x=5;
System.out.println(++x);
will print 6 and
int x=5;
System.out.println(x++);
will print 5.
In Java there is a difference between x++ and ++x
++x is a prefix form:
It increments the variables expression then uses the new value in the expression.
For example if used in code:
int x = 3;
int y = ++x;
//Using ++x in the above is a two step operation.
//The first operation is to increment x, so x = 1 + 3 = 4
//The second operation is y = x so y = 4
System.out.println(y); //It will print out '4'
System.out.println(x); //It will print out '4'
x++ is a postfix form:
The variables value is first used in the expression and then it is incremented after the operation.
For example if used in code:
int x = 3;
int y = x++;
//Using x++ in the above is a two step operation.
//The first operation is y = x so y = 3
//The second operation is to increment x, so x = 1 + 3 = 4
System.out.println(y); //It will print out '3'
System.out.println(x); //It will print out '4'
Hope this is clear. Running and playing with the above code should help your understanding.
I landed here from one of its recent dup's, and though this question is more than answered, I couldn't help decompiling the code and adding "yet another answer" :-)
To be accurate (and probably, a bit pedantic),
int y = 2;
y = y++;
is compiled into:
int y = 2;
int tmp = y;
y = y+1;
y = tmp;
If you javac this Y.java class:
public class Y {
public static void main(String []args) {
int y = 2;
y = y++;
}
}
and javap -c Y, you get the following jvm code (I have allowed me to comment the main method with the help of the Java Virtual Machine Specification):
public class Y extends java.lang.Object{
public Y();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_2 // Push int constant `2` onto the operand stack.
1: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
2: iload_1 // Push the value (`2`) of the local variable at index `1` (`y`)
// onto the operand stack
3: iinc 1, 1 // Sign-extend the constant value `1` to an int, and increment
// by this amount the local variable at index `1` (`y`)
6: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
7: return
}
Thus, we finally have:
0,1: y=2
2: tmp=y
3: y=y+1
6: y=tmp
When considering what the computer actually does...
++x: load x from memory, increment, use, store back to memory.
x++: load x from memory, use, increment, store back to memory.
Consider:
a = 0
x = f(a++)
y = f(++a)
where function f(p) returns p + 1
x will be 1 (or 2)
y will be 2 (or 1)
And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.
Generally, just use x = x + 1. It's way simpler.
Yes.
public class IncrementTest extends TestCase {
public void testPreIncrement() throws Exception {
int i = 0;
int j = i++;
assertEquals(0, j);
assertEquals(1, i);
}
public void testPostIncrement() throws Exception {
int i = 0;
int j = ++i;
assertEquals(1, j);
assertEquals(1, i);
}
}
Yes, using ++X, X+1 will be used in the expression. Using X++, X will be used in the expression and X will only be increased after the expression has been evaluated.
So if X = 9, using ++X, the value 10 will be used, else, the value 9.
If it's like many other languages you may want to have a simple try:
i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check
If the above doesn't happen like that, they may be equivalent
Yes, the value returned is the value after and before the incrementation, respectively.
class Foo {
public static void main(String args[]) {
int x = 1;
int a = x++;
System.out.println("a is now " + a);
x = 1;
a = ++x;
System.out.println("a is now " + a);
}
}
$ java Foo
a is now 1
a is now 2
OK, I landed here because I recently came across the same issue when checking the classic stack implementation. Just a reminder that this is used in the array based implementation of Stack, which is a bit faster than the linked-list one.
Code below, check the push and pop func.
public class FixedCapacityStackOfStrings
{
private String[] s;
private int N=0;
public FixedCapacityStackOfStrings(int capacity)
{ s = new String[capacity];}
public boolean isEmpty()
{ return N == 0;}
public void push(String item)
{ s[N++] = item; }
public String pop()
{
String item = s[--N];
s[N] = null;
return item;
}
}
Yes, there is a difference, incase of x++(postincrement), value of x will be used in the expression and x will be incremented by 1 after the expression has been evaluated, on the other hand ++x(preincrement), x+1 will be used in the expression.
Take an example:
public static void main(String args[])
{
int i , j , k = 0;
j = k++; // Value of j is 0
i = ++j; // Value of i becomes 1
k = i++; // Value of k is 1
System.out.println(k);
}
The Question is already answered, but allow me to add from my side too.
First of all ++ means increment by one and -- means decrement by one.
Now x++ means Increment x after this line and ++x means Increment x before this line.
Check this Example
class Example {
public static void main (String args[]) {
int x=17,a,b;
a=x++;
b=++x;
System.out.println(“x=” + x +“a=” +a);
System.out.println(“x=” + x + “b=” +b);
a = x--;
b = --x;
System.out.println(“x=” + x + “a=” +a);
System.out.println(“x=” + x + “b=” +b);
}
}
It will give the following output:
x=19 a=17
x=19 b=19
x=18 a=19
x=17 b=17
public static void main(String[] args) {
int a = 1;
int b = a++; // this means b = whatever value a has but, I want to
increment a by 1
System.out.println("a is --> " + a); //2
System.out.println("b is --> " + b); //1
a = 1;
b = ++a; // this means b = a+1
System.out.println("now a is still --> " + a); //2
System.out.println("but b is --> " + b); //2
}
With i++, it's called postincrement, and the value is used in whatever context then incremented; ++i is preincrement increments the value first and then uses it in context.
If you're not using it in any context, it doesn't matter what you use, but postincrement is used by convention.
There is a huge difference.
As most of the answers have already pointed out the theory, I would like to point out an easy example:
int x = 1;
//would print 1 as first statement will x = x and then x will increase
int x = x++;
System.out.println(x);
Now let's see ++x:
int x = 1;
//would print 2 as first statement will increment x and then x will be stored
int x = ++x;
System.out.println(x);
Try to look at it this way:
from left to right do what you encounter first. If you see the x first, then that value is going to be used in evaluating the currently processing expression, if you see the increment (++) first, then add one to the current value of the variable and continue with the evaluation of the expression. Simple

Categories