• Post Reply Bookmark Topic Watch Topic
  • New Topic

Data types in the for loop  RSS feed

 
Arend van der Kolk
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am surprised that the 1st block of code compiles fine while the 2nd block does not compile because of error "Syntax error on token "int", delete this token" on line 8

If you cannot have two data types in the inititialization item of the for loop then why does the compiler accept the 1st block where there is a long and a int in the for loop on line 8

1st block


 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That has nothing to do with for-loops, but with variable declarations. In Java you may declare and initialize variables in one statement, and you may declare multiple variables in one statement, but only if they're of the same type.

In the first code snippet, you're not declaring variables. The second code snippet would be valid if you removed the int keyword, which would result in declaring a new variable x of type long.
 
Arend van der Kolk
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Stephan,

I get it now for declaring variables, thank you. But you can initialize multiple variables of different types in one statement? The below code compiles ok.

 
Paul Clapham
Sheriff
Posts: 22827
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arend van der Kolk wrote:But you can initialize multiple variables of different types in one statement? The below code compiles ok.


Sure, in that particular place in a for-statement you can assign values to more than one variable. But only there. If you try this code for example:



I think you'll find you can't do that.
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi this is an intresting topic

after reading through as you said it's valid to initialise both x and y in the first part of the for loop statement but not in any other situation for example the example you pointed out



how come in the for loop that is valid but not valid above?
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adam Chalkley wrote:. . . how come in the for loop that is valid but not valid above?
Don't use floats. Use doubles if you have to do floating‑point arithmetic.
Look in the Java® Language Specification (=JLS) and go through the grammar and that shou‍ld explain why that assignment isn't permissible. You may need other sections, which will probably be as hard to read as the rest of the JLS.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!