Android for Beginners: Booleans

One interesting thing that I have discovered recently is that in java (and in Android), when we declare a boolean as an instance variable in the class without instantiating it, java automatically instantiates it as false. Let’s take a practical example, one that I have encountered recently.

Inside an app, there a boolean instance variable was declared:

public class example {

    private Boolean test;

…do something …

}

Inside the class, we have an if statement which is driven by the boolean variable that has just been created, in other words, we have the following:

if (test) { …do something …}

But since we never instantiated the test variable, one would assume a nullpointerexception would be returned, since we never instantiated “test”. However, from my research, I found out that booleans are actually primitive types and therefore they cannot be null. Only reference types can be null. 

See the following website for description of the two different types: http://pages.cs.wisc.edu/~bahls/cs302/PrimitiveVsReference.html

  • primitive types are the basic types of data
    • byte, short, int, long, float, double, boolean, char
    • primitive variables store primitive values
  • reference types are any instantiable class as well as arrays
    • String, Scanner, Random, Die, int[], String[], etc.
    • reference variables store addresses

Furthermore, if you do not instantiate booleans, the boolean is automatically instantiated by android to “false”. See the boolean section on the android site and look under the section called constructor: http://developer.android.com/reference/java/lang/Boolean.html

Therefore our if statement will be skipped as we will have if (test) which is the same as if (false).

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s