Page 169 - ComputerScience_Class_11
P. 169
The following program demonstrates the use of the shift operators:
Write a program that takes an integer input from the user and demonstrates the use of shift
Program 5
operators by printing their results.
1 import java.util.Scanner;
2 public class ShiftOperatorDemo
3 {
4 public static void main(String args[])
5 {
6 Scanner sc = new Scanner(System.in);
7 // Accept an integer input from the user
8 System.out.print("Enter an integer: ");
9 int num = sc.nextInt();
10 int leftShift = num << 2;
11 System.out.println("Left Shift (num << 2): " + leftShift);
12 int rightShift = num >> 2;
13 System.out.println("Right Shift (num >> 2): " + rightShift);
14 int unsignedRightShift = num >>> 2;
15 System.out.println("Unsigned Right Shift (num >>> 2): " +
unsignedRightShift);
16 }
17 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
Enter an integer: 4
Left Shift (num << 2): 16
Right Shift (num >> 2): 1
Unsigned Right Shift (num >>> 2): 1
7.4 PRECEDENCE OF OPERATORS
The precedence of operators determines the order in which the operators are going to be executed in an expression.
The following table shows the precedence of operators in Java, the higher an operator appears in the table, the higher
its precedence.
S.No. Operators Precedence
1 Postfix unary cal++, cal--
2 Unary including prefix, logical NOT ++cal, --cal, +cal, -cal, ~, !
3 Multiplication, division and modulus *, /, %
4 Addition and subtraction +, -
5 Shift <<, >>, >>>
6 Relational <, >, <=, >=
7 Equality, non-equality ==, !=
8 Bitwise AND &
Variables and Expressions 167

