z atef
z atef

Reputation: 7679

String method Append() : StringBuilder vs StringBuffer

With this code:

  public static void main(String[] args) {

    String s = "Java";
    StringBuilder buffer = new StringBuilder(s);
    change(buffer);

       System.out.println("What's strBuf.charAt(5)? " + strBuf.charAt(3));
       System.out.println(buffer);
  }

     private static void change(StringBuilder buffer) {

          buffer.append(" and HTML");
  }

When I run the code using StringBuilder I get error message

 The constructor StringBuilder(String) is undefined
    The method charAt(int) is undefined for the type StringBuilder

Tried StringBuffer instead and it works. The content of the StringBuffer object is compiled to "Java and Eclipse.."

  public static void main(String[] args) {

    String s = "Java";
    StringBuffer strbuf = new StringBuffer(s);
    change(strbuf);

               System.out.println("The Stringbuffer.charAt(5) is ? " + strbuf.charAt(3));
           System.out.println(strbuf);
 }

       private static void change(StringBuffer strbuf) {

                       strbuf.append(" and Eclipse");
 }

}

Upvotes: 0

Views: 18297

Answers (3)

Some Java Guy
Some Java Guy

Reputation: 5118

Make sure that you are not defining your class name as StringBuilder

For Example: Even if you import it correctly

 import java.lang.StringBuilder;

But if you write your class as

 public class StringBuilder { //If class name matches below Object Creation
 public static void main(String[] args) {

String s = "Java";
StringBuilder buffer = new StringBuilder(s);  //Object creation
change(buffer);

   System.out.println("What's strBuf.charAt(5)? " + strBuf.charAt(3));
   System.out.println(buffer);
}

 private static void change(StringBuilder buffer) {

      buffer.append(" and HTML"); //you will get this error at append
  //The method append(String) is undefined for the type StringBuilder
} 
}

Suggestions

Rename your class name to something else but not StringBuilder

Upvotes: 1

Amin Abu-Taleb
Amin Abu-Taleb

Reputation: 4511

You might have imported a wrong StringBuilder class instead of java.lang.StringBuilder which does have a StringBuilder(String) constructor and charAt(int) method.

Could you check your import. You should have this one

import java.lang.StringBuilder;

Upvotes: 3

fge
fge

Reputation: 121712

StringBuilder does have a constructor accepting a String as an argument, and does have a .charAt() method (which it it must implement since it implements CharSequence).

Conclusion: this is a mishap from the part of your IDE, which did not import the correct StringBuilder. You use another library which has the unfortunate "property" of having implemented a class by the same name -- but not in the same package.

Go see at the top of your file if the import line is:

import java.lang.StringBuilder;

Upvotes: 5

Related Questions