+ 1

Variables and Loops in Java

Variables and Loops in Java ... I do not understand why when creating a variable within a for loop, I can not call it inside an if, I'm making some mistake ??? If so, tell me, I still have not clear ...

20th Jan 2019, 9:31 PM
Michael Meléndez
Michael Meléndez - avatar
2 Answers
+ 13
● U can declare variable outside the for() loop, so that variable will be access outside the loop also & can be used again ● Rough Sample Code : int a=1; for(;a<3;a++){ System.out.println(a);} System.out.print(a); //variable a is accesible here also ● here are different ways to write a for() loop : https://code.sololearn.com/cTvPRdo0974p/?ref=app
21st Jan 2019, 3:08 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
Variables declared within a for loop can (usually only) be accessed from within the loop. That includes all nested loops, if blocks, switch statements etc. The idea this principle is derived from is called 'scope' and does not differ much for most programming languages. If this does not work (although it should) you made a mistake while instanciation or when referencing the variable (you dont 'call' variables, you reference variables and call methods/functions). Please add your code to get further help. Happy coding. Edit: See the attached code for demonstration. https://code.sololearn.com/cjrf4kAvr7D3/?ref=app
20th Jan 2019, 11:57 PM
Felix Pernat
Felix Pernat - avatar