-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
  • 53,011
  • 55
  • 178
  • 243

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
  • 34,993
  • 17
  • 75
  • 115
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,425
  • 1
  • 15
  • 27
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
  • 5,072
  • 6
  • 47
  • 93
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
  • 297,002
  • 52
  • 306
  • 350
0
if(isExists)

Because it assign true by default to the variable

BeyondProgrammer
  • 893
  • 2
  • 15
  • 32
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,033
  • 1
  • 16
  • 26
0

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

if (exists) {
...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
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
  • 5
  • 24