When to use type.length-1; and type.length(); in java
Asked Answered
N

11

6

I'm little bit confused when do I really need to use that length-1. I know that is when we don't want to have out of bound error. For instance I wrote this simple array:

    int [] oldArray = {1, 5, 6, 10, 25, 17};

    for(int i = 0; i < oldArray.length; i++){

It does not give me any error. Any examples when -1 is actually useful? Thank you in advance.

Nucleon answered 21/10, 2013 at 3:49 Comment(6)
To get the last element, for example, odlArray[oldArray.length - 1] will return 17...Intemperate
if I'll do -1 then it will give me 25 not 17Nucleon
@user2888585, if you use -1 in loop it will give u 25, but if u use it in array size it will return 17 as suggested by MadProgrammerSinotibetan
No, it won't. Arrays are 0 indexed, meaning that while the array is 6 elements long (ie oldArray.length == 6), you access elements from 0 through to 5, so the last element will oldArray.length - 1 :DIntemperate
You could also do for(int i = 0; i <= oldArray.length - 1; i++){ for example, but the way you have it is much easier...Intemperate
all of you gave me valuable answers. Thank you so much!Nucleon
M
7

You want to use oldArray.length usually in a for loop call, because as in your example,

for(int i = 0; i < oldArray.length; i++) {
    //Executes from i = 0 to i = oldArray.length - 1 (inclusive)
}

Notice how i goes from 0 up until oldArray.length - 1, but stops exacty at oldArray.length (and doesn't execute). Since arrays start at position 0 instead of 1, old.Array.length is a perfect fit for the number that i should stop at. If arrays started at position 1 instead, for loops would look something like this:

for(int i = 1; i <= oldArray.length; i++) {
    //Executes from i = 1 to i = oldArray.length (inclusive)
}

oldArray.length - 1 is usually to access the last element:

int[] oldArray = {1,2,3,4,5};
int lastElement = oldArray.length - 1; // 4
oldArray[lastElement] // returns last element, 5

Although this is usually when you would use length - 1 vs length, there are many other cases where you would also want one over the other, and thus there is no real specific answer. But don't worry, keep coding, you'll get this hang of this soon ;)

Myocarditis answered 21/10, 2013 at 3:59 Comment(0)
T
5
for(int i = 0; i < oldArray.length; i++)

is equivalent to

for(int i = 0; i <= oldArray.length - 1; i++)
Teredo answered 21/10, 2013 at 4:1 Comment(0)
L
3

Loops and array utility methods can use array.length to mean "up to the last element".

The only place I can think of for using array.length - 1 is when accessing the last element, eg to find largest number in an array:

int[] array;
Arrays.sort(array);
int largest = array[array.length - 1];
Levasseur answered 21/10, 2013 at 3:59 Comment(0)
P
1

This completely depends on what you want to do. In an array you have a collection of things. If you were shown this array [1,2,3,4] say, in elementary school and someone asked you how many things are in there you would say four. You would count starting from one, which is completely reasonable. If someone asked you what the third thing in that array was, you'd point to the 3. Awesome! Except, now that you're coding, you know that arrays start at zero. So even though there are still four things in that array, their names have changed. Now 1's name is zero, 2's name is one, 3's name is two, and 4's name is three. So when you're using a loop and you just want the loop to go through all the things and that's it (like if you're searching through an array), you can use .length and it'll just run through. If you want to access the number 4 in the array specifically, though, 4's name is no longer 4 - it's 3! So you use length-1 because when it comes to indexes, we're using the new name given to the physical thing.

Postdate answered 4/9, 2016 at 7:44 Comment(0)
U
0

There is no specific answer for your question. It depends. one point is when you want to index the last element of an array

int lastElement = oldArray[oldArray.length-1];
Unrig answered 21/10, 2013 at 3:49 Comment(0)
L
0
int [] oldArray = {1, 5, 6, 10, 25, 17};

for(int i = 0; i < oldArray.length; i++){

=>

int [] oldArray = {1, 5, 6, 10, 25, 17};

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

So basically, you want to use oldArray.length - 1 when you need to access the last element.

Lovieloving answered 21/10, 2013 at 3:54 Comment(4)
if I'll do -1 then it will give me 25 not 17Nucleon
@Nucleon no, -1 gives you 17 while -2 gives you 25 since the indexing system for array is zero-based :)Lovieloving
when I run it without -1 it still gives me 17.Nucleon
@Nucleon Note that I changed < to <= in the answer.Lovieloving
D
0

Simply put, although your array has 6 elements, the indexing of the array begins at 0. That means that the index of the first element is 0, the second element 1, ... and the 6th element 5. Therefore, if you try to access oldArray[6], you will get an error. In the loop you demonstrate, this is never the case:

for(int i = 0; i < oldArray.length; i++)

oldArray.length returns 6. The highest value of i reached in the loop is 5, since the loop will break when the value of i becomes 6. This is why there are no errors. So to answer your question directly, oldArray[oldArray.length - 1] will return the last element in the array.

Derain answered 21/10, 2013 at 3:57 Comment(0)
T
0

you can write as below as well:

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

oldArray.length-1 is needed when you want that particular element i.e. final element from array.

i.e. oldArray[oldArray.length-1]

Tellurize answered 21/10, 2013 at 3:57 Comment(0)
R
0

It is use when you want to get the last index number of the array. Seens the computer dosent know how long your array is it gets the indication by using -1. Seens 0 is the start then -1 is the end of the array.

I use this when i want to sort numbers just like the example that Bohemian wrote. Take a look at bubble sort algorithem

{
   int[] arr= new int[5]{23,2,3,34,6}; // unsorted data set
   bubblesort(arr,5); // sorting process using bubble sort
   int i;
  for(i=0;i<5;i++)
      Console.Write(arr[i]); //after sorting
  Console.ReadLine();

}

//bubble sort

static void bubblesort(int[] dataset, int n){
   int i,j;
   for(i=0;i<n;i++)
     for(j=n-1;j>i;j--)
        if(dataset[j]<dataset[j-1])
       {
          int temp=dataset[j];
          dataset[j]=dataset[j-1];
          dataset[j-1]=temp;
        }

     }
   }
}
Roadblock answered 9/4, 2015 at 16:14 Comment(0)
F
0
for (int i = 0; i < array.length; i++) {
    // this will loop throw the entire array
 }

if you want to access an element from array, you need to use array.length-1

 lastElement = array.length -1;
Felly answered 15/7, 2019 at 13:33 Comment(0)
E
0

The main rule is to remember is the Array is starts with 0. While .length is returns the actual number of array, so length do not count or start with 0

So, as per your example:

  int [] oldArray = {1, 5, 6, 10, 25, 17};

Here in your example below

 for(int i = 0; i < oldArray.length; i++){}

The i starts with 0 and loop continue till i value as 5 as you are using < only.

If you try to use <= it will fail again, as you try to assess 7th(0-6) element which is not present.

Now take a another example as below, where we try to reverse a string:

    String name="automation";
    
    System.out.println(name.length());
    
    for(int i=name.length()-1;i>=0;i--) {
        System.out.print(name.charAt(i));
    }

Output:

10

noitamotua

Now in above example if you don't use -1 the value 10 will be pass inside the loop, as the length return 10 as per length of string but for array 10th element not present as array starts with 0 so it require till 9th place only as per above example , if you pass 10 it will throw error as 10th position is not present for it, thats why we need to use -1 at least for decrements(i--) order for sure

Edentate answered 2/2, 2020 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.