var i = 0;
while(i < 100){
return "The number is " + i;
i++;
}
What is wrong with my return statement? Why can I return a string plus a variable?
Having a return statement directly inside a while loop will result in only one iteration being executed. (It makes your loop useless). However, if you replace this line with something like console.
It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed. Otherwise, a compile-time error will occur because the method cannot return nothing (unless it has the Java reserved word "void" in the method header).
The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).
The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
return
means end of function and return some value. Any statements after return statement will not be executed and the execution of a function will terminate at return statement. So, return
in your case will make the loop to execute only one and terminate it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With