Java Operators Practice Sheet Guide
Java Operators Practice Sheet Guide
To reverse the sign of a number using bitwise operators: use '~number + 1'. This converts the number to its two's complement. Example: 'int number = 5; number = ~number + 1;' converts 5 to -5.
In Java, byte has a range of -128 to 127. Arithmetic overflow occurs when operations across this range happen, such as adding 1 to 127 resulting in -128. A demonstration is: 'byte b = 127; b++; System.out.println(b);' outputs '-128'.
To check if a number is odd or even using bitwise operators, you can use the expression '(number & 1)'. If the result is '1', the number is odd; if it's '0', the number is even. This works because the least significant bit of an odd number is 1 and for an even number is 0.
To swap two numbers a and b without a third variable, use the XOR bitwise operator: 'a = a ^ b; b = a ^ b; a = a ^ b;'. This works because XOR-ing the same numbers cancels out the effect, leaving the other operand.
To count set bits, you can repeatedly perform the operation 'number & (number - 1)' which clears the least significant bit set. Count the iterations until number becomes zero. Alternatively, repeatedly right-shift the number and count the number of times the least significant bit is 1.
The logical AND (&&) evaluates boolean expressions and stops evaluating if the first operand is false, making it short-circuiting. For example, in 'true && false', the result is false, and the second operand is evaluated if the first is true. The bitwise AND (&) operates on bits and evaluates both operands fully. For integers, '5 & 3' results in 1 since it compares binary forms: 0101 & 0011 = 0001.
The expression to find the maximum of three numbers a, b, and c using the ternary operator is: 'int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);'. The expression evaluates a>b; if true, it checks a>c. If false, it compares b and c.
The result is '40'. The left shift operator '<<' shifts the bits of the number 10 (1010 in binary) two positions to the left, resulting in 101000, which is the binary representation of the decimal number 40.
The output is '12'. Initially, 'a' is 5. 'a++' evaluates to 5, and then 'a' becomes 6. In '++a', 'a' is incremented first to 7, and then added to 5, resulting in 12.
The output of the expression is '70'. This is due to operator precedence in Java, where multiplication (*) has higher precedence than addition (+). Therefore, 20 is multiplied by 3 first, resulting in 60, and then 10 is added to get 70.