-1

I was trying to copy a word using this manner. I am not sure,I was following right manner handling String.

The code is:

 public static void main(String args[])
   {
      String str="Hello";
      int i=0;
      String copy = "";
      while (str.charAt(i) !='\0')
      {
          copy = copy + str.charAt(i);
          i++;
      }

      System.out.println(copy);
   }

Running this code results in Exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
    at java.lang.String.charAt(Unknown Source)
    at ReverseWord.main(ReverseWord.java:15)

Am I using charAt() and checking null in right way? Or,I have wrong conception about String handling in Java?

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Zahid Hossain
  • 292
  • 1
  • 3
  • 13
  • 6
    You have a wrong conception about String handling. They're not 0 terminated. `String.length()` gives you the size. – Kayaman Jul 10 '15 at 07:53
  • In addition string concattenation in the way you do it used to be rather expensive, don't know if it has been changed in later Java releases. – Samuel Åslund Jul 10 '15 at 07:55
  • Why would you want to copy a string? Try this `String str2 = new String(str);`. And read about string pooling here: http://stackoverflow.com/questions/2486191/what-is-the-java-string-pool-and-how-is-s-different-from-new-strings – Mathias Begert Jul 10 '15 at 08:14

2 Answers2

4

You are using Strings in the wrong way (for Java!) lets clarify some basic points to use String's in Java:

  • String are immutable. This means each time you modify it JVM will create a new object. That is a lot of resources, so, in order of better programming you shouldn't use concatenation in Strings, to make concatenation use StringBuilder.
  • Strings does not end with any special symbol, this could happen in some filetypes but not at Strings objects, so you have to get size with length() and use it to iterate if necessary.
  • Always take a loop at the API of any Java object to know its functionallities:
    StringAPI7
    StringAPI8
  • To loop a String char by char you can do it with for, while and several more ways (splitting, converting...):

For loop example:

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

While example:

while (i < str.length()) {

Said that... Take a look at this code working and using what is explained:

public static void main(String[] args) {
    String str = "Hello";
    int i = 0;
    // string builder is a mutable string! :)
    StringBuilder copy = new StringBuilder();
    // we iterate from i=0 to length of the string (in this case 4)
    while (i < str.length()) {
        // same than copy = copy + str.charAt(i)
        // but not creating each time a new String object
        copy.append(str.charAt(i));
        // goto next char
        i++;
    }

    // print result 
    System.out.println(copy);
}

UPDATE

thanks... but while I am trying this to find a reverse did not get result

If what you want is to reverse the String (your code didn't do that, you must write copy = str.charAt(i) + copy;) is much easier with StringBuilder. Take a look at this example:

public static void main(String[] args) {
    String str = "Hello";
    StringBuilder copy = new StringBuilder(str);
    copy.reverse();
    System.out.println(copy);
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • check my update... your code did't reverse the `String`... but in my update you will find the new code to reverse the `String` – Jordi Castilla Jul 10 '15 at 09:55
1

FIrst way:

Use the below code:

for (int i = 0; i < str.length(); i++) {
    copy = copy+str.charAt(i);
}

Second Way:

Convert String into char[]. then convert it back to String.

char[] ch = str.toCharArray();
String copy = new String(ch);
System.out.println(copy);
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109