I've been using
long a = 123456789;
String b = a+"";
to convert a long value (or int) to String, or in this perspective, treat it as String. My question is, is it ok to do this? Are there any negative impact?
And is there any difference in using String.valueOf() vs Long.toString()?
Thanks
It is ok to do this as recent JVM will likely reduce it to:
String b = String.valueOf(a);
As for negatives, it is not good Java coding style as there is ambiguity. If a was null, would b = "null"? or will an NPE be thrown? You know the answer with experience, but this should be obvious to all readers of your code.
First, your code doesn't compile - you have to append an L after the literal:
Long a = 123456789L;
String.valueOf() and Long.toString() methods both have a primitive long as a parameter, but since a is an wrapper (Long), you can just use the Object#toString() method:
String b = a.toString();
If a, however, is a primitive (long), both String.valueOf() and Long.toString() will do the same, so it's a matter of preference which one to use.
Related
I want to write this in Java but I get some errors and I am not sure how to write it:
C = A - (A*B)/100
All of my values are defined as Bigdecimal objects.
I tried something like this but is not working:
C = A.subtract(A.multiply(B).divide(100));
..I get a warning to add more arguments to the divide method. I do not know how to write it correctly. What am I doing wrong? Thanks in advance
BigDecimal has no divide(int) method, but that's what you're asking it to do with .divide(100), because 100 is an int literal. If you refer to the documentation, all of the divide methods accept BigDecimal instances.
You can use divide(BigDecimal) instead, by using BigDecimal.valueOf:
C = A.subtract(A.multiply(B).divide(BigDecimal.valueOf(100)));
(It accepts a long [or double], but int can be promoted to long.)
Alternately, for some values, you might use the String constructor instead:
C = A.subtract(A.multiply(B).divide(new BigDecimal("100")));
...particularly if you're dealing with floating-point values that might lose precision in double. 100 is fine for valueOf, though.
c = a.subtract(a.multiply(b).divide(BigDecimal.valueOf(100.0)));
This question already has answers here:
String valueOf vs concatenation with empty string
(10 answers)
Closed 7 years ago.
I've had a few people tell me that things like this are super lazy:
int val = 5;
System.out.println("" + val);
String myStr = "" + val;
Why is this better than String.valueOf(val)? Isn't it doing the exact same thing under the hood?
It's not really "better", just shorter, making it easier to read and type. There is (virtually) no ther difference, even though a real purist might, probably, say, this is actually worse, because (at least, in the absence of optimization), this creates an intermediate StringBuilder object, that is then appended a character before being converted into a String, so, this may be spending more ticks, than .valueOf.
From JLS:
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.
In terms of instances of wrapper classes, does the instance behave differently when the instance is created via a String arg in the constructor in comparison to an int, double etc.
E.g is there a difference in:
Integer wrapperInt= new Integer(33);
Integer wrapperInt2= new Integer("33");
The end result will be the same - you'll have an Integer object with the value 33.
The version that takes a String will throw a NumberFormatException if the input string cannot be parsed.
Note: There's no need to write a statement like Integer wrapperInt = new Integer(33);. Let the compiler do it for you (auto-boxing):
Integer wrapperInt = 33;
If, for some reason, you do not want to use auto-boxing, then at least use Integer.valueOf(...) instead of using the constructor:
Integer wrapperInt = Integer.valueOf(33);
This is more efficient; the valueOf method can return a cached object (so that it's not necessary to create a new Integer object).
No, it doesn't. Both instances represent the integer 33. If there was a difference, it would be written in the javadoc.
Note that you should favor the usage of the factory methods instead:
Integer i = Integer.valueOf(33);
i = Integer.valueOf("33");
The only difference is you will be creating a string object unnecessarily in the second approach and it will try to parse the string you have passed to the constructor, If it couldn't parse the string then it will throw NumberFormatException.
The answer is that yes, there can be a difference between the two syntaxes. Specifically, the syntax
new Integer(33);
results in the value 33 being interpreted as an integer constant by the compiler and stored as a literal in the code. By contrast, the syntax
new Integer("33");
results in a call that routes the string value through Integer.parseInt(s, 10). This matters if the value in question has a leading zero character; in the case of an int literal, the compiler will evaluate the literal as octal:
new Integer(010); // equals 8
By contrast, the string constructor will always evaluate the value as base 10:
new Integer("010"); // equals 10
In any case, you should almost always be using Integer.valueOf(), as it is usually more efficient.
I have 3 options:
Declare double member and later when I have to pass String use member + "".
Declare double member and later when I have to pass String use Double.toString(member).
Declare Double member = 0.0 and later when I have to pass String use member.toString().
My opinions:
The shortest one. However, member + "" will be converted to new StringBuilder().append(member).append("").toString(), which seems not elegant.
In Double.toString(member) I don't like that it doesn't start from the word member, which is the most important. We only need to convert it. It's better if member is in the beginning, because I pay most attention to the beginning of word. Quick glance and I know "ah, ok I'm passing member". And with Double.toString(member) my very first concentration goes to "ah, ok... a Double, we are doing toString... of a member! Ah ok".
member.toString() looks fine and it can be typed even faster then + "", because of autocompletion in Eclipse. However, objects are much slower then primitives. Reference.
What is the best option? Maybe there are some other options?
The best all-round approach, which will work for anything, is:
String s = String.valueOf(x);
Here x can be a primitive or an object, which (importantly) may be null.
Edit:
The hackaliciuos way is:
X + "";
Although note that this is not very efficient, because it compiles to:
new StringBuilder().append(x).append("").toString();
And the call to .append(x) invokes String.valueOf(x) anyway.
Note that arrays need special treatment:
String s = Arrays.toString(array);
Is conversion to String in Java using
"" + <int value>
bad practice? Does it have any drawbacks compared to String.valueOf(...)?
Code example:
int i = 25;
return "" + i;
vs:
int i = 25;
return String.valueOf(i);
Update: (from comment)
And what about Integer.toString(int i) compared to String.valueOf(...)?
I would always prefer the String.valueOf version: mostly because it shows what you're trying to do. The aim isn't string concatenation - it's conversion to a string, "the string value of i".
The first form may also be inefficient - depending on whether the compiler spots what you're doing. If it doesn't, it may be creating a new StringBuffer or StringBuilder and appending the value, then converting it to a string.
Funnily enough, I have an article about this very topic - written years and years ago; one of the first Java articles on my web site, IIRC.
There is also Integer.toString(int i), which gives you the option of getting the string as a hex value as well (by passing a second param of 16).
Edit I just checked the source of String class:
public static String valueOf(int i) {
return Integer.toString(i, 10);
}
And Integer class:
public static String toString(int i, int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
/* Use the faster version */
if (radix == 10) {
return toString(i);
}
...
If you call String.valueOf(i), it calls Integer.toString(i, 10), which then calls Integer.toString(i).
So Integer.toString(i) should be very slighty faster than String.valueOf(i), since you'd be cutting out two function calls. (Although the first function call could be optimized away by the compiler.)
Of course, a readability argument could still be made for String.valueOf(), since it allows you to change the type of the argument (and even handles nulls!), and the performance difference is negligible.
Definitely use String.valueOf(i).
Although I'm not sure of the optimizations on the compiler side, worst case scenario if you use "" + :
"" creates a new empty string.
"" + creates a StringBuilder (Java 1.5-16)
"" is appended to the StringBuilder, then
In other words, there is a lot of overhead that occurs if you use string addition. This is why it is not recommended to use the + operator on strings in loops. In general, always use Boolean.valueOf, Integer.valueOf, String.valueOf... etc, when possible. You'll save both on memory and on overhead.
Regardless of any performance considerations I think the first variant is really ugly. IMHO it's a shame that this kind of "dynamic casting" is even possible in Java.
Yes, it is IMHO a bad practice.
It would require to memory allocations (unless compiler and/or JIT optimize them). What's more, it will make less evident, what this code tries to do.
Personally I dislike the style of "" + i, but that is really a preference/coding standards thing. Ideally the compiler would optimize those into equivalent code (although you would have to decompile to see if it actually does), but technically, without optimization, "" + i is more inefficient because it creates a StringBuilder object that wasn't needed.
Right off the bat all I can think of is that in the your first example more String objects will be created than in the second example (and an additional StringBuilder to actually perform the concatenation).
But what you are actualy trying to do is create a String object from a int not concatenate a String with an int, so go for the:
String.valueOf(...);
option,
So yes your first option is bad practice!
I wonder what is best for static final variables contributing to compile-time constants:
public static final int VIEW_TYPE_LABEL_FIELD = 1;
public static final int VIEW_TYPE_HEADER_FIELD = ;
...
List <String[]> listViewInfo = new ArrayList<>();
listViewInfo.add(new String[]{"Label/Field view", String.valueOf(VIEW_TYPE_LABEL_FIELD)});
listViewInfo.add(new String[]{"Header/Field view", "" + VIEW_TYPE_LABEL_FIELD});
The compiler can potentially replace the String expressions with a constant. Is one or the other more recognizable as a compile-time constant? Maybe easier for the ("" + ..) construct?