I think it will print "5 2" because 1 is not greater than 1, but the answer is E, which is "5 2 1". Could u explain to me?
You are correct in thinking that the loop body will not be entered when tailFeathers==1, but you misunderstand what will be printed.
Here's the loop:
while (tailFeathers > 1) {
system.out.print(--tailFeathers + " ");
}
Let's suppose that the loop body was entered because tailFeathers==2 which is > 1. The system.out.print(--tailFeathers + " ") statement will do several things in a well defined order:
- It will decrement the value of
tailFeathers (i.e., it will set tailFeathers=1),
- It will call library functions to create a new
String, "1", to express the new, decimal value of tailFeathers,
- It will concatenate the string
"1" with the string " " to create a new string, "1 ", and then finally,
- It will call
system.out.print("1 ").
The key concept here is the meaning of --tailFeathers. The value of that expression is the value of tailFeathers after the variable has been decremented.
If you changed it to tailFeathers--, you'd get a different result. In that case, the value of the expression is the value that tailFeathers had before it was decremented (i.e., 2 in my example, above.)
The way to remember this is to read it from left to right:
--t means first, decrement t, then use the new value of t, and
t-- means first, use the original value of t, and then some time later, decrement t.