+ 19
Java Doubt ??? // for loop
//see this 👇👇👇 https://code.sololearn.com/cTvPRdo0974p/?ref=app
6 Answers
+ 20
we can also write it as :::
declaration;
for(;test expression;){statement(s); updation;}
//here declaration part comes outside
//👉👉👉try writing declaration part outside like this , does it shows error ...
//👉👉👉it does not show error
//does it means we cannot write for () loop in above form ???????????
//ma puch kya raha hun , aur tum bata kya rahe ho
+ 21
When you declare variable inside for loop, there is one important point to remember: the scope of that variable ends when the for statement does (the scope of the variable is limited to the for loop).
Your output lines :
System.out.println(a) ;
System.out.println(b) ;
are outside loop and because of that it can't found a, b
+ 14
since a and b are local variables of for loop , it cannot be accessed outside the loop
+ 12
Because they are accessible only inside the loop as they are initilized inside the for loop.you have to surround
System.out.print(a) and
System.out.print(b)
with curly braces to access
+ 3
a and b are local variables of for loop.so it's cannot accessed by the outside loop.
+ 1
You are closing the loop right before the print statements are executed so the variables get destroyed after exiting the for loop.
One way is to declare the variables outside the loop and use them in the loop, they wont get destroyed as they are declared outside the loop.
Give it a try!