暂无 |

移位运算符

这些运算符用于向左或向右移位数字的位,从而分别将数字乘以或除以2。当我们必须将数字乘以或除以二时,可以使用它们。一般格式 -

  • <<,左移运算符:将数字的位向左移位,并在剩余的空位上填充0。将数字乘以2的幂的相似效果。
  • >>,带符号的右移运算符:将数字的位向右移位,并在剩余的空位上填充0。最左边的位取决于初始数字的符号。与用2的幂数除数类似的效果。按位右移运算符的解析: Java中的按位右移运算符
  • >>>,无符号右移运算符:将数字的位向右移位,并在剩余的空位上填充0。最左边的位设置为0。
  • // 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
    

操作实例

运营商的实例是用来进行类型检查。它可用于测试对象是否是类,子类或接口的实例。一般格式 -

  • object instance of class/subclass/interface

 

// 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
java教程
php教程
php+mysql教程
ThinkPHP教程
MySQL
C语言
css
javascript
Django教程

发表评论

    评价:
    验证码: 点击我更换图片
    最新评论