-5

I want to change String "Hello World" to "World hello". Here's my code:

    class StringTest
    {
        public static void main(String args[])
        {
            String str= "Hello World";
            String wordcount[]=str.split(" ");
            int count= wordcount.length;
            System.out.println(count);
            for(int i=count;i>0;i--)
            {
                System.out.print(wordcount[i]);
            }

        }
    }

Getting error ArrayOutOfBoundException. Please help.

Maroun
  • 94,125
  • 30
  • 188
  • 241

3 Answers3

3

There is no index matched with count.

starting index of array is 0th index. So if your array has length 5 it has index from 0 to 4

Change

  for(int i=count;i>0;i--){ // there is no index in array for count
     // and this for loop not consider 0th index
     System.out.print(wordcount[i]);
  }

to

  for(int i=count-1;i>-1;i--){ //now loop starts from count-1 and consider 0index
            System.out.print(wordcount[i]);
  }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
2

Arrays are zero-based in Java. You should do:

for(int i=count-1;i>0;i--)
                ↑

If you have an array of size N, the indexes are in range [0, N-1]:

"I love to lie down and pretend I'm a carrot"
 ↓↓↓↓↓↓↓↓↓↓                                ↓
 0123456789...                             42
Maroun
  • 94,125
  • 30
  • 188
  • 241
0

you can use like this

  String str= "Hello World";
            String wordcount[]=str.split(" ");
            int count= wordcount.length;
            System.out.println(count);
            for(int i=count-1;i>=0;i--)
            {
                System.out.print(wordcount[i]);
            }
manivannan
  • 622
  • 1
  • 4
  • 17