[Java] How to get last but one element from an array?
I want to read last but one element of an array into a variable, how can we do that in Java?
1 Answer
4 years ago by Eleven
We can use aray[aray.length - 2] to find the 2rd item from the last. Following is the complete program
public class JavaArrays {
public static void main(String[] args) {
String[] aray = { "blue", "red", "green", "yellow" };
System.out.println(aray[aray.length - 2]);
}
}
Output:
green
Try this program online here: https://onecompiler.com/java/3xmt9y57h
4 years ago by Karthik Divi