aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Difference between the for loops Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Difference between the for loops" Watch "Difference between the for loops" New topic
Author

Difference between the for loops

ishmayel vemuru
Ranch Hand

Joined: Jun 13, 2007
Posts: 45
Hi to every one..
This is ishmayel.. I am going to write complete my SCJP soon..

I had the following doubt regrading the for loop can any one help me please.

1. for( int i=0; i<3; i++)
{
System.out.print(i+"--");
}
out put is :: 0--1--2
2. for( int i=0; i<3; ++i)
{
System.out.print(i+"--");
}
out put is :: 0--1--2
I am thing that out put is like this.... :: 1--2

my question is why I am getting the same output in both conditions...
If both loops are the same than what is the difference between the
for( int i=0; i<3; i++) and for( int i=0; i<3; ++i)
I hope any one may help me soon.
Thanks in Advance..
Ishmayel.
Nevin kumar
Ranch Hand

Joined: Mar 15, 2008
Posts: 93
hi,
Both are same in this case.Difference between post increment and pre increment is for example if you have x=0,y=0

case 1:
int i=++x; the value of i is 1.
case 2:
int i=x++; the value of i is 0 and after using x,it's value is incremented that is x=1.
ishmayel vemuru
Ranch Hand

Joined: Jun 13, 2007
Posts: 45
Hi Naveen kumar..
thanks for your response..

I know the difference between the pre and the post increment/decrement
but why here in Both conditions I am getting the same output.
1.for( int i=0; i<3; i++)
2. for( int i=0; i<3; ++i)

Please explain write in detail.
Thanks in Advance..
Ishmayel
Neha Agarwal
Greenhorn

Joined: Mar 12, 2008
Posts: 16
Hi,
The reason is the way the for loop exceutes
1)Variable is intialized and then comparison is done
eg in this case
i will be initialized to 0 and then compared to value 3 ,since it is less than 3 it goes inside loop and prints value

2)After that it goes to increment part and and increases it by 1 and checks the condition again goes to print statement .So the result in both cases remain same
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

"Neha Java",
Please check your private messages regarding an important administrative matter.
-Ben


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference between the for loops
 
Similar Threads
Array Initialization with foreach loop
Enhanced For Loop Problem
Integer.toOctalString
Need Explanation
A simple Array Problem