Eclipse: Convert String Concat to StringBuilder

Here is a simple yet effective trick for all Eclipse users. In Java we do lot of String concatenation using plain old “” + “”. It is easy but not too effective. StringBuilder is always preferred if you have too many strings to concate.

In below screencast, I convert concatenated strings to StringBuilder using eclipse Ctrl + 1 option.

Move cursor on String “foo” and press Ctrl + 1. It opens a context menu. Select option Use “StringBuilder” for string concatenation

String foo = "This" + "is" + "Sparta"; System.out.println(foo);
Code language: Java (java)

Once done, the code will be converted to below:

StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("This"); stringBuilder.append("is"); stringBuilder.append("Sparta"); String foo = stringBuilder.toString(); System.out.println(foo);
Code language: Java (java)

Enjoy :)

View Comments

  • Hi Viral,

    few small comments.
    1.) The taken example isn't well-chosen.
    [code language="java"]String foo = "This" + "is" + "Sparta";[/code]
    will be compiled as
    [code language="java"]String foo = "This is Sparta";[/code]

    2.) if you consider following case
    [code language="java"]String foo = "This" + variable + "Sparta";[/code]
    this will lead in a more optimised bytecode by the compiler
    [code language="java"]String foo = (new StringBuilder()).append("This").append(variable).append("Sparta").toString();[/code]

    3.) in case many variables needs to be concatenated I prefer to use String.format(..) (very simple example)
    [code language="java"][/code]String foo = String.format("%s from %s has %s %s", name, town, amount, gadgets);

    cheers

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago