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

Total Post:61


 1461  View(s)
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. 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.


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.