增强for循环
- package com.itlwc;
- public class Test {
- public static void main(String[] args) {
- int[] str = new int[] { 1, 2 };
- for (int s : str) {
- System.out.println(s);
- }
- }
- }
- /*
- 打印结果:
- 1
- 2
- */
自动装箱/自动拆箱
- 根据基本类型和包装类来说的,大大方便了基本类型和包装类的使用
- 自动装箱: 基本类型转换为包装类
- 自动拆箱: 包装类转换为基本类型
- package com.itlwc;
- import java.util.ArrayList;
- import java.util.Collection;
- public class Test {
- public static void main(String[] args) {
- Collection<Integer> c = new ArrayList<Integer>();
- c.add(3);// 自动装箱,将int类型的3转换为Integer类型放入集合中
- c.add(4);
- for (Integer in : c) {
- System.out.println(in);// 自动拆箱
- }
- }
- }
- /*
- 打印结果:
- 3
- 4
- */
可变参数
- 可变参数本质就是一个数组,对于某个声明了可变参数的方法来说,可以传入离散的值,
- 也可以传入数组对象,可变参数必须作为方法参数的最后一个,
- 也就是说一个方法参数中不能有两个可变参数
- package com.itlwc;
- public class Test {
- public static void main(String[] args) {
- int a = sum(1, 2, 3, 4, 5);
- System.out.println(a);
- int b = sum(new int[] { 1, 2, 3, 4 });
- System.out.println(b);
- }
- public static int sum(int... is) {
- int sum = 0;
- for (int i : is) {
- sum += i;
- }
- return sum;
- }
- }
- /*
- 打印结果:
- 15
- 10
- */
静态导入
- package com.itlwc;
- import static java.lang.Math.pow;
- import static java.lang.Math.sqrt;
- public class Test {
- public static void main(String[] args) {
- //未使用静态导入
- double d1 = Math.pow(3, 2) + Math.sqrt(4);
- System.out.println(d1);
- //使用静态导入,看起来简单多了
- double d2 = pow(3, 2) + sqrt(4);
- System.out.println(d2);
- }
- }