• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Jxam Question?

 
JM Beauvais
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Jxam asks if the following is valid:
int q;
for (int p = 0, q = 0; p < 5; p++){
System.out.println("Val = " + p + q);
}
The provided answer is: "Answer 4 is incorrect, because you can't mix the initialisation of a local loop variable declaration in the 'for' loop, with the initialisation of another loop variable."
I know that it is illegal to mix declarations/initializations in the first part of the for loop, BUT-- it seems to me that int p=0, q=0 is a valid declaration/initialization, therefore the q in the for statement is a seperate/different more local q? is that true?
jb.
 
nivas rao
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No it's not valid. gives compile error q already declared.
int p=0,q=0; implies declaration and intialisation of two variables p,q.
 
mrudul joshi
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I think is, q is already defined and so it cannot act as local variable for the 'for'loop at the same time when it is member variable for the class.
If we try to run the above program, we get the same compile time error that variable g is already defined.
About second part of your question, I think we cannot declare the same variable as member variable and local variable at the same time.
But we can have n number of declarations in teh first part of the 'for' loop separating them from the conditional expression using ';'.
I hope this helps!
Bye.
 
mrudul joshi
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I think is, q is already defined and so it cannot act as local variable for the 'for'loop at the same time when it is member variable for the class.
If we try to run the above program, we get the same compile time error that variable q is already defined.
About second part of your question, I think we cannot declare the same variable as member variable and local variable at the same time.
But we can have n number of declarations in teh first part of the 'for' loop separating them from the conditional expression using ';'.
I hope this helps!
Bye.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic