OneCompiler

[Java] How to get the last element of an array?

I want to read last element of an array into a variable, how can we do that in Java?

1 Answer

4 years ago by

We can use aray[aray.length - 1] to find the last 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 - 1]);
	}
}

Output:

yellow

Try this program online here: https://onecompiler.com/java/3xmt9zk7z

4 years ago by Karthik Divi