Java / 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. |
& | && |
& 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. |
<> 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.
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); } }
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.
&, |, ^, and ~ are bitwise logical operators.
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.
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.
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.