The Short-Circuit Logical Operators
Lesson:
Main Points:
- The && operator provides the logical AND operation for boolean
types.
- The || operator provides the logical OR operation for boolean
types.
- For an AND operation, if one operand is false, the result is false,
without regard to the other operand.
- For an OR operation, if one operand is true, the result is true, without
regard to the other operand.
Basic Example:
import java.awt.*;
import java.applet.*;
public class shorty extends Applet{
Dimension d;
public void init(){
setBackground(Color.yellow);
d = getSize();
}
public void paint(Graphics g){
for(int x = 0; x < d.width; x+=25){
for(int y = 0; y < d.height; y+=25){
if(x<25 && y<25){
g.setColor(Color.cyan);
}
else if(x<25 || y < 25){
g.setColor(Color.green);
}
else if(x<50 && y < 50){
g.setColor(Color.cyan);
}
else if(x<50 || y < 50){
g.setColor(Color.red);
}
else if(x<75 && y < 75){
g.setColor(Color.cyan);
}
else if(x<75 || y<75){
g.setColor(Color.pink);
}
else if(x<100 && y < 100){
g.setColor(Color.cyan);
}
else if(x<100 || y<100){
g.setColor(Color.magenta);
}
else if(x<125 || y<125){
g.setColor(Color.blue);
}
else if(x == y){
g.setColor(Color.white);
}
else{
g.setColor(Color.black);
}
g.fillRect(x,y,20,20);
}
}
}
}
Short-Circuit Example:
import java.awt.*;
import java.applet.*;
public class stringy extends Applet{
String str;
public void init(){
setBackground(Color.white);
}
public boolean test1(Graphics g, int x, int y){
g.drawString("HELLO FROM TEST1", x, y);
return true;
}
public boolean test2(Graphics g, int x, int y){
g.drawString("HELLO FROM TEST2", x, y);
return false;
}
public void paint(Graphics g){
g.setColor(Color.blue);
//AND SHORT CIRCUIT EXAMPLE
if(test2(g, 10, 20) && test1(g,10,40)){
g.drawString("PASSED test one AND two", 10, 60);
}
else{
g.drawString("FAILED test one AND two", 10, 60);
}
//OR SHORT CIRCUIT EXAMPLE
if(test1(g, 10, 80) || test2(g, 10, 100)){
g.drawString("PASSED test one OR two", 10, 120);
}
else{
g.drawString("FAILED test one OR two", 10, 120);
}
//WHAT ABOUT test1 && test2
//OR test2 || test1 ???
}
}
You will notice in this code that certain print messages get printed and
certain print messages don't get printed. Follow through the code very
carefully so you can see where these apparent descrepancies occur. In the
AND SHORT CIRCUIT EXAMPLE test1 is never called because since test2 returns
false it is unnecessary to call test1 because once test2 returns false the
rest of the condition will be false since both operands must be true for AND
to return true. Similarly in the OR SHORT CIRCUIT EXAMPLE test1 returns true
and so it is not necessary to call test2 since with OR if one operand
returns true then the whole statement has to be true.
Assignment:
In the stringy applet you see two of four possible situations involving
short-circuiting with OR and AND. Add the other two possible situations and
be ready to explain why the applet behaves as it does after you add the
necessary lines.