What can go wrong if you replace && with & in the following code:
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A single ampersand here would lead to a NullPointerException
Last edited by helloworld922; February 11th, 2010 at 11:23 AM.
&& is a shortcut and it means that if the condition on the left is false it wont even bother looking at the condition on the right, if you use a single amp instead it will force it to evaluate both conditions even though it already knows that the whole condition will fail.
And in the above post from Sharad you will see that if you replace the double amps with a single amp it will first check to see if a is not null which will evaluate to false since a is null and then it will check the right side anyways because of the single amp and when you do a.length() it blows up.
// Json
In addition, && only operates on booleans, while & does a full boolean and operation on any primitive data type.
ex:
int a = 0x10; // a = b00010000 int b = 0x08; // b = b00001000 System.out.println(a & b); // prints out 0x18, or b00011000, or 24d
Have a look at Bitwise and Bit Shift Operators (The Java™ Tutorials > Learning the Java Language > Language Basics) for more information on Bitwise operators.
// Json