operators – Difference between & and && in Java?

 

let’s suppose that the startDate is null

 

if(element.getStartDate()!=null & element.getStartDate().length()>0){
//Treatment1 is not executed a nullPointerException is fired

}
& ,tests both left and right operand even if the left is false
in this example if we use the &&  » wich controle the right and the left operand » we can get a null startDate but
when it asses to test the second part we got element.null.length so a nullPointerExeption is fired

 

&& , if the left operand is false we don’t test the right one
if(element.getStartDate()!=null & element.getStartDate().length()>0){
//Treatment2 is xecuted

}

 

$$ || are also named short-circuitting operator

See you folks :))


Votre commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l’aide de votre compte WordPress.com. Déconnexion /  Changer )

Image Twitter

Vous commentez à l’aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l’aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s