[java] What is the correct way to declare a boolean variable in Java?

I have just started learning Java. In the online course I am following, I am asked to try the following code:

String email1 = "[email protected]";
String email2 = "[email protected]";
Boolean isMatch = false;

isMatch = email1.equals (email2);

if (isMatch == true){
    System.out.println("Emails match");
}
else{
    System.out.println("Emails don't match");
}

I don't understand why I'm asked to declare isMatch as false when on the next line i am comparing the email addresses and assigning the value to isMatch.
I've tried the following code which seems to work just the same:

String email1 = "[email protected]";
String email2 = "[email protected]";
Boolean isMatch;

isMatch = email1.equals (email2);

if (isMatch == true){
    System.out.println("Emails match");
}
else{
    System.out.println("Emails don't match");
}

On the course it doesn't explain why I'm declaring isMatch as false first. Is there a reason why I must declare isMatch as false before comparing the email addresses?

This question is related to java variables boolean

The answer is


Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
    
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);
    

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...


First of all, you should use none of them. You are using wrapper type, which should rarely be used in case you have a primitive type. So, you should use boolean rather.

Further, we initialize the boolean variable to false to hold an initial default value which is false. In case you have declared it as instance variable, it will automatically be initialized to false.

But, its completely upto you, whether you assign a default value or not. I rather prefer to initialize them at the time of declaration.

But if you are immediately assigning to your variable, then you can directly assign a value to it, without having to define a default value.

So, in your case I would use it like this: -

boolean isMatch = email1.equals (email2);

In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.

This is helpful when your equals method call throws some exception e.g. NullPointerException;

     boolean isMatch = false;

     try{
         isMatch = email1.equals (email2);
      }catch(NullPointerException npe){
         .....
      }
      System.out.print("Match=="+isMatch);
      if(isMatch){
        ......
      }

As stated by Levon, this is not mandatory as stated in the docs: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

This is probably either an habit from other languages that don't guarantee primitive data types default values.


There is no reason to do that. In fact, I would choose to combine declaration and initialization as in

final Boolean isMatch = email1.equals (email2);

using the final keyword so you can't change it (accidentally) afterwards anymore either.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas