4

Why does NetBeans suggest that I replace StringBuffer / StringBuilder by String?

It shows me a warning message when I write:

StringBuilder demo = new StringBuilder("Hello");
2
  • 1
    Can you share some more code -- are you actually appending anything to demo? Commented Mar 25, 2016 at 23:05
  • @MickMnemonic, If I use any StringBuffer/StringBuilder specific methods, the warning goes away. I was just curious why it suggest that before I do anything with demo. Commented Mar 25, 2016 at 23:16

2 Answers 2

5

Instead of writing

StringBuilder demo = new StringBuilder("Hello");

this is simpler and you don't have to allocate a StringBuilder for it:

String demo = "Hello";

If you use a method which means it has to be a StringBuilder, the warning should go away.

e.g.

StringBuilder demo = new StringBuilder("Hello");
demo.append(" World ");
demo.append(128);
Sign up to request clarification or add additional context in comments.

Comments

3

Replace StringBuffer/StringBuilder by String

The hint will find and offer to replace instances of StringBuffer or StringBuilder which are accessed using ordinary String methods and are never passed out of the method, or assigned to another variable. Keeping such data in StringBuffer/Builder is pointless, and String would be more efficient.

From netbeans wiki.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.