wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Basic Q Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Basic Q" Watch "Basic Q" New topic
Author

Basic Q

Pooja K
Greenhorn

Joined: Oct 27, 2000
Posts: 7
what is the significance of pre & post increment operators in a for loop?
In the following code, both i++ & ++i produce the same result.

class str_1{
public static void main(String args[]){

int i=0;
for(i=0; i<10; i++)
System.out.println("i "+i);
}
}
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
In a for loop, post and pre increment ops behave the same when the result is not assigned to another variable. You can use one or the other, but first check your company Java stylesheet if available for the recommended one.
Most code I've seen used the post increment operator, but it is just a convention...
Regards
Beno�t
Pooja K
Greenhorn

Joined: Oct 27, 2000
Posts: 7
Hi ,
Can you please explain the output of the folowing code???

class str_1{
public static void main(String args[]){

int i=0, j=0;

for(i=0,j=0; i +j <10; ++i, j+=++i)
System.out.println("i "+i + "j " + j + " i+j " + (i+j));

System.out.println("Now doing post \n");
i=0; j=0;

for(i=0,j=0; i +j <10; i++, j+=i--)
System.out.println("i "+i + "j " + j + " i+j " + (i+j));

}
}

Thanks in advance,
Pooja
umang bhartia
Ranch Hand

Joined: Sep 29, 2000
Posts: 60
Hi Pooja,
Well in your eg, if u look then the first for loop will run twice, as the variable i is incremented twice in one loop, os the value would b:
i =0, j=0
i =2, j=2
i =4, j =6 \\ this would not b printed as i+j is = to zero,
while in another for loop, i is first incremented by one and then after assigning the value to j it is again decreased by 1, so the value of j will b increasing by 1 after every loop while i will remain 0.
Hope this is clear.
 
Consider Paul's rocket mass heater.
 
subject: Basic Q