panoskarajohn
panoskarajohn

Reputation: 1988

Java Array !Not! Out Of Bounds

    public class GameEntry {
    private String name;
    private int score;

    public GameEntry(String n, int s){
        name = n;
        score = s;
    }
    public String getName(){
        return name;
    }
    public int getScore(){
        return score;
    }
    public String toString(){
        return "(" + name + ", "+ score + ")";
    }
}

public class Scoreboard {
    private int numEntries = 0;
    public GameEntry[] board;

    public Scoreboard(int capacity){
        board = new GameEntry[capacity];
    }
    **public void add(GameEntry e){**
        //System.out.println(board[numEntries - 1].getScore());
        int newScore = e.getScore();
        //Is the new entry really a high score


//*****This is the line i refer to as******
        if (numEntries < board.length || newScore > board[numEntries - 1].getScore()) {
            if (numEntries<board.length) {
                numEntries++;
            }
            //shift any lower scores rightward to make room for the new entry
            int j = numEntries - 1;
            while(j>0 && board[j-1].getScore()<newScore){
                board[j] = board[j-1]; //shift entry from j-1 to j
                j--; // and decrement j
            }
            board[j] = e; // when done add a new entry
        }
    }
}

I would like to draw your attention inside the Scoreboard class, to its add method.

My question is why this code does not fail.

The first time the add method runs, the numEntries is equal to 0. So inside the if statement the board[numEntries - 1].getScore should get an IndexOutOfBounds.

When i put it before the if i get the proper exception. Does the if catch the exception?

I have printed the value of (numEntries - 1) and i get -1. But yet inside the if ot does not seem to bother it.

The line i refer to is inside the add method the first if.

if (numEntries < board.length || newScore > board[numEntries - 1].getScore())

Upvotes: 1

Views: 156

Answers (2)

Anand Kumar
Anand Kumar

Reputation: 169

You are checking the following expression first:

numEntries < board.length

Then you have an OR (||) followed by the expression you are asking about.

The compiler checks the expression from left to right. So if the above expression is true, it just enters the if and starts executing it's contents without checking other expressions.

Upvotes: 1

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36987

Simple Answer: Short-circuit evaluation of logical or.

When the first part of the condition, i.e. numEntries < board.length evaluates to true, the second part after || is not evaluated at all.

Upvotes: 4

Related Questions