NUMBER.LENGTH-1 IN AN ARRAY, WHAT DOES THE “-1” STANDS FOR

Brad Pitt

Total Post:61

Points:429
Posted by  Brad Pitt
Java 
 1020  View(s)
Ratings:
Rate this:

I am new to Java. I got this from a website and it does bubblesort. I doubt why is there "-1" after the "number.length". I just don't quite get it. Grateful if anyone could help.

import java.util.Arrays;

public class Bubblesort {

  public static void main(String[] args) {

    int[] number = {5,16,4,32,30};

    int j;

    boolean flag = true;   // set flag to true to begin first pass

    int temp;   //holding variable

    while ( flag )

    {

          flag= false;    //set flag to false awaiting a possible swap

          for( j=0;  j <number.length-1;  j++ )

          {

                 if ( number[ j ] > number[j+1] )   // change to > for ascending sort

                 {

                         temp = number[ j ];                //swap elements

                         number[ j ] = number[ j+1 ];

                         number[ j+1 ] = temp;

                        flag = true;              //shows a swap occurred

                }

          }

    }

    System.out.println(Arrays.toString( number ));

  }

}

  1. Garry Winogrand

    Post:24

    Points:168
    Re: number.length-1 in an array, what does the “-1” stands for

    You need to remove 1 from the length of an array to get the last element because arrays are 0-based, but the length is 1-based.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!