Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

490
Visualizações
How to prevent "notice: 'StringBuilder sb' can be replaced with 'String'" in intellij-idea

when I use the IDE -"IDEA 14.03", it always give this notice for me. notice: 'StringBuilder sb' can be replaced with 'String'

Here is the details, when I define a object named "sb",and the object class is "StringBuilder". Here is code snippet that I tried:

StringBuilder sb = new StringBuilder("status=").append(status).append(" ,msg=").append(msg);
System.out.println(sb);

I just want to know what are the benefit if I change the "StringBuilder" to "String". And why the IDE always notify me to change the class type?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

I think in order to understand why your IDE tells you to change StringBuilder to String, you should understand the differences between String, StringBuffer and StringBuilder.

String is immutable. That means if you want to change something from the your string, the original string will not be deleted but created a new one, which includes your changes. StringBuffer and StringBuilder are mutable. That means with your changes, the original string will be changed accordingly.

The another main difference between them is that String and StringBuffer are thread-safe while StringBuilder is not. There are also other differences, please have a look at this site to learn more about the differences.

If you compare String with StringBuilder, on most cases, using String is more practical and logical, if you do not know, what you do with your string.

It is not always better to concatenate string with plus sign (+). For example, StringBuilder's append method is more logical if you change your string in a loop because of its mutability. Please read the comments in the code;

String a;
StringBuilder b;
for(int i=0; i<5; i++)
{
a += i; //String is immutable and in each iteration, a new object will be created
b.append(i); //StringBuilder is mutable and in each iteration, the existing string will be used.
}

What your IDE makes is just show you the best practices. That is why, it is called as recommendation.

If you want to go on your way anyway and do not want Intellij warn you about it; you can disable the warning like;

enter image description here

EDIT

@CrazyCoder's comment is important to note here.

IDE is actually very smart here, it suggests you to change it for better code readability since internally compiler will generate exactly the same bytecode and your code will have the same performance and the same memory usage, but it will be easier to read. You get a readability benefit without any performance compromises. Similar question was asked and answered in IntelliJ IDEA forum some time ago.

over 4 years ago · Santiago Trujillo Relatório

0

I know it's an old question that was already answered with a very good answer, but just a tiny unrelated comment: In such cases, for the sake of readability, (and since the compiler does the same anyway as Ad mentioned) I would use String.format. instead of

StringBuilder sb = new StringBuilder("status=").append(status).append(" ,msg=").append(msg);

I find this more readable:

String.format("status=%s, msg=%s", status, msg);
over 4 years ago · Santiago Trujillo Relatório

0

Although the code is easier to read with String concatenation, for Java 8 and below, this is implemented with a StringBuilder, so on the surface, it looks like your just hurting yourself.

However, StringBuilder has a default capacity of 16. If you dig in the source code for StringBuilder you'll see that the realloc uses:

         int newCapacity = (value.length << 1) + 2;

So, basically you double every time. So, for arbitrary string of length, say 100, you'll end up allocating space and copying 4 times with capacities of 16, 32, 64, and finally 128.

However, you could do something like:

new StringBuffer(128).sb.append("status=").append(status).append(" ,msg=").append(msg).toString();

And, you've saved yourself 3 allocs and array copies.

As I understand it, Java 9+ has a much better solution. So, Knowing that this will be fixed, I usually use Strings unless I know performance is a concern and then I revert StringBuilder's. This is definitely the case if you're working on embedded systems or Android as resources are scarce. On a cloud server, not so much.

As for the IntelliJ inspector, I turned it off, but I usually add a JAVA10 tag in a comment, so that I can find these later and revert them when we migrate to 10. Maybe, I just need to remember to re-enable the inspector instead. :)

PS- I like Udi's answer. I'll look into the implementation.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda