Home > DeveloperSection > Forums > number.length-1 in an array, what does the “-1” stands for
Brad Pitt
Brad Pitt

Total Post:61

Posted on    October-05-2013 3:40 AM

 Java Java 

 1 Reply(s)
 967  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 ));



Garry Winogrand
Garry Winogrand

Total Post:24

Posted on    October-05-2013 4:25 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick