Noob question about a statement in a Java program

Posted by happysoul on Stack Overflow See other posts from Stack Overflow or by happysoul
Published on 2010-05-07T09:08:10Z Indexed on 2010/05/07 9:18 UTC
Read the original article Hit count: 349

Filed under:
|

I am beginner to java and was trying out this code puzzle from the book head first java which I solved as follows and got the output correct :D

class DrumKit
    {
        boolean topHat=true;
        boolean snare=true;
        void playSnare()
            {
                System.out.println("bang bang ba-bang");
            }
        void playTopHat()
            {
                System.out.println("ding ding da-ding");
             }


    }

public class DrumKitTestDriver
    {

        public static void main(String[] args)

            {
                DrumKit d =new DrumKit();

                if(d.snare==true)

                    {
                        d.playSnare();
                    }

                   d.playTopHat();

            }

    }

Output is ::

bang bang ba-bang ding ding da-ding

Now the problem is that in that code puzzle one code snippet is left that I did not include..it's as follows

d.snare=false;

Even though I did not write it , I got the output like the book. I am wondering why is there need for us to set it's value as false even when we know the code is gonna run without it too !??

I am wondering what the coder had in mind ..I mean what could be the possible future use and motive behind doing this ?

I am sorry if it's a dumb question. I just wanna know why or why not to include that particular statement ? It's not like there's a loop or something that we need to come out of. Why is that statement there ?

© Stack Overflow or respective owner

Related posts about java

Related posts about beginner