Java - Why no out of bounds error for this array

In summary, the code creates an array of students and initializes it to be "length" + 1. Then, in line 27, the loop iterates over the students in the array and assigns the value of the student at index "i" to the variable "studentsRevised[i]". This loop is only executed once, when i equals -1.
  • #1
JonnyG
234
45
Homework Statement
Create method to add students to course array.
Relevant Equations
no equations
I am writing a class called "Course" in Java so that one can input students names, etc. Here is my relevant code for the Course class:

Java:
public class Course {

    private String courseName;

    private String[] students = new String[0];

    private int numberOfStudents = 0;
    public Course(String courseName) {

        this.courseName = courseName;

    }
    public void addStudent(String student) {

        String[] studentsRevised = new String[students.length + 1];

  

        for (int i = 0; i <= students.length - 1; i++)

            studentsRevised[i] = students[i];

    

        studentsRevised[studentsRevised.length - 1] = student;

        numberOfStudents++;

        students = studentsRevised;

    }
As a little test, I wrote in the main method:

Java:
    Course course = new Course("math");

        course.addStudent("jonathan");

    

        for (String student : course.getStudents())

            System.out.println(student);

The output was "jonathan", but I was expecting an error! Let me explain:

The array "students" is initialized to be of length 0. In the Course class method addStudent, look at the line
Java:
 studentsRevised[i] = students[i].
When i is initially equal to 0 and the line
Java:
 studentsRevised[i] = students[i].
is executed, there should be an out of bounds error because students[0] doesn't exist. Why do I not get an error?
 
Last edited:
Physics news on Phys.org
  • #2
I assume you did not write the code yourself and now want to understand why it works.

The single code line you quote (line 27 in your initial snippet, which by the way has omissions and does not match your later quote) is inside a loop. Try analyze how this loop is executed, i.e. what value variable i can take. Pay special attention to the limit condition.
 
  • Like
Likes JonnyG
  • #3
Filip Larsen said:
I assume you did not write the code yourself and now want to understand why it works.

The single code line you quote (line 27 in your initial snippet, which by the way has omissions and does not match your later quote) is inside a loop. Try analyze how this loop is executed, i.e. what value variable i can take. Pay special attention to the limit condition.

I wrote it myself, but became confused afterward upon closer inspection of the code. But your hint was very helpful. I now see that the for loop in line 25 will never actually execute because I initially set i = 0, but the loop is only ran if i <= -1 (since students.length - 1 = -1).

Thanks!
 

FAQ: Java - Why no out of bounds error for this array

1. Why doesn't Java throw an out of bounds error for this array?

Java does not throw an out of bounds error for this array because it uses a different approach to handling arrays. Unlike other programming languages, Java arrays are objects and have built-in methods to handle exceptions, such as ArrayIndexOutOfBoundsException. This means that Java checks for out of bounds errors during runtime rather than compile time.

2. Can you explain how Java handles arrays differently compared to other programming languages?

In Java, arrays are objects and have built-in methods to handle exceptions. This means that Java checks for out of bounds errors during runtime rather than compile time. Other programming languages, such as C++, handle arrays as pointers and do not have built-in methods to handle exceptions, resulting in out of bounds errors during compile time.

3. How does Java's approach to handling arrays benefit developers?

Java's approach to handling arrays allows for more flexibility and ease of use for developers. By checking for out of bounds errors during runtime, developers do not have to worry about these errors during the development process. Additionally, Java's built-in methods for handling exceptions make it easier to handle errors and prevent program crashes.

4. Are there any downsides to Java's approach to handling arrays?

One downside to Java's approach to handling arrays is that it may be less efficient compared to other programming languages. The runtime checking for out of bounds errors can slow down the program's execution. Additionally, the use of built-in methods for handling exceptions may add extra lines of code and complexity to the program.

5. How can developers prevent out of bounds errors when working with arrays in Java?

Developers can prevent out of bounds errors by properly using Java's built-in methods for handling exceptions. For example, the try-catch block can be used to catch ArrayIndexOutOfBoundsException and handle it appropriately. Additionally, developers can also use the length property of arrays to ensure they do not access elements outside of the array's bounds.

Similar threads

Replies
5
Views
2K
Replies
12
Views
2K
Replies
1
Views
1K
Replies
1
Views
1K
Replies
1
Views
2K
Replies
7
Views
2K
Replies
1
Views
2K
Replies
7
Views
2K
Replies
1
Views
1K
Back
Top