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?
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”.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With