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");
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Zehafta Tekea
  • 41
  • 1
  • 5
  • 1
    Can you share some more code -- are you actually appending anything to `demo`? – Mick Mnemonic Mar 25 '16 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*. – Zehafta Tekea Mar 25 '16 at 23:16

2 Answers2

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);
Willcodeforfun
  • 361
  • 3
  • 10
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
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.

Community
  • 1
  • 1
rdonuk
  • 3,921
  • 21
  • 39