Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

post vs pre increment implementation

  Asked By: Annie    Date: Apr 27    Category: Java    Views: 1335
  

i tried using the post increment and pre increment
operators in java and got intrigued by the way they
work.

below is my program and questions.

public class Meghna {

public static void main(String[] args) {
int a=1;

for(int i=0;i<2;i++)
{
System.out.println("a++="+ a++);
}

a=1;

for(int i=0;i<2;i++)
{
System.out.println("++a="+ ++a);
}

}
}

output

a++=1
a++=2
++a=2
++a=3

------------------------------

i am really curious to understand the physical
implementation of the post and pre increment operators
.

i.e what actually happens when i run the code. an
example i would like to give is the one below

for(i=o;i<2;i++)

here how does the program understand that it
shouldnt increment i for the first time when it
executes the loop and how does it know that it has to
increment i the 2nd time it executes the loop.

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Lela Lynch     Answered On: Apr 27

If I understood your problem correctly, in your class  the execution of for loop
is same in both the cases, i.e, first i=0, then it increments i to 1 since u
gave i++ and checks for i<2 and continue like. The difference is in 'a', value
Ist loop, when i=0, since it is a++ in ur print statement, a=1 in output, after
that it is incremented to 2 . so when i=1, a=2 in output, after which is
incremented to 3.
2nd loop, when i=0, since it is ++a in ur print statement, it is incremented to
2, so u get output as 2. When i=1, it is again incremented to 3 and output u get
is 3.

 
Answer #2    Answered By: Mark R     Answered On: Apr 27

In the following statement we must understand  that we need to print current
value of a and then increment.
System.out.println("a++="+ a++);

In the following statement we must understand that we will increment  a before
printing it.
System.out.println("++a="+ ++a);

 
Didn't find what you were looking for? Find more on post vs pre increment implementation Or get search suggestion and latest updates.




Tagged: