Meaningless Drivel is fun!
The moose likes Java in General and the fly likes Boolean question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Boolean question" Watch "Boolean question" New topic

Boolean question

Steve Janvrin

Joined: Feb 10, 2005
Posts: 9
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.snare = false;

if (d.snare == true); {
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
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

Joined: Jun 05, 2003
Posts: 89

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

Joined: Feb 10, 2005
Posts: 9
Thanks - I would have thought that the compiler would have caught that, but I guess not.

Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

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.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
I agree. Here's the link:
subject: Boolean question
jQuery in Action, 3rd edition