-5

I have a boolean variable isExists. I need to check if isExists is true then i have to perform some action otherwise i need to perform other action. I can write conditional code like following

approach-1

if(isExists){
//perform use previous interest
}else{
//create new interest
}

approach-2

if(true == isExists){
//perform use previous interest
}else{
//create new interest
}

In some books approach 2 is used and in others approach-1 is used.

What is the difference and which one is better between these two way of checking conditional statement for boolean

Sunil Kumar Sahoo
  • 51,611
  • 53
  • 174
  • 242

8 Answers8

3

if(isExists) this is enough and meaning full.

if(true == isExists) here you are checking isExist with boolean true again. No need redundancy.

Ruchira Gayan Ranaweera
  • 33,712
  • 16
  • 72
  • 110
1

In java if your variable is primitive 'boolean' than it is file but if it is a object of Boolean class than please beware about NPE
Below code can cause NPE.
Boolean b = null; // Not a primitive boolean.
if(b) {
System.out.println("It is true");
}else
System.out.println("It is false");

Naveen Ramawat
  • 1,405
  • 1
  • 14
  • 25
0
if(isExists){
//perform use previous interest
}else{
//create new interest
}

is enough. Thats the advantage of having a boolean variable. If you have only a single one to check, just specifying the name is sufficient.

SoulRayder
  • 4,924
  • 5
  • 42
  • 90
0

The result would be the same in both approaches.

It's usually considered better form to use the former, though, for a couple of reasons:

  • isExists is in itself a boolean value - there's no need to compute another one
  • The former appraoch seems more natural when read out aloud (or in your head)
Mureinik
  • 277,661
  • 50
  • 283
  • 320
0
if(isExists)

Because it assign true by default to the variable

BeyondProgrammer
  • 873
  • 2
  • 15
  • 31
0

in other words. its just a condition evaluation. The boolen is a boolen is a boolean. So, you dont compare a boolean (true) with true again to find out weather it is true or false. it doesnt hurt, as in, the compiler doesnt complain but it is no difference.

Hrishikesh
  • 2,013
  • 1
  • 15
  • 24
0

Version 1 is more readable, especially if we change the name to exists

if (exists) {
...
Evgeniy Dorofeev
  • 129,181
  • 28
  • 195
  • 266
0

if(condition)

this checks if the condition is true. basically it does this( i.e. if your boolean is true):

if(condition==true) -> if(true==true) by reading the boolean's value

So for a boolean, it will take it's value and check it against true. Both of your approaches are good, but conventionally the first one is used, since a boolean is named in such a way expressing a fulfilled condition.

diazazar
  • 522
  • 1
  • 4
  • 24