初学者Java笔记1

强制类型转换:

public class Main {
    public static void main(String[] args) {
        double x = 9.54;
        // 对浮点类型数进行舍入运算,得到最近的整数,调用方法返回long类型
        int n = (int)Math.round(x); 
        System.out.println("n = " + n);
    }
}

结果:

n = 10

自增与自减(与C没啥区别)

public class Main {
    public static void main(String[] args) {
        int num_1 = 7;
        int num_2 = 7;
        int a = 2 * num_1++;
        int b = 2 * ++num_2;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

结果:

a = 14
b = 16

位运算符

如果使用二进制显示数值会更好的体现

public class Main {
    public static void main(String[] args) {
        int num1 = 0b101;
        int num2 = 0b1010 << 0b11;
        int num3 = 0b1010 >> 0b11;
        System.out.println("num2 = " + num2);
        System.out.println("num1 = " + num1);
        System.out.println("num3 = " + num3);
    }

num2 = 80
num1 = 5
num3 = 1

public class Main {
    public static void main(String[] args) {
        int num1 = 15;
        int num2 = 12;
        int num3 = 0;
        int fourBit1 = (num2 | 0b1000) / 0b1000;
        System.out.println("fourBit1 = " + fourBit1);
        int fourBit2 = (num1 & 0b1000) / 0b1000;
        System.out.println("fourBit2 = " + fourBit2);
        int fourBit3 = (num1 ^ num3);
        System.out.println("fourBit3 = " + fourBit3);
        // 在相同数值的情况下数值为0
        int fourBit4 = (num2 ^ 0b1100);
        System.out.println("fourBit4 = " + fourBit4);
    }
}

fourBit1 = 1
fourBit2 = 1
fourBit3 = 15
fourBit4 = 0

你可能感兴趣的:(初学者Java笔记1)