String method Append() : StringBuilder vs StringBuffer

后端 未结 3 1445
小蘑菇
小蘑菇 2021-01-26 10:53

With this code:

  public static void main(String[] args) {

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

               


        
3条回答
  •  春和景丽
    2021-01-26 11:17

    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

提交回复
热议问题