Java / Operators
1. What is the difference between the Boolean & operator and the && operator?
| & | && |
| & is the "bit-wise AND" operator. | && is the "conditional logical AND" operator. |
| & always evaluates both arguments. | && evaluates the first argument. if it is true, it then evaluates the second. |
2. What is the difference between the >> and >>> operators?
| >> | >>> |
| ">>" is a signed right shift. | ">>>" is an unsigned right shift. |
| If >> is applied on a negative number, the result will still be negative. | >>> ignores the sign of the number. If >>> is applied on a negative number,the result will be a positive number |
| The >> fills from the left with the sign bit (0 or 1). | The >>> zero-fills from the left. |
3. Explain Diamond Operator in Java.
<> denotes the diamond operator. Purpose of the diamond operator is to simplify instantiation of generic classes.
For example, see the below.
List<Integer> myList = new ArrayList<Integer>(); //with the diamond operator we can write as below easily. List<Integer> myList = new ArrayList<>();
The Diamond Operator reduces some of Java's verbosity surrounding generics by having the compiler infer parameter types for constructors of generic classes.
4. Write a Java program to generate a random number between 0 to 99.
The below program uses the current time in milliseconds and apply modulo operator to pick a random number between 0 to 99.
public class RandomNumberGen {
public static void main(String[] args) {
long start_time = System.currentTimeMillis();
System.out.println(start_time % 100);
}
}
5. What is the difference between ++i and i++ under increment operators?
In ++i, the value of i will get incremented before it is used in the expression.
In i++, the previous value is used in the expression first, and after that i is modified and incremented.
6. What are Bitwise Logical Operators?
&, |, ^, and ~ are bitwise logical operators.
7. What is the difference between the Boolean & operator and the && operator?
For Boolean arguments, & works as the (unconditional) "logical AND" operator "&" always evaluates both arguments.
"&&" is defined for two boolean arguments. It is the "conditional logical AND" operator. "&&" ealuates the first argument. if it is true, it then evaluates the second otherwise it wont.
8. Is ++i faster than i++ in for-loops in Java?
No, it is just same. in C/C++, it is considered ++i is faster as i++ involves coping it to temporarily variable. In Java, it is not the case.
9. Alternative to calculate modulo for power of 2 in Java.
Instead of modulo or reminder operator (%) in Java, we may use & bit wise AND operator if N is a power of 2.
For example, to calculate x % 2, since 2 is power of 1, we may use x & 1. Similarly to calculate 5%4, use 5 & 3.
The formula is x & n-1 given that n is power of 2.
