short circuit evaluations

J

JS#

Hi all, does anyone have any code that will prove java uses short circuit
evaluation e.g. (expr1 && expr2), if expr1 is false it will stop evaluating.
Thanks in advance
JS
 
V

VisionSet

JS# said:
Hi all, does anyone have any code that will prove java uses short circuit
evaluation e.g. (expr1 && expr2), if expr1 is false it will stop evaluating.
Thanks in advance

public static void main(String[] args) throws DAOException {

int x = 1, y = 2;
boolean b, c;
b = true;
c = false;

if ((b = (x == 0)) && (c= (y == 2))) ;

System.out.println("b should be false: b= " + b);
System.out.println("c should be false: c= " + c);

b = true;
c = false;

if ((b = (x == 0)) & (c= (y == 2))) ;

System.out.println("b should be false: b= " + b);
System.out.println("c should be true: c= " + c);
}
 
J

Jimi Hullegård

JS# said:
Hi all, does anyone have any code that will prove java uses short circuit
evaluation e.g. (expr1 && expr2), if expr1 is false it will stop
evaluating.
Thanks in advance

public class NullTest
{
public static void main(String args[])
{
String a = "a";
String b = null;
if (a.equals("b") && b.equals("a"))
{
System.out.println("a == b??? and what about
NullPointerException??");
}
System.out.println("a != b :)");
}
}

If java whould evaluate both expressions in the if-statement, then it would
make a call to the equals-method of object b. But since b is null that would
cause an NullPointerException. If you run this program, you will see that no
exception is thrown. If you then change the a string to be "b" instead of
"a", then the first expression evaluates to true, and java evaluates the
second expression, resulting in a NullPointerException.

/Jimi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top