Java: Variables: boolean

In this tutorial I will explain the boolean. To do that I will use this file.


package net.tutorial.src;

public class Tutorial 
{
public static void main(String[] args)
{
System.out.println(“Hello World!”);
}
}


Like all other variables a boolean has to be created somewhere inside of a class.
A boolean can have 2 states. true and false. It can’t be anything else than that.
The reason why people want to use it is because of if statements and other checks you might want to have before a part of your code is ran. For example if someone is on a menu there shouldn’t be things happening in the game. That’s where you can use a boolean.
If you want to use a boolean in java you need to code it like this.


boolean isatutorial = true;


The first part in this line is the type of variable. In this case a boolean.
The second part in this line of code is the name of the variable. In this case isatutorial.
The last part of this line of code is whether or not is true. If it isn’t true it will be false.
If you want to print this out in the console you have to use a line of code like this.


System.out.println(isatutorial);


Because this bit of the code is in the main method and the main method is static you have to add the word static in front of boolean. Why that is and how you should use that is something for a later tutorial though.


package net.tutorial.src;

public class Tutorial 
{
static boolean isatutorial = true;

public static void main(String[] args)
{
System.out.println(isatutorial);
}
}


 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">