Bitwise Shift Operator

7 0 0
                                        


import java.util.Scanner;


public class BitwiseShift{

         public static void main(String[] arg){

                   Scanner input = new Scanner(System.in);

                    System.out.println("Enter a number");

                    int aNum = input.nextInt();

                    System.out.println(aNum << 2);

                    System.out.println(aNum >> 5);

                    System.out.println(aNum >>> 5);

         }

}

================================================================================

/* Output: In left shift or right shift, you convert the number to binary or 1's and 0's then, you shift it either to left or right depending on the number of shift

Example:

Enter a number if aNum = -32 aNum << 2 = -128 aNum >> 5 = -1 aNum >>> 5 = 134217727


Note: in unsigned right shift, you put a 1 to the left most part of the 32 bit signed two's complement since it is an integer. 1000 0000 0000 0000 0000 0000 0010 0000 after shifting 0000 0100 0000 0000 0000 0000 0000 0001 (2 exp n) - 1 this is equals to 134217727


if aNum = 32 aNum << 2 = 128 aNum >> 5 = 1 aNum >>> 5 = 1*/

================================================================================

/* Meaning of the word */

1. "import java.util.Scanner;" - this is a class scanner that is imported coming from a package in the built in library. util is a utility class that has a subclass of Scanner. Both class belong to the built in java package.

2. "Scanner input = new Scanner(System.in);" - this is how we declare and initialize at the same time a scanner class. In "system. in", the System is a class and the "in" is the field.

3. "int aNum = input.nextInt();" - we declare "aNum" as the name of our variable with a adata type of integer. It is equaled to "input" which is the declared name of the Scanner and connected to the "input" reference is the method "nextInt()" which scans the integer input and return the scanned integer.


Java codes i learned onlineWhere stories live. Discover now