Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 1 month ago

What line of code lets you get the last character in an array?

I am writing code in java and I'm not sure which one would allow me to get the last character in the array.

so, I have  char[ ] newArray = new char [5];

would I get it by doing newArray[newArray.length-1] or would I simply just get it by doing newArray[5]? 

2 Answers

Relevance
  • roger
    Lv 7
    1 month ago

    Easy in C

     if (strlen(array)) array[strlen(array)-1];

  • 1 month ago

    I'd use the first expression.  That computes the index rather than hard-coding a value that will only work on one array size.  You can make that into a static method, if you like:

        public static lastElement(char[] array) {

            return array[array.length - 1];

        }

    If you were going to use a hard-coded index, use the right one.  The last index in a length 5 array is 4, not 5.  (Array index values start at 0 for the first element.)

        char lastChar = newArray[4];

Still have questions? Get answers by asking now.