I read the book Head First Java and when solving a problem the question arose - "Why are the values ​​greater than I thought?" Here is the following code:

public class Main { public static void main(String[] args) { int x = 5; while(x>1) { x--; if(x<3) { System.out.println("small x"); } } } } 

It seems to me that there should be one phrase on the command line:

small x

Because "1" in the loop and "2" in the conditional operator are not inclusive. As a result, two phrases appear. Please explain what I am wrong ?!

  • one
    so x<2 or x<3 ? %) If 3, explain why you think the phrase should appear only once?)) - Alexey Shimansky
  • I apologize for the initial misconception. Actually x <3, I made a mistake when I wrote the code - Alex Sh.

2 answers 2

Decrement x--; is between the condition of the cycle and the condition of the message output, therefore the value before the cycle was 3, and in the cycle after the decrement it was 2, and then before the cycle 2, and in the cycle it was 1, therefore it was displayed twice.

Accordingly, to get output to the console only once, you need x--; placed at the end of the cycle, not at its beginning.

  • Accordingly, to get output to the console only once, you need x--; placed at the end of the cycle, not at its beginning. - Vasily Ukin

Let's look at the cycle

 while(x>1) { x--; if(x<2) { System.out.println("small x"); } } 

Output to the console will be in one case: when x less than 2, that is, when inside the body of the loop, x is 1. This can happen only in one case, when at the very beginning of the loop iteration, x is 2.

After that in the sentence

  x--; 

the value of x will be reduced, and the condition in the if clause will be true.

After exiting this iteration, x will be equal to 1, and in view of the cycle condition

 while(x>1) { ^^^^ 

the cycle will stop its work.

Therefore, only once a message will be displayed to the console.

 small x 

You cannot receive two such messages.

EDIT: If you change the loop condition with

  if(x<2) { 

on

  if(x<3) { 

then two messages will be displayed on the console. The first message will be issued when, at the next iteration of the loop, x will be 3 (in this case, after the execution of the sentence x--; x will become equal to 2 before calculating the condition in the if clause). And the second message will be issued when in the next iteration of the loop, at which the initial value of x will be equal to 2.

A total of two messages will be displayed on the console.