以下对两个右移操作符>>和>>>进行测试:
public class Opetator { public static void main(String[] args) { byte b = -1; short s = -1; int i = -1; long l = -1; System.out.println("byte b = " + b); System.out.println("(b >> 1) = " + (b >> 1)); System.out.println("(b >>> 1) = " + (b >>> 1)); System.out.println(String.format("hexof (b >> 1) = %x", (b >> 1))); System.out.println(String.format("hexof (b >>> 1) = %x", (b >>> 1))); System.out.println("short s = " + s); System.out.println("(s >> 1) = " + (s >> 1)); System.out.println("(s >>> 1) = " + (s >>> 1)); System.out.println(String.format("hexof (s >> 1) = %x", (s >> 1))); System.out.println(String.format("hexof (s >>> 1) = %x", (s >>> 1))); System.out.println("int i = " + i); System.out.println("(i >> 1) = " + (i >> 1)); System.out.println("(i >>> 1) = " + (i >>> 1)); System.out.println(String.format("hexof (i >> 1) = %x", (i >> 1))); System.out.println(String.format("hexof (i >>> 1) = %x", (i >>> 1))); System.out.println("long l = " + l); System.out.println("(l >> 1) = " + (l >> 1)); System.out.println("(l >>> 1) = " + (l >>> 1)); System.out.println(String.format("hexof (l >> 1) = %x", (l >> 1))); System.out.println(String.format("hexof (l >>> 1) = %x", (l >>> 1))); } }
输出:
byte b = -1 (b >> 1) = -1 (b >>> 1) = hexof (b >> 1) = ffffffff hexof (b >>> 1) = 7fffffff short s = -1 (s >> 1) = -1 (s >>> 1) = hexof (s >> 1) = ffffffff hexof (s >>> 1) = 7fffffff int i = -1 (i >> 1) = -1 (i >>> 1) = hexof (i >> 1) = ffffffff hexof (i >>> 1) = 7fffffff long l = -1 (l >> 1) = -1 (l >>> 1) = hexof (l >> 1) = ffffffffffffffff hexof (l >>> 1) = 7fffffffffffffff
可得出以下结论:
1. byte、short、int 类型的右移操作都是先将左操作数转换为int类型,然后执行右移操作,结果也是int类型。
2. long 类型的右移操作并没有对左操作数进行类型转换,结果也是long类型。
3. >>操作对左边空位补符号位,>>>对左边空位补0。
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/java-jiao-cheng/15060.html