Return to site

☕🎓JAVA CERTIFICATION QUESTION: spot the dirty code

· ocp,java

Your colleague is working on an application that analyzes statistics for vehicles of different makes and models. A business rule requirement is that each car instance in the application must have a unique manufacturing year; creating a second instance of a vehicle with the same year must fail.

The Car class created by the colleague is as follows:

You wonder if the business constraint is properly implemented and decide to test the code using the following code fragment:

Which statement is true? Choose one.

* The test code runs without throwing an exception.

* Line n1 will cause IllegalArgumentException.

* Line n1 will cause IndexOutOfBoundsException.

* Line n3 will cause IllegalArgumentException.

* Line n2 will cause IndexOutOfBoundsException.

#java #certificationquestion #ocp




existingYears list is created as an instance member of a Car object, so every Car object has a List of its own.

So, the years in which other Car objects were created will not be found in each List.

If instead, the existingYears field carried the static modifier, only one instance List would exist in the program.

In that case: "Line n3 will cause IllegalArgumentException." would have been the answer, but as that wasn’t done, that option is incorrect.

You might notice that the current car’s year is added to the list before the check is run.

You might expect that an exception would be thrown for every new car, based on an expected collision with its own year.

That would throw an IllegalArgumentException for any and all attempts to instantiate a Car.

If so, the first exception would presumably prevent further execution, and you would expect an exception at line n1.

However, the loop stops before the last item is checked, which makes "Line n1 will cause IllegalArgumentException." incorrect.

Notice the following test in the loop:

i < existingYears.size()-1

Because the size value is reduced by one, the code would ignore the last item in the list.

About IndexOutOfBoundsException that might be thrown, there are none because we never get into the loop that is the only place that manipulates indexes.

So the only correct answer is "The test code runs without throwing an exception."