This is especially useful in guarding against nullness.
String x = null;
if ( x != null && x.equals("xyz") {
then do something with x...
}
The above condition is the best example for handle the null exception. If u put first condition is not equal to null then only it will check for other conditions.
String x = null;
if ( x != null & x.equals("xyz") {
then do something with x...
}
In the above example (bitwise & operator) ,it will check the all conditions in the if statements, so it will throw the NullPointerException.
One main difference between & and && is, bitwise & you can use with both integral and boolean but && you can use with only boolean operands.
class OperatorExOne {
public static void main (String[] args) {
String a = null;
if(a != null && a.equals("Java")) {
System.out.println("Inside If Statement");
} else {
System.out.println("Inside else Statement");
}
}
}
Output:- Inside else Statement
In the above code,if we changed the first condition of if statement, then it will throw NullPointerException, See below.
2) What is the output of given code?
class OperatorExTwo {
public static void main (String[] args) {
String a = null;
if(a.equals("a") && a != null ) {
System.out.println ("Inside If Statement");
} else {
System.out.println ("Inside else Statement");
}
}
}
Output:-java.lang.NullPointerException
3) What is the output of given code?
class OperatorExThree {
public static void main (String[] args) {
int a = 2;
int b = 3;
int result = a & b;
System.out.println(result);
}
}
Output:- 2
4) What is the output of given code?
class OperatorExFour {
public static void main (String[] args) {
int a = 2;
int b = 3;
int result = a && b; //Compilation error
System.out.println(result);
}
}
Output:- Compilation error,
The operator && is undefined for the argument
type(s) int, int
Related Posts:--
1) String Interview Questions and Answers
2) Exception Handling Interview questions and answers
3) Interface and Abstract Class Interview Questions and Answers