这些运算符用于向左或向右移位数字的位,从而分别将数字乘以或除以2。当我们必须将数字乘以或除以二时,可以使用它们。一般格式 -
// Java program to illustrate // shift operators public class operators { public static void main(String[] args) { int a = 0x0005; int b = -10; // left shift operator // 0000 0101<<2 =0001 0100(20) // similar to 5*(2^2) System.out.println("a<<2 = " + (a << 2)); // right shift operator // 0000 0101 >> 2 =0000 0001(1) // similar to 5/(2^2) System.out.println("a>>2 = " + (a >> 2)); // unsigned right shift operator System.out.println("b>>>2 = "+ (b >>> 2)); } }
输出:
a2 = 1 b >>> 2 = 1073741821
运营商的实例是用来进行类型检查。它可用于测试对象是否是类,子类或接口的实例。一般格式 -
// Java program to illustrate // instance of operator class operators { public static void main(String[] args) { Person obj1 = new Person(); Person obj2 = new Boy(); // As obj is of type person, it is not an // instance of Boy or interface System.out.println("obj1 instanceof Person: " + (obj1 instanceof Person)); System.out.println("obj1 instanceof Boy: " + (obj1 instanceof Boy)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); // Since obj2 is of type boy, whose parent class is // person and it implements the interface Myinterface // it is instance of all of these classes System.out.println("obj2 instanceof Person: " + (obj2 instanceof Person)); System.out.println("obj2 instanceof Boy: " + (obj2 instanceof Boy)); System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); } } class Person { } class Boy extends Person implements MyInterface { } interface MyInterface { }
输出:
obj1 instanceof Person:true obj1 instanceof Boy:false obj1 instanceof MyInterface:false obj2 instanceof Person:true obj2 instanceof Boy:true obj2 instanceof MyInterface:true