This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Basic Q" Watch "Basic Q" New topic

Basic Q

Pooja K

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);
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...
Pooja K

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,
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.
wood burning stoves
subject: Basic Q
Similar Threads
display error
need help?
column heading dates ...
how to combine between two arraylist if has same value
Declare an Array?