aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Boolean question" Watch "Boolean question" New topic
Author

Boolean question

Steve Janvrin
Greenhorn

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.playsnare();
d.playtophat();
d.snare = false;

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

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

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

Steve.
Paul Sturrock
Bartender

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: http://aspose.com/file-tools
 
subject: Boolean question
 
Similar Threads
Head First Java Beginnner's Question
Method help: how does this work?
Head First Exercise Pg 43
Error: Exeption in thread "main" java.lang.NoSuchMethodError: main
Wrong coding