Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 445
user1762031 Avatar asked Oct 20 '12 19:10

user1762031


People also ask

How do you declare a boolean variable?

To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.

What is a boolean variable in Java?

In Java, the boolean keyword is a primitive data type. It is used to store only two possible values, either true or false. It specifies 1-bit of information and its "size" can't be defined precisely. The boolean keyword is used with variables and methods. Its default value is false.

What are Booleans initialized to Java?

Java boolean keyword is used to declare a variable as a boolean type which represents only one of two possible values i.e. either true or false . In java, by default boolean variables are initialized with false.


1 Answers

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...

like image 94
Tomasz Nurkiewicz Avatar answered Sep 20 '22 14:09

Tomasz Nurkiewicz