Hello
Ive come up with a stupid question that just needs a why
What would this do?
for (int i=5; i<2;i++)
{
System.out.println("What?");
}
System.out.println("Who?");
Print "Who?" once? I can't see it looping because i will never be < 2 when it starts at 5. That being said, the only print should be "Who?".
Print "Who?" once? I can't see it looping because i will never be < 2 when it starts at 5. That being said, the only print should be "Who?".
The problem is that it is a "if" before it is actually a "for"...
That "for" loop (according to what you have said) is the same as a while loop saying:
_
int i=5
while (i<2)
{
System.out.println("What?");
}
System.out.println("Who?");
I just ran your code and it indeed printed who? once and that was it. I don't really get what you mean by:
The problem is that it is a "if" before it is actually a "for"...
but the while loop seems like it will do the exact same as the for loop.
See the Java Language Spec 14.14 - it makes this very clear...
http://docs.oracle.com/javase/specs/jls/se5.0/html/statements.html#14.14
The basic for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.
What is "some initialization code"? Because that happens before the second step which is making sure the expression is true before entering...
Someone will correct me if I'm wrong but the initialization code would be the code that is bold.
for (int i = 0;i<something.length;i++)
or in your case
for (int i=5;i<2;i++)
That "for" loop (according to what you have said) is the same as a while loop saying:
Close. It's more like this (note that the braces introducing a scope are significant):
{
int i = 5;
while (i < 2)
{
System.out.println("What?");
i++;
}
}
System.out.println("Who?");
Since i
is never less than 2, the loop body is never entered, and the only output is "Who?".
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.