Meaningless Drivel is fun!*
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "if conditions" Watch "if conditions" New topic
Author

if conditions

Christoffer Blyerts
Greenhorn

Joined: Jun 03, 2012
Posts: 10
Hi,

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?


Thanks,

Christoffer

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60050
    
  65

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] [Bear's FrontMan] [About Bear] [Books by Bear]
Guilherme Bazilio
Greenhorn

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: http://aspose.com/file-tools
 
subject: if conditions
 
Similar Threads
Runtime behavior after command-line invocation
Increment Operator and Assignment Operator
Overriding .equal method to compare between 2 objects (user defined classes)
how to compare the values in arrays
== vs = Question