
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
59 lines
2.2 KiB
Plaintext
59 lines
2.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
"Boxing" is the process of putting a primitive value into a primitive-wrapper object. When that's done purely to use the wrapper class' ``++toString++`` method, it's a waste of memory and cycles because those methods are ``++static++``, and can therefore be used without a class instance. Similarly, using the ``++static++`` method ``++valueOf++`` in the primitive-wrapper classes with a non-``++String++`` argument should be avoided.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
int myInt = 4;
|
|
String myIntString = (new Integer(myInt)).toString(); // Noncompliant; creates & discards an Integer object
|
|
myIntString = Integer.valueOf(myInt).toString(); // Noncompliant
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
int myInt = 4;
|
|
String myIntString = Integer.toString(myInt);
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Use "Xxx.toString" instead.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 10 Oct 2014, 13:57:44 Freddy Mallet wrote:
|
|
Perfect @Ann, I would just add the word "just" in the title :
|
|
|
|
|
|
"Primitives should not be boxed just for 'String' conversion"
|
|
|
|
=== on 12 Oct 2014, 16:49:26 Freddy Mallet wrote:
|
|
@Ann, I guess this rule should be associated to Findbugs rule DM_BOXED_PRIMITIVE_TOSTRING
|
|
|
|
=== on 14 Oct 2014, 14:50:53 Ann Campbell wrote:
|
|
Yes, thanks.
|
|
|
|
=== on 15 Sep 2017, 16:48:12 Michael Gumowski wrote:
|
|
Updated RSPEC to remove example of a constant concatenated with an empty String, accordingly to SONARJAVA-2452. Concatenation of literals with empty string (or any String literal) is valid and will produce an optimized string when compiled into bytecode.
|
|
|
|
=== on 27 Sep 2017, 11:28:58 Tibor Blenessy wrote:
|
|
Removing string concatenation altogether from this rule because, as described in \https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1 modern Java compilers can and do optimize string concatenation of primitive values. Furthermore concatenation can be effectively optimized by JIT and trying to be smart may circumvent these optimizations. See for example \http://openjdk.java.net/jeps/280 . Implemented in SONARJAVA-2481
|
|
|
|
endif::env-github,rspecator-view[]
|