1.循環
/** 1.4 */
for(int i = 0; i < array.length; i++){
type variable = array[i];
body
}
/** 5.0 */
for(type variable : array){
body
}
/** 1.4 */
for(int i = 0; i < arrayList.size(); i++){
type variable = (type) arrayList.get(i);
body
}
/** 5.0 */
for(type variable : arrayList){
body
}
2 泛型
/** 1.4 */
ArrayList arrayList = new ArrayList();
Type type = (Type) arrayList.get(i)
/** 1.5 */
ArrayList<Type> arrayList = new ArrayList<Type>()
Type type = arrayList.get(i);
3 自動裝箱拆箱:在JDK5.0以前,在原始類型與相應的包裝類之間的轉化是不能自動完成的。要完成這種轉化,需要手動調用包裝類的構造函數:
/** 1.4 */
Integer wrapper = new Integer(n);
int n = wrapper.intValue();
/** 5.0 */
Integer wrapper = new Integer(n);
int n = wrapper;
4 可變參數列表
/** 1.4 */
method(Object params)
/** 5.0 */
method(Object... params)
5 可變的返回類型:在JDK5.0以前,當覆蓋父類方法時,返回類型是不能改變的。現在有新的規則用於覆蓋方法。如下,一個典型的例子就是clone()方法:
/** 1.4 */
public Object clone() { ... }
Employee cloned = (Employee) e.clone();
/** 5.0 */
public Employee clone() { ... }
Employee cloned = e.clone();
6 靜態導入:對於JDK 5.0以前的版本是不支持的
/** 1.4 */
System.out.println(Math.sqrt(Math.PI));
/** 5.0 */
import static java.lang.Math;
import static java.lang.System;
...
out.println(sqrt(PI));
7 控制檯輸入
/** 1.4 */
String input = JOptionPane.showInputDialog(prompt);
int n = Integer.parseInt(input);
double x = Double.parseDouble(input);
s = input;
/** 5.0 */
Scanner in = new Scanner(System.in);System.out.print(prompt);
int n = in.nextInt();
double x = in.nextDouble();
String s = in.nextLine();
8 格式化輸出:JDK5.0以前的版本沒有print方法,只能使用NumberFormat.getNumberInstance來代替。
/** 1.4 */
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String formatted = formatter.format(x);
for (int i = formatted.length(); i < 8; i++){
System.out.print(" "); System.out.print(formatted);
}
/** 5.0 */
System.out.printf("%8.2f", x);
9 內容面板代理:在JDK5.0先前的版本中,JFrame,JDialog,JApplet等類沒有代理add和setLayout方法。
/** 1.4 */
getContentPane().add(component)
getContentPane().setLayout(manager)
/** 5.0 */
add(component)
setLayout(manager)
10 StringBuilder類:JDK 5.0引入了StringBuilder類,這個類的方法不具有同步,這使得該類比StringBuffer類更高效。