Java: Prefix/postfix of increment/decrement operators - java

From the program below or here, why does the last call to System.out.println(i) print the value 7?
class PrePostDemo {
public static void main(String[] args) {
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}

i = 5;
System.out.println(++i); //6
This prints out "6" because it takes i, adds one to it, and returns the value: 5+1=6. This is prefixing, adding to the number before using it in the operation.
i = 6;
System.out.println(i++); //6 (i = 7, prints 6)
This prints out "6" because it takes i, stores a copy, adds 1 to the variable, and then returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. The beauty of a postfix increment.
Then when you print out i, it shows the real value of i because it had been incremented: 7.

Another way to illustrate it is:
++i will give the result of the new i, i++ will give the result of the original i and store the new i for the next action.
A way to think of it is, doing something else within the expression. When you are printing the current value of i, it will depend upon whether i has been changed within the expression or after the expression.
int i = 1;
result i = ++i * 2 // result = 4, i = 2
i is evaluated (changed) before the result is calculated. Printing i for this expression, shows the changed value of i used for this expression.
result i = i++ * 2 // result = 2, i = 2
i is evaluated after the result in calculated. So printing i from this expression gives the original value of i used in this expression, but i is still changed for any further uses. So printing the value for i immediately after the expression, will show the new incremented value of i. As the value of i has changed, whether it is printed or used.
result i = i++ * 2 // result = 2, i = 2
System.out.println(i); // 2
If you kept a consistent pattern and included print lines for all the values:
int i = 3;
System.out.println(i); // 3
System.out.println(i++); // 3
System.out.println(i); // "4"
System.out.println(++i); // 5
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"

Think of ++i and i++ as similar to i = i+1. But it is not the same. The difference is when i gets the new increment.
In ++i , the increment happens immediately.
But if i++ is there, the increment will happen when the program goes to the next line.
Look at the code here.
int i = 0;
while(i < 10){
System.out.println(i);
i = increment(i);
}
private int increment(i){
return i++;
}
This will result in a nonending loop. Because i will be returned with the original value and after the semicolon, i will get incremented, but the returned value has not been. Therefore i will never actually returned as an incremented value.

Why wouldn't the variable have been updated?
Postfix: passes the current value of i to the function and then increments it.
Prefix: increments the current value and then passes it to the function.
The lines where you don't do anything with i make no difference.
Notice that this is also true for assignments:
i = 0;
test = ++i; // 1
test2 = i++; // 1

System.out.println(i++); // "6"
This sends println the value I had prior to this line of code (6), and then increments I (to 7).

An example of how the actual operators are implemented:
class Integer {
private int __i;
function Integer ++() { // Prefix operator i.e. ++x
__i += 1; // Increment
return this; // Return the object with the incremented value
}
function Integer ++(Integer x) { // Postfix operator, i.e., x++
__i+=1; // Increment
return x; // Return the original object
}
}

Maybe you can understand better Prefix/postfix with this example.
public class TestPrefixPostFix
{
public static void main (String[] args)
{
int x = 10;
System.out.println((x++ % 2 == 0) ? "yes " + x: " no " + x);
x = 10;
System.out.println((++x % 2 == 0) ? "yes " + x: " no " + x);
}
}

This may be easy to understand:
package package02;
public class C11PostfixAndPrefix {
public static void main(String[] args) {
// In this program, we will use the value of x for understanding prefix
// and the value of y for understaning postfix.
// Let's see how it works.
int x = 5;
int y = 5;
Line 13: System.out.println(++x); // 6 This is prefixing. 1 is added before x is used.
Line 14: System.out.println(y++); // 5 This is postfixing. y is used first and 1 is added.
System.out.println("---------- just for differentiating");
System.out.println(x); // 6 In prefixing, the value is same as before {See line 13}
System.out.println(y); // 6 In postfixing, the value increases by 1 {See line 14}
// Conclusion: In prefixing (++x), the value of x gets increased first and the used
// in an operation. While, in postfixing (y++), the value is used first and changed by
// adding the number.
}
}

It prints 7 for the last statement, because in the statement above, its value is 6 and it's incremented to 7 when the last statement gets printed.

This might help... it also took my to understand this puzzle.
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 5;
System.out.println(++x);
System.out.println(y++);
System.out.println("------");
System.out.println(x);
System.out.println(y);
}
}

Well, think of it in terms of temporary variables.
i = 3;
i ++; // Is equivalent to: temp = i++; and so, temp = 3 and then "i" will increment and become i = 4;
System.out.println(i); // Will print 4
Now,
i = 3;
System.out.println(i++);
is equivalent to
temp = i++; // 'temp' will assume a value of the current "i", after which "i" will increment and become i = 4
System.out.println(temp); // We're printing 'temp' and not "i"

Related

Increment in for loop give different answers [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 4 years ago.
class Test {
public static void main(String[] args) {
for (int i= 1; i < 2; i++) {
System.out.println(i);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
}
}
}
The output here is 1,2 and 1,3. We are doing post-increment and pre-increment in both the cases why I am getting different results?
Because post increment happens at the end of the iteration.
Hence the below code :
for (int i= 1; i < 2; i++) {
System.out.println(i);
System.out.println(++i);
Will work something like this:
int i = 1;
System.out.println(i); // i is still 1
System.out.println(++i); // pre increment making i to 2 and then print
i++;
if(i<2)
// iterate again
However, in second case:
int a = 1;
System.out.println(a++); // post increment first print 1 and then change a to 2
System.out.println(++a); // pre increment a now changed to 3
System.out.println(i); // 1 (initial value)
System.out.println(++i); // 2 (pre increment returns the value after increment)
int a = 1;
System.out.println(a++); // 1 (initial value prior to increment, since post increment
// returns the value prior to increment)
System.out.println(++a); // 3 (pre increment returns the value after increment)
The i++ in the loop's definition only takes place at the end of each iteration. You never print the value of i after i++ is executed, since the loop terminates after the first iteration.
BTW, if i++ was executed prior to System.out.println(i);, you'd still get a different output (compared to the last two println statements) - 2 followed by 3.
The general structure of a for loop (more precisely: this type of basic for statement) is:
for ([ForInit]; [Expression]; [ForUpdate]) Statement
The equivalent while loop is:
[ForInit];
while ([Expression]) {
Statement;
[ForUpdate];
}
In other words, the update is executed after the loop body.
So your code is equivalent to:
// ForInit
int i = 1;
while (/* Expression */ i < 2) {
// Statement
System.out.println(i);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
// ForUpdate
i++;
}
Hopefully it is then easy to see why there is a difference in the output.
In the first case, the post-increment is not called. If you understand how a for loop works, you will know that the increment section is not executed the very first time. The initialization section, here int i = 1, and the condition checking - i < 2 is validated. The increment section is invoked only after each iteration.
In the second case, the post-increment is performed and hence the difference in values. You should focus more on the basics of looping.
System.out.println(i);
i isn't postincremented here. The answers would be the same if it were:
System.out.println(i++);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
for (int i= 1; i < 2; **i++)**
doesn't do anything until a pass through loop is done.

understanding increment and decrement [duplicate]

From the program below or here, why does the last call to System.out.println(i) print the value 7?
class PrePostDemo {
public static void main(String[] args) {
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}
i = 5;
System.out.println(++i); //6
This prints out "6" because it takes i, adds one to it, and returns the value: 5+1=6. This is prefixing, adding to the number before using it in the operation.
i = 6;
System.out.println(i++); //6 (i = 7, prints 6)
This prints out "6" because it takes i, stores a copy, adds 1 to the variable, and then returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. The beauty of a postfix increment.
Then when you print out i, it shows the real value of i because it had been incremented: 7.
Another way to illustrate it is:
++i will give the result of the new i, i++ will give the result of the original i and store the new i for the next action.
A way to think of it is, doing something else within the expression. When you are printing the current value of i, it will depend upon whether i has been changed within the expression or after the expression.
int i = 1;
result i = ++i * 2 // result = 4, i = 2
i is evaluated (changed) before the result is calculated. Printing i for this expression, shows the changed value of i used for this expression.
result i = i++ * 2 // result = 2, i = 2
i is evaluated after the result in calculated. So printing i from this expression gives the original value of i used in this expression, but i is still changed for any further uses. So printing the value for i immediately after the expression, will show the new incremented value of i. As the value of i has changed, whether it is printed or used.
result i = i++ * 2 // result = 2, i = 2
System.out.println(i); // 2
If you kept a consistent pattern and included print lines for all the values:
int i = 3;
System.out.println(i); // 3
System.out.println(i++); // 3
System.out.println(i); // "4"
System.out.println(++i); // 5
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
Think of ++i and i++ as similar to i = i+1. But it is not the same. The difference is when i gets the new increment.
In ++i , the increment happens immediately.
But if i++ is there, the increment will happen when the program goes to the next line.
Look at the code here.
int i = 0;
while(i < 10){
System.out.println(i);
i = increment(i);
}
private int increment(i){
return i++;
}
This will result in a nonending loop. Because i will be returned with the original value and after the semicolon, i will get incremented, but the returned value has not been. Therefore i will never actually returned as an incremented value.
Why wouldn't the variable have been updated?
Postfix: passes the current value of i to the function and then increments it.
Prefix: increments the current value and then passes it to the function.
The lines where you don't do anything with i make no difference.
Notice that this is also true for assignments:
i = 0;
test = ++i; // 1
test2 = i++; // 1
System.out.println(i++); // "6"
This sends println the value I had prior to this line of code (6), and then increments I (to 7).
An example of how the actual operators are implemented:
class Integer {
private int __i;
function Integer ++() { // Prefix operator i.e. ++x
__i += 1; // Increment
return this; // Return the object with the incremented value
}
function Integer ++(Integer x) { // Postfix operator, i.e., x++
__i+=1; // Increment
return x; // Return the original object
}
}
Maybe you can understand better Prefix/postfix with this example.
public class TestPrefixPostFix
{
public static void main (String[] args)
{
int x = 10;
System.out.println((x++ % 2 == 0) ? "yes " + x: " no " + x);
x = 10;
System.out.println((++x % 2 == 0) ? "yes " + x: " no " + x);
}
}
This may be easy to understand:
package package02;
public class C11PostfixAndPrefix {
public static void main(String[] args) {
// In this program, we will use the value of x for understanding prefix
// and the value of y for understaning postfix.
// Let's see how it works.
int x = 5;
int y = 5;
Line 13: System.out.println(++x); // 6 This is prefixing. 1 is added before x is used.
Line 14: System.out.println(y++); // 5 This is postfixing. y is used first and 1 is added.
System.out.println("---------- just for differentiating");
System.out.println(x); // 6 In prefixing, the value is same as before {See line 13}
System.out.println(y); // 6 In postfixing, the value increases by 1 {See line 14}
// Conclusion: In prefixing (++x), the value of x gets increased first and the used
// in an operation. While, in postfixing (y++), the value is used first and changed by
// adding the number.
}
}
It prints 7 for the last statement, because in the statement above, its value is 6 and it's incremented to 7 when the last statement gets printed.
This might help... it also took my to understand this puzzle.
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 5;
System.out.println(++x);
System.out.println(y++);
System.out.println("------");
System.out.println(x);
System.out.println(y);
}
}
Well, think of it in terms of temporary variables.
i = 3;
i ++; // Is equivalent to: temp = i++; and so, temp = 3 and then "i" will increment and become i = 4;
System.out.println(i); // Will print 4
Now,
i = 3;
System.out.println(i++);
is equivalent to
temp = i++; // 'temp' will assume a value of the current "i", after which "i" will increment and become i = 4
System.out.println(temp); // We're printing 'temp' and not "i"

how i = i++ is returning 10 and when doing k = i++ the value of i returns 11 where i=10 and k=0? [duplicate]

This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 6 years ago.
I want to know that when i=10 and k=0 then and when i am trying to print the value of i when i am doing like this :
case 1 : i = i++;
It's printing i=10 where
case 2 : k = i++;
It's printing i = 11;
I want to know how exactly doing this operation? because in both cases i++ is doing and after then i am printing the value of i?
if in the second case i am getting i=11; then i should get 11 in case 1 also. Please someone explain me the process?
The Code is like this :
public class Case1{
public static void main(String[] a){
int i = 10;
i = i++;
System.out.println(i);
}
}
It's giving ans : 10;
and
public class Case1{
public static void main(String[] a){
int i = 10;
int k = 0;
k = i++;
System.out.println(i);
}
}
Here the ans is coming as 11.
Now please explain me both the cases like how it's doing in the first program i = 10 and in second program 11 as ans.
The expression i++ increments the value of i by 1 and returns the value of i before the increment was done. So in case 1, i++ changes the value of i to 11 but returns the value 10, which you then assign back to i, effectively undoing the increment.
Case 2 is different because you're assigning the result of i++ to a different variable, so the increment is not undone. k holds the value 10 and i holds the value 11.
In the first case, the side effect of ++ is applied to i before the assignment is performed:
i++ is evaluated; the result is 10 (remember, it's a post-increment!)
i+1 is stored in i, which briefly becomes 11 (but nobody "sees" it, because it gets overwritten)
The result of the evaluation of pre-increment, i.e. 10, is written back to i
When you make an assignment to k, there is no double-writing to i:
i++ is evaluated; the result is 10
i+1 is stored in i, which becomes 11, and stays like that
The result of the evaluation, i.e. 10, is written to k, which becomes 10
Your first code is similar to this:
public class Case1{
public static void main(String[] a){
int i = 10; // i becomes 10
int tmp = i; // tmp becomes 10
i = i + 1; // i becomes 11
i = tmp; // i becomes tmp's value, which is 10
System.out.println(i); // The result is 10
}
}
and second code to this:
public class Case1{
public static void main(String[] a){
int i = 10; // i becomes 10
int k = 0; // k becomes 0
int tmp = i; // tmp becomes 10
i = i + 1; // i becomes 11
k = tmp; // k becomes tmp's value, which is 10
System.out.println(i); // The result is 11 as you print the i.
// If k was printed, it would be 10 like in example 1.
}
}
ok dude,first i wrote sample program below please check this and will explain you
import java.util.*;
public class StackTest {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int num=sc.nextInt();
int i=10;
int k;
switch(num){
case 1:
i=i++;
System.out.println("case1:"+i);
break;
case 2:
k=i++;
System.out.println("case2:"+i);
break;
default:break;
}
}
}
Here u doubt is first case u may pass num is 1 result is:10,
second case u may pass num is 2 result is:11 right.
ok i am going to give clarity on this. First case what happens means that 'i' value is not incremented just the 10 is assigned to same memory allocated variable like 'i'
but in second case the incremented result 'i' value is assigned to some other new variable like k ,here result is will allocate to k and print 11
see this u can understand and get both cases 11 as outout
import java.util.*;
public class StackTest1 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int num=sc.nextInt();
int i=10;
int k;
switch(num){
case 1:
k=i++;
System.out.println("case1:"+i);
break;
case 2:
k=i++;
System.out.println("case2:"+i);
break;
default:break;
}
}
}
i think this answear is satisfy you.Thank you

Explaining output in a for loop

I'm a novice in Java programming and I'm trying to guess why the output of the following code:
public class ForLoop {
public static void main(String[] args) {
int x;
for (x=1; x<=2; x++) {
x += 3;
}
System.out.print(x);
}
}
is 5 and not 7! For the first iteration, 1 is added to 3 (result: 4) and it is stored in the variable x so x is 4. In the second iteration, we add 3 to 4 and we must obtain 7. The error might be easy to find but I can't catch it. Please help and thanks.
This part:
for (x=1; x<=2; x++)
means that x will be incremented at the end of each iteration. So, in the first iteration, 3 is added to x because of this:
x += 3;
which results in a value of 4. Then, at the end of that iteration, x is incremented by 1, which comes to 5. Since 5 is greater than 2, the loop is then closed.
Big problem here using x as your iterator and your variable to update. This is what the computer is evaulating.
When you are inside the for loop, x is initially 1, then you add three to it, and then your iterator on the for loop adds 1 to it afterwards (making it five). At that point, your condition, (x<=2) is false for the for loop is complete.
change it to this and you will get your desired result:
public class ForLoop {
public static void main(String[] args) {
int x = 1;
for (int y = 0; y <= 1; y++) {
x += 3;
}
System.out.print(x);
}
}
In first pass the body is carried out, there x becomes 4. Then the incrementation is carried out. (The 3rd parameter of for loop) which results x to be 5.
In the second pass the condition is unmet as x is already 5 there but less than or equals to 2 is required to run the loop. So instead the loop will discontinue and x will be printed 5.
The code
int x;
for (x=1; x<=2; x++) {
x += 3;
}
works as follows:
int x;
x = 1; // for-initialization
while (x <= 2) { // for-condition
x += 3; // for-body
x++ // for-increment
}
Particularly:
the condition is tested before the loop body, and in your case
the loop body has an effect on the condition.
After the first iteration x is 4 as you say, but then x++ is executed, so x becomes 5. 5 is bigger than 2 (x<=2), so iteration stops.

do-while loop using IF

I am using if condition statement with a do while loop. I want that everytime when the compiler runs the program it should print the statement in the" IF " till it reaches less then 15 what is happening is that the job is going quite well in do-while loop but the statement in" IF " only printed once? Where am i going wrong. If someone explains the flow it would be really appreciated as i am a beginner. Please see below for the code :
package loopexamples2;
public class DoWhileLoop {
public static void main(String[] args) {
int n = 1;
if(n<15)
System.out.println("print value of n is equal to"+ n);
do {
System.out.println(n);
n++;
}
while(n<10);
}
}
output--> print value of n is equal to1
1
2
3
4
5
6
7
8
9
Your if statement is outside your do while loop. Put it inside the do {} block
package loopexamples2;
public class DoWhileLoop {
public static void main(String[] args) {
int n = 1;
do {
if(n<15) {
System.out.println("print value of n is equal to"+ n);
}
System.out.println(n);
n++;
}
while(n<10);
}
}
You're looking for something closer to this:
while(n<15) {
System.out.println("print value of n is equal to"+ n);
n++
}
The block of code within { and } will be run constantly until n reaches a value greater or equal to 15.
With your current code, the full print statement is only output once, as it isn't included in your while loop.
I explain the workflow, since you are a beginner:
int n = 1;
1 is assigned to n.
if(n<15)
System.out.println("print value of n is equal to"+ n);
The program check if n is less than 15. it is the case, so it execute the action: print "print value of n is equal to" + n. It only does that once. It's not a while or a for loop that execute a loop repeatedly.
do {
System.out.println(n);
n++;
}
while(n<10);
}
Here the program execute everything between the { and the } until n=10.
You are saying "it should print the statement in the" IF " till it reaches less then 15"
Then you need a similar do/while loop:
do {
System.out.println("print value of n is equal to"+ n);
n++
}
while (n<15);
I want that everytime when the compiler runs the program it should print the statement in the" IF " till it reaches less then 15
Since you are using n<10 condition in do while loop , the loop will not proceed beyond n=9 . So it won't reach n=15.
I guess this is what you want:
package loopexamples2;
public class DoWhileLoop {
public static void main(String[] args) {
int n = 1;
do {
System.out.println("print value of n is equal to"+ n);
n++;
} while(n<10);
}
}
Code flow:
int n = 1; Assigns n to 1
do { Repeat code between braces from here until while.
System.out.println("print value of n is equal to"+ n); Prints print value of n is equal to1
n++; Increments n by 1, so n = 2
} while(n<10); Is n < 10? Yes so repeat from do
System.out.println("print value of n is equal to"+ n); Prints print value of n is equal to2
n++; Increments n by 1, so n = 3
} while(n<10); Is n < 10? n = 3 so yes, repeat from do
[ ...same thing repeats until... ]
System.out.println("print value of n is equal to"+ n); Prints print value of n is equal to9
n++; Increments n by 1, so n = 10
} while(n<10); Is n < 10? n = 10 so no, exit loop.
End of program.
The statement inside the IF is passed only once. Since it is not inside any loop.
The flow of the program is procedural. So the execution is from top to bottom. It first pass the IF block, executes it, procedes to the next line, finds the do-while block which is loop until the while condition is met. Loops only iterates on it's block and not on lines before it.
First off you need to put the if() statement INSIDE the do while loop. otherwise the program only sees the if once.
the next thing you're doing is in your statement:
do {
System.out.println(n);
n++;
}
while(n<10);
you have it only going until n is less then 10, you want it to be less then 15.
I assume you wan't it to print out 15 as well so you can change
while(n < 10)
to
while(n <= 15)
so all together your code would look like this:
package loopexamples2;
public class DoWhileLoop {
public static void main(String[] args) {
int n = 1;
do {
if(n <= 15){
System.out.println("The value of n is equal to " + n);
n++;
} while(n <= 15);
}
}
note <= means "less then or equal to"
You can refer this any time...
It will be more helpful to you..
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html

Categories

Resources