In the book, I read that casting int to String using concatenation, for example, where а is int

 String s = a + ""; 

this is a bad way. But

 String s = Integer.toString(a); 

Or

 String s = String.valueOf(a); 

These are good ways. Why? enter image description here

5 answers 5

No, concatenation is not bad. It looks more visually and in most cases, javac able to optimize it using java.lang.StringBuilder . Also, internment works, which allows not to create a lot of objects. For example,

  String value = "hello world" + 1; System.out.println(value == "hello world1"); 

will lead

true

And the Integer.toString and String.valueOf identical, since the latter delegates the call to the second. But they have a feature - with each call a new line is created.

  • String is the same object. You use reference comparison operator for primitives. Maybe all the same equals ? - Flippy
  • 3
    @ SergeyGrushin I compare the links to show that not two objects were created, but one. - Artem Konovalov
  • Everything is clear now :) concatenation is really the best way - Flippy
  • Or "contour", m? - Flippy
  • one
    @vp_arth yes, I am very illiterate :) - Artem Konovalov

Well, maybe, if there is not just a number, but an expression, it is not immediately obvious what the result will be. For example, the following code:

 System.out.println(6 + 4 + ""); System.out.println("" + 4 + 6); 

The first line displays 10, and the second - 46.

  • In both cases there will be no addition, is it not? Concatenation is more important than addition to increasing priority - Flippy
  • Will count from left to right. ideone.com/4QwTGg - Kirill Malyshev
  • Oops. For sure. I did not understand correctly, sorry. - Flippy
  • But you can put the addition in brackets, because they have higher priority. And after that the concatenation will be executed. So, in the book, a bad way means a way with a pitfall - Flippy
  • They write that valueOf is faster (at the end of the article). habrahabr.ru/post/132241 - Kirill Malyshev

This is bad because Java is a strongly typed language, and implicit type conversion is a violation of the language paradigm.

If you have a small application, in which no one except you will ever get into the code, you can run your own way, but imagine that this is a complex project that will have to be corrected by some trainee.

Two code options:

 String s = a + ""; String s = Integer.toString(a); 

The second is a completely normal and standard pattern that will not cause any difficulties, but at first it will stumble and stupid for a couple of minutes, trying to understand what is happening there and why they decided to do this.

  • Oops, again the views have changed. Well, is it really implicit? Concatenation is equivalent to StringBuffer.append() and StringBuffer.append() through toString() Implicit! = Invisible - Flippy
  • 2
    Sergey, int + string is an implicit cast of int to string. This is not prohibited, it is the described behavior of the language, but ideally incorrectly trite. Than the “dangerous” implicit ghost was written in his answer by Kirill Malyshev. If it comes to, for example, PHP with dynamic typing, then such an expression is perfectly normal and will not cause any complaints to anyone, and in Java, where the programmer is sure that the types are brought only consciously, it can lead to a long search for errors from scratch. The issue of hygiene can be said. - rjhdby
  • 3
    @rjhdby I would not say so categorically. In crooked hands, any instrument is "dangerous." Not knowing the priority of operations and the order of operations - I think the problem is primarily a programmer. Objectively, concatenation is more readable + well optimized and knowing how it works in certain situations will significantly bring more benefits than harm. - Artem Konovalov
  • one
    The trainee must be checked for knowledge of concatenation :) - Flippy
  • one
    to create a string. In general, I am tired of proving something, do not want to write nicely and concisely "i'm number #" + number write "i'm number #" + Integer.toString (number) this is of course safer, more ideologically correct, more readable, of course also more productive. - Artem Konovalov

When using concatenation, several unnecessary actions are performed:

  • Integer.toString(a) is called implicitly;

  • StringBuffer is StringBuffer for concatenation where the empty string "" and the number translated to the string are copied.

  • StringBuffer converted to string

The implementation may be different and the compiler may optimize this, but it is better not to use such a method and explicitly call converting a number to a string.

  • one
    I will insert my five kopecks, not BufferString, but StringBuilder, and if you look at the implementation (java 8) then a new string is not created there, which will then be dropped. There, the chars created from int are appended to the internal char array in StringBuilder. - Artem Konovalov
  • one
    StringBuffer Normally: Java compiler can be used. From here: docs.oracle.com/javase/specs/jls/se7/html/ ... But as I understand it, it depends on the implementation and can be implemented from the beginning - Michel_T.
  • thanks for proof. Hmm, it's not very clear what motivated them to use a synchronized StringBuffer instead of a StringBuilder. It is clear that in the absence of content costs for synchronization are absent but still. - Artem Konovalov

Let's write a test class with two ways of casting a number to a string:

 public class TestString { public void intToStringConcat(int value){ String stringValue = value + ""; } public void intToStringValueOf(int value){ String stringValue = String.valueOf(value); } } 

Baytkod for them will be the following:

  public void intToStringConcat(int); Code: 0: new #2 // class java/lang/StringBuilder 3: dup 4: invokespecial #3 // Method java/lang/StringBuilder."<init>":()V 7: iload_1 8: invokevirtual #4 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder; 11: ldc #5 // String 13: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 16: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String; 19: astore_2 20: return public void intToStringValueOf(int); Code: 0: iload_1 1: invokestatic #8 // Method java/lang/String.valueOf:(I)Ljava/lang/String; 4: astore_2 5: return 

Looking at bytecode, we can conclude that in the case of concatenation of a number with a string, a StringBuilder object is StringBuilder , the append() method is executed two times and then toString() .

The StringBuilder.append(int value) and Integer.toString(int values) methods ultimately call the Integer.getChars() method. However, for Android, the Integer.toString(int values) method Integer.toString(int values) optimized by caching values ​​in the range of -100..100. I don’t know what c version this optimization was added to, but nevertheless it is.

From all this we can conclude that converting a number to a string by concatenating a number with an empty string is a bad practice, especially critical in Android, and it doesn’t look very nice.

If you need to convert a number to a string, it is better to use the Integer.toString(int values) method. If you need to form a string of several words and numbers, then concatenation is not a bad option if it is not executed in a loop. A concatenation in a loop is generally a bad idea.

  • one
    Looking at baytkod for the sake of looking into baytkod meaningless. JIT C2 optimizes everything in a way that is not obvious to you. Moreover, the more obvious the code is written, the easier it will be for the JVM to optimize it in runtime. - Nofate ♦
  • @Notafe may also optimize, but this does not mean that you need to write code according to the principle "and it will do so." It is better to write more optimally at once, than later hopes for some optimizations in runtime. - temq
  • I do not say that it is necessary to write anyhow. I am more about the fact that fortune telling on baytkode - this is fortune telling. As for optimizations, at all conferences, people from Oracle say: write simple, clear code until it becomes obvious that there is a bottleneck in it. - Nofate ♦