It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes if conditions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "if conditions" Watch "if conditions" New topic

if conditions

Christoffer Blyerts

Joined: Jun 03, 2012
Posts: 10

i get a bit confused sometimes of when a variable changes value or not in a if statement, for example:

x will be equal to 2 after this if statement.

In this case x will be equal to 3.

What are the rules for when the variable value gets changed or not within a if statement?



Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63873

This has nothing at all to do with if statements, but with the operators you are using. ++ modifies its operand, + does not.

[Asking smart questions] [About Bear] [Books by Bear]
Guilherme Bazilio

Joined: Mar 02, 2009
Posts: 23
The ++ sign is an increment operator (assignment). Used to modify (increment in one) the variable.

This snippet willl only modify the value of x variable after it's current value has been used. So in that if statement it will be evaluated to 2.

On the other hand, this one will modify (increment) the x variable before using it. Then it comes to be 3 in the if statement.

++ modifies the variable!

The + sign is just an arithmetic operator used to sum values and return the result. So x + 2 will be returned to any variable that wants to receive it.

After that code, y will be 2. In the if statement, the result of the sum is not assigned to any variable. The variable x keeps its value since we are not assigning any value to it.
I agree. Here's the link:
subject: if conditions
It's not a secret anymore!