Browser Games | Cybiko | Amiga | Applications | Windows Games | Java Area | Test Area | Guides | Site Map

Out Of Bounds - Java


This is part of a series testing each of the languages I use to see how good they are at catching simple array out of bounds errors.

These tests check for the following:

The Code

The following was tested using the OpenJDK 12.0.2 :

class oob_java{
	public static void main(String[] arguments)
		final int pa=4;
		int pb=5;
		int[] myarray={0,1,2};

		// #1. Simple so should be an easy catch - CT: FAILED
		// #2. This is a constant so should also be an easy catch - CT: FAILED
		// #3. Variable index but does start outside - CT: FAILED
		// #4. Looping through array - CT: FAILED
		for(int i=0;i<6;i++)

Test 1 - Default Settings

The compiler (javac) surprisingly did not pick up any problems at compile time.

Running the above, the program does give Array Index Out Of Bounds exceptions.


To fix error #4, we could use a range based loop instead:

	// #4. Looping through array - Better version
	for(var value:myarray)


This does not seem like a very good result given that Java is usually in the top 3 of languages used. Surely it would be better to bring attention to any obvious errors while the program is being made?