Integer into textview [duplicate] - java

I'm working on a project where all conversions from int to String are done like this:
int i = 5;
String strI = "" + i;
I'm not familiar with Java.
Is this usual practice or is something wrong, as I suppose?

Normal ways would be Integer.toString(i) or String.valueOf(i).
The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).
Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();
at compile-time. It's slightly less efficient (sb.append() ends up calling Integer.getChars(), which is what Integer.toString() would've done anyway), but it works.
To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:
simon#lucifer:~$ cat TestClass.java
public class TestClass {
public static void main(String[] args) {
int i = 5;
String strI = "" + i;
}
}
simon#lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_5
1: istore_1
Initialise the StringBuilder:
2: new #2; //class java/lang/StringBuilder
5: dup
6: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
Append the empty string:
9: ldc #4; //String
11: invokevirtual #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;
Append the integer:
14: iload_1
15: invokevirtual #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;
Extract the final string:
18: invokevirtual #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
21: astore_2
22: return
}
There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.

It's acceptable, but I've never written anything like that. I'd prefer this:
String strI = Integer.toString(i);

It's not a good way.
When doing conversion from int to string, this should be used:
int i = 5;
String strI = String.valueOf(i);

It's not only the optimization1. I don't like
"" + i
because it does not express what I really want to do 2.
I don't want to append an integer to an (empty) string. I want to convert an integer to string:
Integer.toString(i)
Or, not my prefered, but still better than concatenation, get a string representation of an object (integer):
String.valueOf(i)
1. For code that is called very often, like in loops, optimization sure is also a point for not using concatenation.
2. this is not valid for use of real concatenation like in System.out.println("Index: " + i); or String id = "ID" + i;

A lot of introductory University courses seem to teach this style, for two reasons (in my experience):
It doesn’t require understanding of classes or methods. Usually, this is taught way before the word “class” is ever mentioned – nor even method calls. So using something like String.valueOf(…) would confuse students.
It is an illustration of “operator overloading” – in fact, this was sold to us as the idiomatic overloaded operator (small wonder here, since Java doesn’t allow custom operator overloading).
So it may either be born out of didactic necessity (although I’d argue that this is just bad teaching) or be used to illustrate a principle that’s otherwise quite hard to demonstrate in Java.

The expression
"" + i
leads to string conversion of i at runtime. The overall type of the expression is String. i is first converted to an Integer object (new Integer(i)), then String.valueOf(Object obj) is called. So it is equivalent to
"" + String.valueOf(new Integer(i));
Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i)) which will produce the very same result.
The advantage of ""+i is that typing is easier/faster and some people might think, that it's easier to read. It is not a code smell as it does not indicate any deeper problem.
(Reference: JLS 15.8.1)

Personally, I don't see anything bad in this code.
It's pretty useful when you want to log an int value, and the logger just accepts a string. I would say such a conversion is convenient when you need to call a method accepting a String, but you have an int value.
As for the choice between Integer.toString or String.valueOf, it's all a matter of taste.
...And internally, the String.valueOf calls the Integer.toString method by the way. :)

The other way I am aware of is from the Integer class:
Integer.toString(int n);
Integer.toString(int n, int radix);
A concrete example (though I wouldn't think you need any):
String five = Integer.toString(5); // returns "5"
It also works for other primitive types, for instance Double.toString.
See here for more details.

This technique was taught in an undergraduate level introduction-to-Java class I took over a decade ago. However, I should note that, IIRC, we hadn't yet gotten to the String and Integer class methods.
The technique is simple and quick to type. If all I'm doing is printing something, I'll use it (for example, System.out.println("" + i);. However, I think it's not the best way to do a conversion, as it takes a second of thought to realize what's going on when it's being used this way. Also, if performance is a concern, it seems slower (more below, as well as in other answers).
Personally, I prefer Integer.toString(), as it is obvious what's happening. String.valueOf() would be my second choice, as it seems to be confusing (witness the comments after darioo's answer).
Just for grins :) I wrote up classes to test the three techniques: "" + i, Integer.toString, and String.ValueOf. Each test just converted the ints from 1 to 10000 to Strings. I then ran each through the Linux time command five times. Integer.toString() was slightly faster than String.valueOf() once, they tied three times, and String.valueOf() was faster once; however, the difference was never more than a couple of milliseconds.
The "" + i technique was slower than both on every test except one, when it was 1 millisecond faster than Integer.toString() and 1 millisecond slower than String.valueOf() (obviously on the same test where String.valueOf() was faster than Integer.toString()). While it was usually only a couple milliseconds slower, there was one test where it was about 50 milliseconds slower. YMMV.

There are three ways of converting to Strings
String string = "" + i;
String string = String.valueOf(i);
String string = Integer.toString(i);

There are various ways of converting to Strings:
StringBuilder string = string.append(i).toString();
String string = String.valueOf(i);
String string = Integer.toString(i);

It depends on how you want to use your String. This can help:
String total = Integer.toString(123) + Double.toString(456.789);

Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.

String strI = String.valueOf(i);
String string = Integer.toString(i);
Both of the ways are correct.

There are many way to convert an integer to a string:
1)
Integer.toString(10);
2)
String hundred = String.valueOf(100); // You can pass an int constant
int ten = 10;
String ten = String.valueOf(ten)
3)
String thousand = "" + 1000; // String concatenation
4)
String million = String.format("%d", 1000000)

Using "" + i is the shortest and simplest way to convert a number to a string. It is not the most efficient, but it is the clearest IMHO and that is usually more important. The simpler the code, the less likely you are to make a mistake.

Personally I think that "" + i does look as the original question poster states "smelly". I have used a lot of OO languages besides Java. If that syntax was intended to be appropriate then Java would just interpret the i alone without needing the "" as desired to be converted to a string and do it since the destination type is unambiguous and only a single value would be being supplied on the right. The other seems like a 'trick" to fool the compiler, bad mojo when different versions of Javac made by other manufacturers or from other platforms are considered if the code ever needs to be ported. Heck for my money it should like many other OOL's just take a Typecast: (String) i. winks
Given my way of learning and for ease of understanding such a construct when reading others code quickly I vote for the Integer.toString(i) method. Forgetting a ns or two in how Java implements things in the background vs. String.valueOf(i) this method feels right to me and says exactly what is happening: I have and Integer and I wish it converted to a String.
A good point made a couple times is perhaps just using StringBuilder up front is a good answer to building Strings mixed of text and ints or other objects since thats what will be used in the background anyways right?
Just my two cents thrown into the already well paid kitty of the answers to the Mans question... smiles
EDIT TO MY OWN ANSWER AFTER SOME REFLECTION:
Ok, Ok, I was thinking on this some more and String.valueOf(i) is also perfectly good as well it says: I want a String that represents the value of an Integer. lol, English is by far more difficult to parse then Java! But, I leave the rest of my answer/comment... I was always taught to use the lowest level of a method/function chain if possible and still maintains readablity so if String.valueOf calls Integer.toString then Why use a whole orange if your just gonna peel it anyways, Hmmm?
To clarify my comment about StringBuilder, I build a lot of strings with combos of mostly literal text and int's and they wind up being long and ugly with calls to the above mentioned routines imbedded between the +'s, so seems to me if those become SB objects anyways and the append method has overloads it might be cleaner to just go ahead and use it... So I guess I am up to 5 cents on this one now, eh? lol...

As already pointed out Integer.toString() or String.valueOf() are the way to go. I was curious and did a quick benchmark:
Integer.toString(i) and String.valueOf(i) are basically identical in performance, with Integer.toString(i) being a tiny bit faster. However i + "" is 1.7 times slower.
import java.util.Random;
public class Test {
public static void main(String[] args) {
long concat = 0;
long valueOf = 0;
long toString = 0;
int iterations = 10000;
int runs = 1000;
for(int i = 0; i < runs; i++) {
concat += concat(iterations);
valueOf += valueOf(iterations);
toString += to_String(iterations);
}
System.out.println("concat: " + concat/runs);
System.out.println("valueOf: " + valueOf/runs);
System.out.println("toString: " + toString/runs);
}
public static long concat(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = r.nextInt() + "";
}
return System.nanoTime() - start;
}
public static long valueOf(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = String.valueOf(r.nextInt());
}
return System.nanoTime() - start;
}
public static long to_String(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = Integer.toString(r.nextInt());
}
return System.nanoTime() - start;
}
}
Output:
concat: 1004109
valueOf: 590978
toString: 587236

use Integer.toString(tmpInt).trim();

Try simple typecasting
char c = (char) i;

Related

(Java) What is the point of using `concat()`? [duplicate]

Assuming String a and b:
a += b
a = a.concat(b)
Under the hood, are they the same thing?
Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.
public String concat(String s) {
int i = s.length();
if (i == 0) {
return this;
}
else {
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
}
No, not quite.
Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.
To look under the hood, write a simple class with a += b;
public class Concat {
String cat(String a, String b) {
a += b;
return a;
}
}
Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:
java.lang.String cat(java.lang.String, java.lang.String);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
7: aload_1
8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: aload_2
12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String;
18: astore_1
19: aload_1
20: areturn
So, a += b is the equivalent of
a = new StringBuilder()
.append(a)
.append(b)
.toString();
The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.
The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.
Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From #lukaseder, a list of HotSpot JVM intrinsics.
Niyaz is correct, but it's also worth noting that the special + operator can be converted into something more efficient by the Java compiler. Java has a StringBuilder class which represents a non-thread-safe, mutable String. When performing a bunch of String concatenations, the Java compiler silently converts
String a = b + c + d;
into
String a = new StringBuilder(b).append(c).append(d).toString();
which for large strings is significantly more efficient. As far as I know, this does not happen when you use the concat method.
However, the concat method is more efficient when concatenating an empty String onto an existing String. In this case, the JVM does not need to create a new String object and can simply return the existing one. See the concat documentation to confirm this.
So if you're super-concerned about efficiency then you should use the concat method when concatenating possibly-empty Strings, and use + otherwise. However, the performance difference should be negligible and you probably shouldn't ever worry about this.
I ran a similar test as #marcio but with the following loop instead:
String c = a;
for (long i = 0; i < 100000L; i++) {
c = c.concat(b); // make sure javac cannot skip the loop
// using c += b for the alternative
}
Just for good measure, I threw in StringBuilder.append() as well. Each test was run 10 times, with 100k reps for each run. Here are the results:
StringBuilder wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.
a += b takes about 40000ms (40s) for each run.
concat only requires 10000ms (10s) per run.
I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b spends much of the time creating new objects of StringBuilder and then converting them back to String.
Most answers here are from 2008. It looks that things have changed over the time. My latest benchmarks made with JMH shows that on Java 8 + is around two times faster than concat.
My benchmark:
#Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
#Measurement(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
public class StringConcatenation {
#org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State2 {
public String a = "abc";
public String b = "xyz";
}
#org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State3 {
public String a = "abc";
public String b = "xyz";
public String c = "123";
}
#org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State4 {
public String a = "abc";
public String b = "xyz";
public String c = "123";
public String d = "!##";
}
#Benchmark
public void plus_2(State2 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b);
}
#Benchmark
public void plus_3(State3 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b+state.c);
}
#Benchmark
public void plus_4(State4 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b+state.c+state.d);
}
#Benchmark
public void stringbuilder_2(State2 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).toString());
}
#Benchmark
public void stringbuilder_3(State3 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).toString());
}
#Benchmark
public void stringbuilder_4(State4 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).append(state.d).toString());
}
#Benchmark
public void concat_2(State2 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b));
}
#Benchmark
public void concat_3(State3 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b.concat(state.c)));
}
#Benchmark
public void concat_4(State4 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b.concat(state.c.concat(state.d))));
}
}
Results:
Benchmark Mode Cnt Score Error Units
StringConcatenation.concat_2 thrpt 50 24908871.258 ± 1011269.986 ops/s
StringConcatenation.concat_3 thrpt 50 14228193.918 ± 466892.616 ops/s
StringConcatenation.concat_4 thrpt 50 9845069.776 ± 350532.591 ops/s
StringConcatenation.plus_2 thrpt 50 38999662.292 ± 8107397.316 ops/s
StringConcatenation.plus_3 thrpt 50 34985722.222 ± 5442660.250 ops/s
StringConcatenation.plus_4 thrpt 50 31910376.337 ± 2861001.162 ops/s
StringConcatenation.stringbuilder_2 thrpt 50 40472888.230 ± 9011210.632 ops/s
StringConcatenation.stringbuilder_3 thrpt 50 33902151.616 ± 5449026.680 ops/s
StringConcatenation.stringbuilder_4 thrpt 50 29220479.267 ± 3435315.681 ops/s
Tom is correct in describing exactly what the + operator does. It creates a temporary StringBuilder, appends the parts, and finishes with toString().
However, all of the answers so far are ignoring the effects of HotSpot runtime optimizations. Specifically, these temporary operations are recognized as a common pattern and are replaced with more efficient machine code at run-time.
#marcio: You've created a micro-benchmark; with modern JVM's this is not a valid way to profile code.
The reason run-time optimization matters is that many of these differences in code -- even including object-creation -- are completely different once HotSpot gets going. The only way to know for sure is profiling your code in situ.
Finally, all of these methods are in fact incredibly fast. This might be a case of premature optimization. If you have code that concatenates strings a lot, the way to get maximum speed probably has nothing to do with which operators you choose and instead the algorithm you're using!
How about some simple testing? Used the code below:
long start = System.currentTimeMillis();
String a = "a";
String b = "b";
for (int i = 0; i < 10000000; i++) { //ten million times
String c = a.concat(b);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
The "a + b" version executed in 2500ms.
The a.concat(b) executed in 1200ms.
Tested several times. The concat() version execution took half of the time on average.
This result surprised me because the concat() method always creates a new string (it returns a "new String(result)". It's well known that:
String a = new String("a") // more than 20 times slower than String a = "a"
Why wasn't the compiler capable of optimize the string creation in "a + b" code, knowing the it always resulted in the same string? It could avoid a new string creation.
If you don't believe the statement above, test for your self.
Basically, there are two important differences between + and the concat method.
If you are using the concat method then you would only be able to concatenate strings while in case of the + operator, you can also concatenate the string with any data type.
For Example:
String s = 10 + "Hello";
In this case, the output should be 10Hello.
String s = "I";
String s1 = s.concat("am").concat("good").concat("boy");
System.out.println(s1);
In the above case you have to provide two strings mandatory.
The second and main difference between + and concat is that:
Case 1:
Suppose I concat the same strings with concat operator in this way
String s="I";
String s1=s.concat("am").concat("good").concat("boy");
System.out.println(s1);
In this case total number of objects created in the pool are 7 like this:
I
am
good
boy
Iam
Iamgood
Iamgoodboy
Case 2:
Now I am going to concatinate the same strings via + operator
String s="I"+"am"+"good"+"boy";
System.out.println(s);
In the above case total number of objects created are only 5.
Actually when we concatinate the strings via + operator then it maintains a StringBuffer class to perform the same task as follows:-
StringBuffer sb = new StringBuffer("I");
sb.append("am");
sb.append("good");
sb.append("boy");
System.out.println(sb);
In this way it will create only five objects.
So guys these are the basic differences between + and the concat method.
Enjoy :)
For the sake of completeness, I wanted to add that the definition of the '+' operator can be found in the JLS SE8 15.18.1:
If only one operand expression is of type String, then string
conversion (§5.1.11) is performed on the other operand to produce a
string at run time.
The result of string concatenation is a reference to a String object
that is the concatenation of the two operand strings. The characters
of the left-hand operand precede the characters of the right-hand
operand in the newly created string.
The String object is newly created (§12.5) unless the expression is a
constant expression (§15.28)
About the implementation the JLS says the following:
An implementation may choose to perform conversion and concatenation
in one step to avoid creating and then discarding an intermediate
String object. To increase the performance of repeated string
concatenation, a Java compiler may use the StringBuffer class or a
similar technique to reduce the number of intermediate String objects
that are created by evaluation of an expression.
For primitive types, an implementation may also optimize away the
creation of a wrapper object by converting directly from a primitive
type to a string.
So judging from the 'a Java compiler may use the StringBuffer class or a similar technique to reduce', different compilers could produce different byte-code.
The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.
The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.
Except this, the code you provided does the same stuff.
I don't think so.
a.concat(b) is implemented in String and I think the implementation didn't change much since early java machines. The + operation implementation depends on Java version and compiler. Currently + is implemented using StringBuffer to make the operation as fast as possible. Maybe in the future, this will change. In earlier versions of java + operation on Strings was much slower as it produced intermediate results.
I guess that += is implemented using + and similarly optimized.
When using +, the speed decreases as the string's length increases, but when using concat, the speed is more stable, and the best option is using the StringBuilder class which has stable speed in order to do that.
I guess you can understand why. But the totally best way for creating long strings is using StringBuilder() and append(), either speed will be unacceptable.
Note that s.concat("hello"); would result in a NullPointereException when s is null. In Java, the behavior of the + operator is usually determined by the left operand:
System.out.println(3 + 'a'); //100
However, Strings are an exception. If either operand is a String, the result is expected to be a String. This is the reason null is converted into "null", even though you might expect a RuntimeException.

How do I convert from int to String?

I'm working on a project where all conversions from int to String are done like this:
int i = 5;
String strI = "" + i;
I'm not familiar with Java.
Is this usual practice or is something wrong, as I suppose?
Normal ways would be Integer.toString(i) or String.valueOf(i).
The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).
Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();
at compile-time. It's slightly less efficient (sb.append() ends up calling Integer.getChars(), which is what Integer.toString() would've done anyway), but it works.
To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:
simon#lucifer:~$ cat TestClass.java
public class TestClass {
public static void main(String[] args) {
int i = 5;
String strI = "" + i;
}
}
simon#lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_5
1: istore_1
Initialise the StringBuilder:
2: new #2; //class java/lang/StringBuilder
5: dup
6: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
Append the empty string:
9: ldc #4; //String
11: invokevirtual #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;
Append the integer:
14: iload_1
15: invokevirtual #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;
Extract the final string:
18: invokevirtual #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
21: astore_2
22: return
}
There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.
It's acceptable, but I've never written anything like that. I'd prefer this:
String strI = Integer.toString(i);
It's not a good way.
When doing conversion from int to string, this should be used:
int i = 5;
String strI = String.valueOf(i);
It's not only the optimization1. I don't like
"" + i
because it does not express what I really want to do 2.
I don't want to append an integer to an (empty) string. I want to convert an integer to string:
Integer.toString(i)
Or, not my prefered, but still better than concatenation, get a string representation of an object (integer):
String.valueOf(i)
1. For code that is called very often, like in loops, optimization sure is also a point for not using concatenation.
2. this is not valid for use of real concatenation like in System.out.println("Index: " + i); or String id = "ID" + i;
A lot of introductory University courses seem to teach this style, for two reasons (in my experience):
It doesn’t require understanding of classes or methods. Usually, this is taught way before the word “class” is ever mentioned – nor even method calls. So using something like String.valueOf(…) would confuse students.
It is an illustration of “operator overloading” – in fact, this was sold to us as the idiomatic overloaded operator (small wonder here, since Java doesn’t allow custom operator overloading).
So it may either be born out of didactic necessity (although I’d argue that this is just bad teaching) or be used to illustrate a principle that’s otherwise quite hard to demonstrate in Java.
The expression
"" + i
leads to string conversion of i at runtime. The overall type of the expression is String. i is first converted to an Integer object (new Integer(i)), then String.valueOf(Object obj) is called. So it is equivalent to
"" + String.valueOf(new Integer(i));
Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i)) which will produce the very same result.
The advantage of ""+i is that typing is easier/faster and some people might think, that it's easier to read. It is not a code smell as it does not indicate any deeper problem.
(Reference: JLS 15.8.1)
Personally, I don't see anything bad in this code.
It's pretty useful when you want to log an int value, and the logger just accepts a string. I would say such a conversion is convenient when you need to call a method accepting a String, but you have an int value.
As for the choice between Integer.toString or String.valueOf, it's all a matter of taste.
...And internally, the String.valueOf calls the Integer.toString method by the way. :)
The other way I am aware of is from the Integer class:
Integer.toString(int n);
Integer.toString(int n, int radix);
A concrete example (though I wouldn't think you need any):
String five = Integer.toString(5); // returns "5"
It also works for other primitive types, for instance Double.toString.
See here for more details.
This technique was taught in an undergraduate level introduction-to-Java class I took over a decade ago. However, I should note that, IIRC, we hadn't yet gotten to the String and Integer class methods.
The technique is simple and quick to type. If all I'm doing is printing something, I'll use it (for example, System.out.println("" + i);. However, I think it's not the best way to do a conversion, as it takes a second of thought to realize what's going on when it's being used this way. Also, if performance is a concern, it seems slower (more below, as well as in other answers).
Personally, I prefer Integer.toString(), as it is obvious what's happening. String.valueOf() would be my second choice, as it seems to be confusing (witness the comments after darioo's answer).
Just for grins :) I wrote up classes to test the three techniques: "" + i, Integer.toString, and String.ValueOf. Each test just converted the ints from 1 to 10000 to Strings. I then ran each through the Linux time command five times. Integer.toString() was slightly faster than String.valueOf() once, they tied three times, and String.valueOf() was faster once; however, the difference was never more than a couple of milliseconds.
The "" + i technique was slower than both on every test except one, when it was 1 millisecond faster than Integer.toString() and 1 millisecond slower than String.valueOf() (obviously on the same test where String.valueOf() was faster than Integer.toString()). While it was usually only a couple milliseconds slower, there was one test where it was about 50 milliseconds slower. YMMV.
There are three ways of converting to Strings
String string = "" + i;
String string = String.valueOf(i);
String string = Integer.toString(i);
There are various ways of converting to Strings:
StringBuilder string = string.append(i).toString();
String string = String.valueOf(i);
String string = Integer.toString(i);
It depends on how you want to use your String. This can help:
String total = Integer.toString(123) + Double.toString(456.789);
Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.
String strI = String.valueOf(i);
String string = Integer.toString(i);
Both of the ways are correct.
There are many way to convert an integer to a string:
1)
Integer.toString(10);
2)
String hundred = String.valueOf(100); // You can pass an int constant
int ten = 10;
String ten = String.valueOf(ten)
3)
String thousand = "" + 1000; // String concatenation
4)
String million = String.format("%d", 1000000)
Using "" + i is the shortest and simplest way to convert a number to a string. It is not the most efficient, but it is the clearest IMHO and that is usually more important. The simpler the code, the less likely you are to make a mistake.
Personally I think that "" + i does look as the original question poster states "smelly". I have used a lot of OO languages besides Java. If that syntax was intended to be appropriate then Java would just interpret the i alone without needing the "" as desired to be converted to a string and do it since the destination type is unambiguous and only a single value would be being supplied on the right. The other seems like a 'trick" to fool the compiler, bad mojo when different versions of Javac made by other manufacturers or from other platforms are considered if the code ever needs to be ported. Heck for my money it should like many other OOL's just take a Typecast: (String) i. winks
Given my way of learning and for ease of understanding such a construct when reading others code quickly I vote for the Integer.toString(i) method. Forgetting a ns or two in how Java implements things in the background vs. String.valueOf(i) this method feels right to me and says exactly what is happening: I have and Integer and I wish it converted to a String.
A good point made a couple times is perhaps just using StringBuilder up front is a good answer to building Strings mixed of text and ints or other objects since thats what will be used in the background anyways right?
Just my two cents thrown into the already well paid kitty of the answers to the Mans question... smiles
EDIT TO MY OWN ANSWER AFTER SOME REFLECTION:
Ok, Ok, I was thinking on this some more and String.valueOf(i) is also perfectly good as well it says: I want a String that represents the value of an Integer. lol, English is by far more difficult to parse then Java! But, I leave the rest of my answer/comment... I was always taught to use the lowest level of a method/function chain if possible and still maintains readablity so if String.valueOf calls Integer.toString then Why use a whole orange if your just gonna peel it anyways, Hmmm?
To clarify my comment about StringBuilder, I build a lot of strings with combos of mostly literal text and int's and they wind up being long and ugly with calls to the above mentioned routines imbedded between the +'s, so seems to me if those become SB objects anyways and the append method has overloads it might be cleaner to just go ahead and use it... So I guess I am up to 5 cents on this one now, eh? lol...
As already pointed out Integer.toString() or String.valueOf() are the way to go. I was curious and did a quick benchmark:
Integer.toString(i) and String.valueOf(i) are basically identical in performance, with Integer.toString(i) being a tiny bit faster. However i + "" is 1.7 times slower.
import java.util.Random;
public class Test {
public static void main(String[] args) {
long concat = 0;
long valueOf = 0;
long toString = 0;
int iterations = 10000;
int runs = 1000;
for(int i = 0; i < runs; i++) {
concat += concat(iterations);
valueOf += valueOf(iterations);
toString += to_String(iterations);
}
System.out.println("concat: " + concat/runs);
System.out.println("valueOf: " + valueOf/runs);
System.out.println("toString: " + toString/runs);
}
public static long concat(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = r.nextInt() + "";
}
return System.nanoTime() - start;
}
public static long valueOf(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = String.valueOf(r.nextInt());
}
return System.nanoTime() - start;
}
public static long to_String(int iterations) {
Random r = new Random(0);
long start = System.nanoTime();
for(int i = 0; i < iterations; i++) {
String s = Integer.toString(r.nextInt());
}
return System.nanoTime() - start;
}
}
Output:
concat: 1004109
valueOf: 590978
toString: 587236
use Integer.toString(tmpInt).trim();
Try simple typecasting
char c = (char) i;

Is there a way to build a Java String using an SLF4J-style formatting function?

I've heard that using StringBuilder is faster than using string concatenation, but I'm tired of wrestling with StringBuilder objects all of the time. I was recently exposed to the SLF4J logging library and I love the "just do the right thing" simplicity of its formatting when compared with String.format. Is there a library out there that would allow me to write something like:
int myInteger = 42;
MyObject myObject = new MyObject(); // Overrides toString()
String result = CoolFormatingLibrary.format("Simple way to format {} and {}",
myInteger, myObject);
Also, is there any reason (including performance but excluding fine-grained control of date and significant digit formatting) why I might want to use String.format over such a library if it does exist?
Although the Accepted answer is good, if (like me) one is interested in exactly Slf4J-style semantics, then the correct solution is to use Slf4J's MessageFormatter
Here is an example usage snippet:
public static String format(String format, Object... params) {
return MessageFormatter.arrayFormat(format, params).getMessage();
}
(Note that this example discards a last argument of type Throwable)
For concatenating strings one time, the old reliable "str" + param + "other str" is perfectly fine (it's actually converted by the compiler into a StringBuilder).
StringBuilders are mainly useful if you have to keep adding things to the string, but you can't get them all into one statement. For example, take a for loop:
String str = "";
for (int i = 0; i < 1000000; i++) {
str += i + " "; // ignoring the last-iteration problem
}
This will run much slower than the equivalent StringBuilder version:
StringBuilder sb = new StringBuilder(); // for extra speed, define the size
for (int i = 0; i < 1000000; i++) {
sb.append(i).append(" ");
}
String str = sb.toString();
But these two are functionally equivalent:
String str = var1 + " " + var2;
String str2 = new StringBuilder().append(var1).append(" ").append(var2).toString();
Having said all that, my actual answer is:
Check out java.text.MessageFormat. Sample code from the Javadocs:
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
Output:
The disk "MyDisk" contains 1,273 file(s).
There is also a static format method which does not require creating a MessageFormat object.
All such libraries will boil down to string concatenation at their most basic level, so there won't be much performance difference from one to another.
Plus it worth bearing in min that String.format() is a bad implementation of sprintf done with regexps, so if you profile your code you will see an patterns and int[] that you were not expecting.
MessageFormat and the slf MessageFormmater are generally faster and allocate less junk

Replace the first letter of a String in Java?

I'm trying to convert the first letter of a string to lowercase.
value.substring(0,1).toLowerCase() + value.substring(1)
This works, but are there any better ways to do this?
I could use a replace function, but Java's replace doesn't accept an index. You have to pass the actual character/substring. It could be done like this:
value.replaceFirst(value.charAt(0), value.charAt(0).toLowerCase())
Except that replaceFirst expects 2 strings, so the value.charAt(0)s would probably need to be replaced with value.substring(0,1).
Is there any standard way to replace the first letter of a String?
I would suggest you to take a look at Commons-Lang library from Apache. They have a class
StringUtils
which allows you to do a lot of tasks with Strings. In your case just use
StringUtils.uncapitalize( value )
read here about uncapitalize as well as about other functionality of the class suggested
Added: my experience tells that Coomon-Lang is quite good optimized, so if want to know what is better from algorithmistic point of view, you could take a look at its source from Apache.
The downside of the code you used (and I've used in similar situations) is that it seems a bit clunky and in theory generates at least two temporary strings that are immediately thrown away. There's also the issue of what happens if your string is fewer than two characters long.
The upside is that you don't reference those temporary strings outside the expression (leaving it open to optimization by the bytecode compiler or the JIT optimizer) and your intent is clear to any future code maintainer.
Barring your needing to do several million of these any given second and detecting a noticeable performance issue doing so, I wouldn't worry about performance and would prefer clarity. I'd also bury it off in a utility class somewhere. :-) See also jambjo's response to another answer pointing out that there's an important difference between String#toLowerCase and Character.toLowerCase. (Edit: The answer and therefore comment have been removed. Basically, there's a big difference related to locales and Unicode and the docs recommend using String#toLowerCase, not Character.toLowerCase; more here.)
Edit Because I'm in a weird mood, I thought I'd see if there was a measureable difference in performance in a simple test. There is. It could be because of the locale difference (e.g., apples vs. oranges):
public class Uncap
{
public static final void main(String[] params)
{
String s;
String s2;
long start;
long end;
int counter;
// Warm up
s = "Testing";
start = System.currentTimeMillis();
for (counter = 1000000; counter > 0; --counter)
{
s2 = uncap1(s);
s2 = uncap2(s);
s2 = uncap3(s);
}
// Test v2
start = System.currentTimeMillis();
for (counter = 1000000; counter > 0; --counter)
{
s2 = uncap2(s);
}
end = System.currentTimeMillis();
System.out.println("2: " + (end - start));
// Test v1
start = System.currentTimeMillis();
for (counter = 1000000; counter > 0; --counter)
{
s2 = uncap1(s);
}
end = System.currentTimeMillis();
System.out.println("1: " + (end - start));
// Test v3
start = System.currentTimeMillis();
for (counter = 1000000; counter > 0; --counter)
{
s2 = uncap3(s);
}
end = System.currentTimeMillis();
System.out.println("3: " + (end - start));
System.exit(0);
}
// The simple, direct version; also allows the library to handle
// locales and Unicode correctly
private static final String uncap1(String s)
{
return s.substring(0,1).toLowerCase() + s.substring(1);
}
// This will *not* handle locales and unicode correctly
private static final String uncap2(String s)
{
return Character.toLowerCase(s.charAt(0)) + s.substring(1);
}
// This will *not* handle locales and unicode correctly
private static final String uncap3(String s)
{
StringBuffer sb;
sb = new StringBuffer(s);
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
return sb.toString();
}
}
I mixed up the order in various tests (moving them around and recompiling) to avoid issues of ramp-up time (and tried to force some initially anyway). Very unscientific, but uncap1 was consistently slower than uncap2 and uncap3 by about 40%. Not that it matters, we're talking a difference of 400ms across a million iterations on an Intel Atom processor. :-)
So: I'd go with your simple, straightforward code, wrapped up in a utility function.
Watch out for any of the character functions in strings. Because of unicode, it is not always a 1 to 1 mapping. Stick to string based methods unless char is really what you want. As others have suggested, there are string utils out there, but even if you don't want to use them for your project, just make one yourself as you work. The worst thing you can do is to make a special function for lowercase and hide it in a class and then use the same code slightly differently in 12 different places. Put it somewhere it can easily be shared.
Use StringBuffer:
buffer.setCharAt(0, Character.toLowerCase(buffer.charAt(0)));

String concatenation: concat() vs "+" operator

Assuming String a and b:
a += b
a = a.concat(b)
Under the hood, are they the same thing?
Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.
public String concat(String s) {
int i = s.length();
if (i == 0) {
return this;
}
else {
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
}
No, not quite.
Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.
To look under the hood, write a simple class with a += b;
public class Concat {
String cat(String a, String b) {
a += b;
return a;
}
}
Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:
java.lang.String cat(java.lang.String, java.lang.String);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
7: aload_1
8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: aload_2
12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String;
18: astore_1
19: aload_1
20: areturn
So, a += b is the equivalent of
a = new StringBuilder()
.append(a)
.append(b)
.toString();
The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.
The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.
Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From #lukaseder, a list of HotSpot JVM intrinsics.
Niyaz is correct, but it's also worth noting that the special + operator can be converted into something more efficient by the Java compiler. Java has a StringBuilder class which represents a non-thread-safe, mutable String. When performing a bunch of String concatenations, the Java compiler silently converts
String a = b + c + d;
into
String a = new StringBuilder(b).append(c).append(d).toString();
which for large strings is significantly more efficient. As far as I know, this does not happen when you use the concat method.
However, the concat method is more efficient when concatenating an empty String onto an existing String. In this case, the JVM does not need to create a new String object and can simply return the existing one. See the concat documentation to confirm this.
So if you're super-concerned about efficiency then you should use the concat method when concatenating possibly-empty Strings, and use + otherwise. However, the performance difference should be negligible and you probably shouldn't ever worry about this.
I ran a similar test as #marcio but with the following loop instead:
String c = a;
for (long i = 0; i < 100000L; i++) {
c = c.concat(b); // make sure javac cannot skip the loop
// using c += b for the alternative
}
Just for good measure, I threw in StringBuilder.append() as well. Each test was run 10 times, with 100k reps for each run. Here are the results:
StringBuilder wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.
a += b takes about 40000ms (40s) for each run.
concat only requires 10000ms (10s) per run.
I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b spends much of the time creating new objects of StringBuilder and then converting them back to String.
Most answers here are from 2008. It looks that things have changed over the time. My latest benchmarks made with JMH shows that on Java 8 + is around two times faster than concat.
My benchmark:
#Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
#Measurement(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
public class StringConcatenation {
#org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State2 {
public String a = "abc";
public String b = "xyz";
}
#org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State3 {
public String a = "abc";
public String b = "xyz";
public String c = "123";
}
#org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State4 {
public String a = "abc";
public String b = "xyz";
public String c = "123";
public String d = "!##";
}
#Benchmark
public void plus_2(State2 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b);
}
#Benchmark
public void plus_3(State3 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b+state.c);
}
#Benchmark
public void plus_4(State4 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b+state.c+state.d);
}
#Benchmark
public void stringbuilder_2(State2 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).toString());
}
#Benchmark
public void stringbuilder_3(State3 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).toString());
}
#Benchmark
public void stringbuilder_4(State4 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).append(state.d).toString());
}
#Benchmark
public void concat_2(State2 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b));
}
#Benchmark
public void concat_3(State3 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b.concat(state.c)));
}
#Benchmark
public void concat_4(State4 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b.concat(state.c.concat(state.d))));
}
}
Results:
Benchmark Mode Cnt Score Error Units
StringConcatenation.concat_2 thrpt 50 24908871.258 ± 1011269.986 ops/s
StringConcatenation.concat_3 thrpt 50 14228193.918 ± 466892.616 ops/s
StringConcatenation.concat_4 thrpt 50 9845069.776 ± 350532.591 ops/s
StringConcatenation.plus_2 thrpt 50 38999662.292 ± 8107397.316 ops/s
StringConcatenation.plus_3 thrpt 50 34985722.222 ± 5442660.250 ops/s
StringConcatenation.plus_4 thrpt 50 31910376.337 ± 2861001.162 ops/s
StringConcatenation.stringbuilder_2 thrpt 50 40472888.230 ± 9011210.632 ops/s
StringConcatenation.stringbuilder_3 thrpt 50 33902151.616 ± 5449026.680 ops/s
StringConcatenation.stringbuilder_4 thrpt 50 29220479.267 ± 3435315.681 ops/s
Tom is correct in describing exactly what the + operator does. It creates a temporary StringBuilder, appends the parts, and finishes with toString().
However, all of the answers so far are ignoring the effects of HotSpot runtime optimizations. Specifically, these temporary operations are recognized as a common pattern and are replaced with more efficient machine code at run-time.
#marcio: You've created a micro-benchmark; with modern JVM's this is not a valid way to profile code.
The reason run-time optimization matters is that many of these differences in code -- even including object-creation -- are completely different once HotSpot gets going. The only way to know for sure is profiling your code in situ.
Finally, all of these methods are in fact incredibly fast. This might be a case of premature optimization. If you have code that concatenates strings a lot, the way to get maximum speed probably has nothing to do with which operators you choose and instead the algorithm you're using!
How about some simple testing? Used the code below:
long start = System.currentTimeMillis();
String a = "a";
String b = "b";
for (int i = 0; i < 10000000; i++) { //ten million times
String c = a.concat(b);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
The "a + b" version executed in 2500ms.
The a.concat(b) executed in 1200ms.
Tested several times. The concat() version execution took half of the time on average.
This result surprised me because the concat() method always creates a new string (it returns a "new String(result)". It's well known that:
String a = new String("a") // more than 20 times slower than String a = "a"
Why wasn't the compiler capable of optimize the string creation in "a + b" code, knowing the it always resulted in the same string? It could avoid a new string creation.
If you don't believe the statement above, test for your self.
Basically, there are two important differences between + and the concat method.
If you are using the concat method then you would only be able to concatenate strings while in case of the + operator, you can also concatenate the string with any data type.
For Example:
String s = 10 + "Hello";
In this case, the output should be 10Hello.
String s = "I";
String s1 = s.concat("am").concat("good").concat("boy");
System.out.println(s1);
In the above case you have to provide two strings mandatory.
The second and main difference between + and concat is that:
Case 1:
Suppose I concat the same strings with concat operator in this way
String s="I";
String s1=s.concat("am").concat("good").concat("boy");
System.out.println(s1);
In this case total number of objects created in the pool are 7 like this:
I
am
good
boy
Iam
Iamgood
Iamgoodboy
Case 2:
Now I am going to concatinate the same strings via + operator
String s="I"+"am"+"good"+"boy";
System.out.println(s);
In the above case total number of objects created are only 5.
Actually when we concatinate the strings via + operator then it maintains a StringBuffer class to perform the same task as follows:-
StringBuffer sb = new StringBuffer("I");
sb.append("am");
sb.append("good");
sb.append("boy");
System.out.println(sb);
In this way it will create only five objects.
So guys these are the basic differences between + and the concat method.
Enjoy :)
For the sake of completeness, I wanted to add that the definition of the '+' operator can be found in the JLS SE8 15.18.1:
If only one operand expression is of type String, then string
conversion (§5.1.11) is performed on the other operand to produce a
string at run time.
The result of string concatenation is a reference to a String object
that is the concatenation of the two operand strings. The characters
of the left-hand operand precede the characters of the right-hand
operand in the newly created string.
The String object is newly created (§12.5) unless the expression is a
constant expression (§15.28)
About the implementation the JLS says the following:
An implementation may choose to perform conversion and concatenation
in one step to avoid creating and then discarding an intermediate
String object. To increase the performance of repeated string
concatenation, a Java compiler may use the StringBuffer class or a
similar technique to reduce the number of intermediate String objects
that are created by evaluation of an expression.
For primitive types, an implementation may also optimize away the
creation of a wrapper object by converting directly from a primitive
type to a string.
So judging from the 'a Java compiler may use the StringBuffer class or a similar technique to reduce', different compilers could produce different byte-code.
The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.
The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.
Except this, the code you provided does the same stuff.
I don't think so.
a.concat(b) is implemented in String and I think the implementation didn't change much since early java machines. The + operation implementation depends on Java version and compiler. Currently + is implemented using StringBuffer to make the operation as fast as possible. Maybe in the future, this will change. In earlier versions of java + operation on Strings was much slower as it produced intermediate results.
I guess that += is implemented using + and similarly optimized.
When using +, the speed decreases as the string's length increases, but when using concat, the speed is more stable, and the best option is using the StringBuilder class which has stable speed in order to do that.
I guess you can understand why. But the totally best way for creating long strings is using StringBuilder() and append(), either speed will be unacceptable.
Note that s.concat("hello"); would result in a NullPointereException when s is null. In Java, the behavior of the + operator is usually determined by the left operand:
System.out.println(3 + 'a'); //100
However, Strings are an exception. If either operand is a String, the result is expected to be a String. This is the reason null is converted into "null", even though you might expect a RuntimeException.

Categories