-1

I was just figuring out how instance variables are working, but it lead me to something strange.

public 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");        
    }
}

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

        DrumKit d = new DrumKit();
        d.playSnare();
        d.snare = false;
        d.playTopHat();

        if (d.snare == true);{
            d.playSnare();  
        }
    }
}

How is it possible that it outputs: "bang bang ba-bang ding ding da-ding bang bang ba-bang"

And not: "bang bang ba-bang ding ding da-ding"

Because what I thought was that the snare only would play once because I'm declaring it after d.playSnare(); to d.snare = false;

William Morrison
  • 10,953
  • 2
  • 31
  • 48

2 Answers2

6

Remove the semicolon in this line, which is acting as the body for your if block.

if (d.snare == true);{

Change it to

if (d.snare == true){

Also, d.snare is already a boolean, so you can simplify the conditional expression to:

if (d.snare){
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

Here's the bang

if (d.snare == true);

Remove ;