Tuesday, February 8, 2011

Tips to use boolean variables in Java

Tips to use boolean variables in Java

In Java a boolean variable can be initialized to true or false only and not to integers like in C/C++. Moreover the primitive boolean variables are very widely used in java application development, j2ee development and also while developing java web services. The basic rules to use the boolean variables are:

1) When using a boolean variable in the if condition, there is no need of == operator. The if condition will evaluate to true or false based on the boolean variable’s value and there is no need of comparison operator. The if conditions are very widely used in java application development.

Example Code:

1
2
3
4
5
6
7
8
9
10
11
package example;
public class Test {
public static void main (String[] args) {
boolean var1 = true;
if(var) {
System.out.println(“The condition is true”);
} else {
System.out.println(“The condition is false”);
}
}
}

Here we can see that if condition is getting evaluated successfully as expected. Even though compiler doesn’t complain about using == operator, but there is virtually no need for comparison operator even if using that code in j2ee development.


This can be treated as a best practice or coding guidelines. Beginners are bound to use == operator for if conditions with boolean variables.


2) The DeMorgan's Theorm(NOT (P OR Q) = (NOT P) AND (NOT Q)
NOT (P AND Q) = (NOT P) OR (NOT Q) ) should be used when there are Java short circuit logical operators involved. The theorm can be demonstrated as:


Here is an example code to showcase the principle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package example.java;
public class Test{
public static void main (String args[]) {
String a1="Test",a2="Test";
if(!"Test1".equals(a1) && !"Test2".equals(a2)) {
System.out.println("This is test1");
}
if(!("Test1".equals(a1) || "Test2".equals(a2))) {
System.out.println("This is test2");
}
}
}


We can see that using the second if condition in the code above, makes it easier to understand the boolean expression. This is also commonly missed out by most of the Java developers and J2EE developers.

No comments:

Post a Comment