What is the purpose of concatenating a string and an integer?

This method returns true if the number passed inside contains 1 .

 public boolean hasOne(int n) { return (n + "").contains("1"); } 

What is the purpose of the + "" ? How to do this n a string ? ( .contains only works with Strings , as I understand it).

-one
java string
May 19 '14 at
source share
3 answers

An int is primitive. Adding a primitive to a string will implicitly convert this primitive to String and add two strings together. In this case, int converted and "" (empty String ) is added,

This can be rewritten as:

 return Integer.toString(n).contains("1"); 

or

 return String.valueOf(n).contains("1"); 

or

 return String.format("%d", n).contains("1"); 
+5
May 19 '14 at 22:27
source share

From a technical point of view, the + operator in Java implies the use of a StringBuilder object, when one of the operands is a string, the Java Compiler (and not the JVM) translates this syntactic sugar into bytecode instructions that call StringBuilder methods to perform concatenation.

The exact equivalent of the piece of code in the question:

  public boolean hasOne(int n) { StringBuilder sb = new StringBuilder(); sb.append(n); // Which does Integer.getChars(i, spaceNeeded, value); sb.append(""); return sb.toString().contains("1"); } 

As mentioned in other answers to this question, the n + "" construct is not an efficient way to convert a primitive integer value to a string - using Integer#toString(int) definitely the recommended way to do this.

EDIT:

While the official Oracle JVM "" + n definitely slower, as it always has been, I came across some confusing results comparing my OpenJDK JVMs. Although I still adhere to my claim that "" + n is a kind of anti-pattern both in terms of performance and clarity, the rather low performance mismatch that I see on OpenJDK.

+2
May 19 '14 at 10:32
source share

The "contains" method (see javadoc at http://docs.oracle.com/javase/7/docs/api/java/lang/String.html # contains (java.lang.CharSequence) takes "CharSequent" as a parameter . "n +" "creates a String object, which is a subclass of CharSequence.

-one
May 19 '14 at 22:28
source share



All Articles