Why R is not being printed ? why the output is PQST?

120 Views Asked by At

Here's my code. Here PQRST should be the output but R is not printed. I don't understand why ?

class Validator{
    public int[] studentId = { 101, 102, 103 };

    public void validateStudent(int id) {
        try {
            for (int index = 0; index <= studentId.length; index++) {
                if (id == studentId[index])
                    System.out.println("P");
            }
        } finally {
            System.out.println("Q");
        }
    }
}


public class Tester {
    public static void main(String[] args) {
        Validator validator = new Validator();
        try {
            validator.validateStudent(101);
            System.out.print("R");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("S");
        } finally {
            System.out.println("T");
        }
    }
}
2

There are 2 best solutions below

0
Vojtěch Váchal On BEST ANSWER

The problem is that the validateStudent method ends with an ArrayIndexOutOfBoundsException exception, and therefore the System.out.print ("R"); statement does not execute. When the exception happens.

I would probably try to solve this problem a little differently and not with exceptions, which in my opinion are quite complicated in terms of logic and processing. It simply slows down the program that could be more simple.

0
Elliott Frisch On

Your code is currently throwing an ArrayIndexOutOfBoundsException. Because you exceed the length of the array. This

for (int index = 0; index <= studentId.length; index++) {

should be

for (int index = 0; index < studentId.length; index++) {

But then S will not be printed (because it won't throw an Exception).

Today is an excellent day to learn how to use a debugger.