This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "for loop" Watch "for loop" New topic

for loop

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Cann't we declare & initialize two variables in a for loop.
for(int i=3,int j=5;i+j<20;i++,j++)
//do something
this code is giving me error while compiling. Can somebody explains this???
Thanx in advanced.

Joined: Aug 26, 2000
Posts: 25
You can initialize multiple variables in the init part of a for loop, but the corrct syntax is like this
for( int i=0, j=0; i<10; i++, j++) {}
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
It means that we have to declare the varibale j before the starting of for loop otherwise it will give a complie error.
Praveen Zala
Ranch Hand

Joined: Jul 02, 2000
Posts: 118
Hi there
the code
for(int i=3,int j=5;i+j<20;i++,j++)
//do something
will not compile alright !!!
for(int i=3,j=5;i+j<20;i++,j++)
//do something
will compile !!
But wonder why
for(int i=3,char j=5;i<20;i++)
//do something
results in a compilation error ! ?
Praveen Zala
Vijay T

Joined: Sep 02, 2000
Posts: 5
You need not declare 'j' before the beginning of for loop. The syntax

int i=0, j=0

will take care the declaration part for both i and j.
I agree. Here's the link:
subject: for loop
Similar Threads
continue statement
break lable problem
Expression in for loop
Help with Character count from a file.
Multiplication table from a file