Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Boolean question

 
Steve Janvrin
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I run this code the value of the boolean snare is correctly reset from true to false, but the if test ignores this and executes the code inside the if test.

This is the code as shown on page 44 of Head First Java, so it should work.

Please assist.

Steve Janvrin.

class DrumKit {
boolean tophat = true;
boolean snare = true;

void playtophat() {
System.out.println("ding ding da-ding");
}

void playsnare() {
System.out.println("bang bang ba-bang");
}
}

class DrumKitTestDrive {
public static void main(String[] args) {

DrumKit d = new DrumKit();

d.playsnare();
d.playtophat();
d.snare = false;

if (d.snare == true); {
d.playsnare();
}
}
}
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is the semicolon you place after the parentheses of the if. That essentially says that's the end of the if. The braces around the code don't mean anything unless you remove the semicolon.
 
Barry Higgins
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Note the ; after the if statement this turns the statement into an inline if and therefore the d.playsnare() will be executed whatever happens.
The code should look like this

 
Steve Janvrin
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks - I would have thought that the compiler would have caught that, but I guess not.

Steve.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It didn't catch it because strictly its not a compilation error. Writing this:

Is synonomous with writing:

In English what your code is saying is "If a equals b, do nothing". Curly brackets define limits of blocks of code in Java. What defines what that block represents is the keyword used when the block is opened (try, catch, do, for, if etc.) If you don't define one, then the only effect they have is on the scope of valiables. For example:

is pretty much the same as:

However, brackets do make this possible:

because the scope of a is limited to what's in the brackets.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic