Java Programs

Left Shift and Right Shift
==========================

<< Left shift operator shifts bits of variable to left.
>> Right shift operator shifts bits of variable to right.

//Left shift and right shift

class sh {
	public static void main(String ar[])
	{
	  byte p=10, r=50;

	  int q,s;

	  q = p << 2; //left shift value of p by 2 bits.

	  s = r >> 4; //right shift value of r by 4 bits.

	  System.out.println("p = "+p+" p left shifted by 2 bits = " + q);

	  System.out.println("r = "+r+" r right shifted by 4 bits = " + s);
	}
}


to compile : c:\myjavaprog>javac sh.java
to run : c:\myjavaprog>java sh
output:
p = 10 p left shifted by 2 bits = 40
r = 50 r right shifted by 4 bits = 3


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

//unsigned right shift operator >>>

class ursh {
   public static void main(String a[]) {

	int s=5,t;

	t = s >>> 3;

	System.out.println("s="+s+"\nunsigned right shift s by 3 bit= "+ t);
	}
}

to compile : c:\myjavaprog>javac ursh.java
to run : c:\myjavaprog>java ursh
output:
s=5

unsigned right shift s by 3 bit= 0


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

Next