Java 数组中最后一个元素的输出方法:1. 直接索引:array[array.length - 1]。2. 使用 length 属性:array[array.length - 1]。3. 使用 length-1 下标:array[array.length - 1]。4. 使用 lastElement() 方法(Java 8+):IntStream.of(array).last().getAsInt()。
如何输出 Java 数组中的最后一个元素?
要输出 Java 数组中的最后一个元素,可以使用以下方法:
- 直接索引:
int[] array = {1, 2, 3, 4, 5};
int lastElement = array[array.length - 1];
System.out.println(lastElement); // 输出:5- 使用
length属性:
int[] array = {1, 2, 3, 4, 5};
int lastElement = array[array.length - 1];
System.out.println(lastElement); // 输出:5- 使用
length下标:
-1
int[] array = {1, 2, 3, 4, 5};
int lastElement = array[array.length - 1];
System.out.println(lastElement); // 输出:5- 使用
lastElement()方法(仅适用于 Java 8 及更高版本):
int[] array = {1, 2, 3, 4, 5};
int lastElement = IntStream.of(array).last().getAsInt();
System.out.println(lastElement); // 输出:5









