java不常用语法汇总(jdk1.6)

1.浮点数省略的0

System.out.println(.5f);   //.5和0.5等价。

2.import static引入一个static method后,可以在这个类中直接使用这个method.

import static sort.BasicSort.bubbleSort;

public class Test {
    public static void main(String[] args) {
        int[] number = new int[] { 1, 2, 3 };
        bubbleSort(number);
    }
}

3.volatile关键字,用于保证多线程每次取值都取最新的值。

private volatile int index = 0;

4.transient关键字在序列化时保证某个变量不会被序列化,用于Model类的源码不能修改,又没有实现Serializable或要求不能序列化的情况。  

import java.io.Serializable;

public class Bean implements Serializable {
    private int index;
    private transient Model m;
}

5.Object...作为形参时,只能作为方法的最后一个参数,表示可以传任意数量个此类型的参数,方法内使用时可以当做数组。

public class Test {

    public static void main(String[] args) {
        System.out.println(add(1, 2, 3, 4, 5));
    }

    public static int add(int... numbers) {
        int sum = 0;
        for (int i : numbers) {
            sum += i;
        }
        return sum;
    }
}

6.跳出多层循环的label,下面的代码只会打印5个1(不建议使用,建议通过其他方式避免多层循环)

public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            labelA: for (int j = 0; j < 5; j++) {
                for (int k = 0; k < 5; k++) {
                    if (k == 1) {
                        break labelA;
                    }
                    System.out.println(1);
                }
            }
        }
    }

7.非常方便的三元运算符

public class Bean {
    private static Bean instance;

    private Bean() {

    }

    public static Bean getInstance() {
        return instance == null ? new Bean() : instance;
    }
}
原文地址:https://www.cnblogs.com/xirtam/p/3974819.html