Using String or StringBuffer in Java: which is better?

I read a lot about using StringBuffer and String, especially regarding concatenation in Java and whether a stream is safe or not.

So, in the various Java methods that should be used?

For example, in PreparedStatement there should be a StringBuffer request:

    String query = ("SELECT * " +
                    "FROM User " +
                    "WHERE userName = ?;");

    try {
        ps = connection.prepareStatement(query);

And again in the String utility, for example:

public static String prefixApostrophesWithBackslash(String stringIn) {
    String stringOut = stringIn.replaceAll("'", "\\\\'");
    return stringOut;
}

and

 // Removes a char from a String.
public static String removeChar(String stringIn, char c) {
    String stringOut = ("");
    for (int i = 0; i < stringIn.length(); i++) {
        if (stringIn.charAt(i) != c) {
            stringOut += stringIn.charAt(i);
        }
    }
    return stringOut;
}

Should I use StringBuffers? Especially where repalceAll is not available for such objects.

thank

Mr. Morgan.

Thanks for all the tips. StringBuffers were replaced by StringBuilders and Strings replaced by StringBuilders, where I thought it was the best.

+5
source share
6 answers

StringBuffer.

StringBuffer , , StringBuilder. StringBuffer StringBuilder, , . .

, , String vs StringBuffer, . , , , , , . , , , .

+7

( StringBuilder StringBuffer...). , " ", .

String - . Java ( StringBuilder) , String. , , , , .

, String StringBuilder... . java.util.regex.Matcher, .

EDIT. , String StringBuilder . Matcher.replaceAll StringBuilder .

StringBuilder. Java ( ), .

+3

 // Removes a char from a String.
public static String removeChar(String stringIn, char c) {
    String stringOut = ("");
    for (int i = 0; i < stringIn.length(); i++) {
        if (stringIn.charAt(i) != c) {
            stringOut += stringIn.charAt(i);
        }
    }
    return stringOut;
}

stringIn.replaceAll(c+"","")

+1

MT- , . StringBuilder StringBuffer.

+1

. String StringBuilder, String, , .

1:

String query = ("SELECT * " +
                "FROM User " +
                "WHERE userName = ?;");

somthing :

StringBuiler sb = new StringBuilder();
sb.append("SELECT * ");
sb.append("FROM User ");
sb.append("WHERE userName = ?;");
String query = sb.toString();

2:

String numbers = "";
for (int i = 0;i < 20; i++)
  numbers = numbers + i;

, StringBuilder .


SUN jdk1.5+. Java jdks . StringBuilder ( StringBuffer jdk 1.4.2 ).

+1

, , StringBuilder. , StringBuffer .

Concatenating strings with the "+" operator is good "only when you're lazy to use StringBuilder or just want the code to be easy to read, and it is acceptable in terms of performance, for example, in the" LOG "startup log. info ("Starting instance" + inst_id + "from" + app_name); "

0
source

All Articles