-3

What is the difference between these two snippets of code? I know that the ++ sign in java increases the value by 1, in this case it is 4, The first one does not print anything but the second one does print the value of 5. Why?

int val = 4;
if (val++ == 5)
    System.out.println(val);

And this one

int val = 4;
if (val++ == 5)
    System.out.println(val);
System.out.println(val);
Savior
  • 3,225
  • 4
  • 24
  • 48
  • You're using the postfix increment operator. The value of val++ is the value *before* incrementing. There's also a prefix increment operator ++val whose value is the value *after* incrementing. By the way, a more specific title would help you gather answers to your question. – Andy Thomas Apr 22 '16 at 17:32
  • Essentially a duplicate of [Difference between prefix and postfix](http://stackoverflow.com/questions/30297641/difference-between-prefix-and-postfix-operators-in-java), as the answer cites the relevant parts of the specification. – KevinO Apr 22 '16 at 17:35

4 Answers4

1

In the first case, val++ will only increment value after the comparison. Therefore, the if will evaluate to false and nothing is printed.

In the second case, the if still evaluates to false, but there is now a second println after the if is finished executing. Therefore, the value of val (5) is printed.

mdewit
  • 2,016
  • 13
  • 31
0

If you do ++val it will increase to five before the comparison. val++ increases it after the comparison. Remember that. So the first code will not print anything because val is is not increased to 5 until after the comparison.

Dave
  • 131
  • 2
  • 10
0

val++ is called post increment. ++val is called preincrement. There is a difference between them in Java and most other languages, like C, C++.

Postincrement first evaluates the expression, and then increments the value of the variable. Preincrement does the other way round.

Also, your if evaluates to false in both cases. If you skip the parenthesis {} after the condition, only the line that immediately follows is included in the if block. Hence the last line in your second part does not really depend on the if.

user5104026
  • 678
  • 1
  • 6
  • 22
-1

try this

int val = 4;

    if (++val == 5)
        System.out.println(val);

++val(first increase, later comparison)

val++(first comparation, later increase)

satellite satellite
  • 893
  • 2
  • 10
  • 27