Reputation: 21
The following is the code that I'm asking about:
int price = 0;
boolean isFree = (price == 0);
if (isFree) {
price = 10;
if (isFree)
System.out.println("one");
else
System.out.println("two");
}
So I just wanna know why the isFree
variable remains true while the price variable changes to 10. In other words why does the price variable switch to 10 without affecting the boolean expression?
Upvotes: 1
Views: 362
Reputation: 11832
Because the isFree variable had its value set once when you defined it. If you want the isFree variable to have another value, you need to set it.
You could change your definition of isFree into a method:
private boolean isFree(int price) {
return price == 0;
}
Then any time you want to know if the price is free, you can call the isFree
method:
int price = 0;
if (isFree(price)) {
price = 10;
if (isFree(price))
System.out.println("one");
else
System.out.println("two");
}
Upvotes: 1
Reputation: 4915
After initialized by boolean isFree = (price == 0);
, the isFree
variable is determined to be true
.
it will not be changed even though the price
is changed, unless you change it explicitly(like calling boolean isFree = (price == 0);
again).
Upvotes: 1
Reputation: 99
By using two isFree statements you are basically cancelling out the condition thus making it true (static) and not checking the new condition which is dynamic.
int price = 0;
boolean isFree = (price == 0);
if (isFree){
price = 10;
System.out.println("one");
}
else{
System.out.println("two");
}
Upvotes: 0
Reputation: 789
It stays the same because you don't check the boolean variable again after comparing it the first time. If you had another
isFree = (price == 0);
after checking and re-assigning price to 10, then it would be false.
Upvotes: 0