1

I'm tying to learn Java. I need to make a method called reverse that gets a string and return a string (but in reverse order). Here is what i tried. Can you fix the code and explain what I'm doing wrong? Please also give me some advice about a good start in Java. Thank you!

public class Test{
    public static String reverse(String a){  
        int j = a.length();
        char[] newWord = new char[j];
        for(int i=0;i<a.length();i++)
        {
            newWord[j] = a.charAt(i);
            j--;
        }
        return new String(newWord);
    }

    public static void main(String a[]){

        String word = "abcdefgh";
        System.out.println(reverse(word));
    }
}
3
  • 4
    initialize j to a.length()-1 Commented Mar 6, 2018 at 8:36
  • 3
    What is happening and what did you want to happen? If you're getting an ArrayIndexOutOfBoundsException, wouldn't that be useful to mention in your question? (Just a hint here: int j = a.length() -1;, as arrays are indexed from zero to their length minus 1) Commented Mar 6, 2018 at 8:39
  • Does this answer your question? Reverse a string in Java, also see ArrayIndexOutOfBoundsException when iterating through all the elements of an array Commented May 3, 2024 at 20:43

9 Answers 9

10

You can use this to reverse the string, you don't need to use your own method

new StringBuilder(word).reverse().toString()

If you want to use your solution you must change int j = a.length() to int j = a.length() -1;

Sign up to request clarification or add additional context in comments.

Comments

3

The fixed code is

public class Test {
    public static String reverse(String a) {
        int j = a.length();
        char[] newWord = new char[j];
        for (int i = 0; i < a.length(); i++) {
            newWord[--j] = a.charAt(i);
        }
        return new String(newWord);
    }

    public static void main(String a[]) {

        String word = "abcdefgh";
        System.out.println(reverse(word));
    }
}

Like others have mentioned, arrays indexes start at 0. So if an array has size 5 for example it has indices 0,1,2,3,4. It does not have an index 5.

For an example of a string with length 5, the code change that I did newWord[--j] = a.charAt(i); will assign to the indices 4,3,2,1,0 in that order.

Regarding getting a good start in Java, I think you could try https://softwareengineering.stackexchange.com/. This site is not meant for that kind of thing.

2 Comments

If I've made a char[] too big and I want to clear the empty slots how can i do it? For example I have a char[10] in the begining and in the end after all the operations i did i only got enough to fill 6 slots and the other 4 are empty. How do i trim them?
Use a list(java.util.List) if you don't know the size. Arrays are used when you know the number of items. If you want a more detailed answer you should ask a new questino
2

This is a common difficulty with new Java developers.

The point you are missing is that the last entry in an array is at position a.length-1. Similarly for Strings

Here's an improved version to demonstrate.

public static String reverse(String a) {
    char[] newWord = new char[a.length()];
    for (int i = 0, j = a.length() - 1; i < a.length(); i++, j--) {
        newWord[j] = a.charAt(i);
    }
    return new String(newWord);
}

Comments

0

You're already on the right track with your method. The one thing I will say to you is that you don't need to use an array of characters and then use something like return new String(newWord);. That's overly complicated for beginner Java in my view.

Instead, you can create an empty String and just keep appending the characters onto it as you loop through all the characters in the String you want to reverse.

So your for loop, because you're reversing the word, should begin at the end of the word being reversed (a in this case) and work backwards to index position 0 (ie. the start of the word being reversed).

Try this and see if this makes sense to you:

public static String reverse(String a) {
    String reversedWord = "";
    for (int index = a.length() - 1; index >= 0; index --) {
        reversedWord += a.charAt(index);
    }
    return reversedWord;  
}

This is, then, starting at the end of a, working backwards one character at a time (hence the use of index --) until we reach a point where index has gone beyond the character at index position 0 (the middle condition of index >= 0).

At each index position, we are simply taking the character from the a String and appending it onto the reversedWord String.

Hope this helps! Feel free to ask any other questions if you are stuck on this.

Comments

0

In your for loop, body must be as that newWord[--j] = a.charAt(i);. It's because if the lenght of array is 8, its indexes are 0-7. So we first decrement j and then use it as array pointer.

Comments

0
  public class Test {
        public static String reverse(String a) {
            int size= a.length();//size of string
            char[] newWord = new char[size];//intialize  
            for (int i = size-1,j=0; i >=0 ; i--,j++) {//loop start from 7 to 0
                newWord[j] = a.charAt(i);// and reverse string goes from 0 to 7
            }
            return new String(newWord);
        }

        public static void main(String a[]) {

            String word = "abcdefgh";
            System.out.println(reverse(word));
        }
    }

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
0
static void reverse {
    String word = "Hello World";
    StringBuilder str = new StringBuilder(word);
    str.reverse();
    System.out.println(str);
}

or you could do

new StringBuilder(word).reverse().toString()

Comments

0
public static void main(String[] args) {

    String input = "hello world";
    String output = new String();

    for (int i = input.length() - 1; i >= 0; i--) {
        output = output + input.charAt(i);
    }

    System.out.println(output);

}

1 Comment

please add an explanation for the answer. It will help op and visitors to understand the problem.
0
package Reverse;
import java.util.*;

public class StringReverse {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a String:  ");
        String original = input.nextLine();

        String rev = "";// Initialize as Empty String
        for(int i = original.length() - 1 ; i>=0 ; i--){
            rev += original.charAt(i);
        }
        System.out.println("Reverse form: "+rev);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.