Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Java 1.7+ should we still need to convert "this string" + "should" + "be" + "joined" using StringBuffer.append for best practices?

On Java 1.7+ should we still need to convert "this string" + "should" + "be" + "joined" using StringBuffer.append for best practices?

like image 612
kjv.007 Avatar asked Apr 15 '15 05:04

kjv.007


1 Answers

1) constant expressions (JLS 15.28) like "this string" + " should" + " be" + " joined" do not need StringBuilder because it is calculated at compile time into one string "this string should be joined"

2) for non-constant expressions compiler will apply StringBuilder automatically. That is, "string" + var is equivalent to new StringBuilder().append("string").append(var).toString();

We only need to use StringBuilder explicitly where a string is constructed dynamically, like here

    StringBuilder s = new StringBuilder();
    for (String e : arr) {
        s.append(e);
    }
like image 53
Evgeniy Dorofeev Avatar answered Oct 12 '22 22:10

Evgeniy Dorofeev