Convert Integer, Double to String in Java - java

Which of the following ways is better to convert Integer, Double to String in Java.
String.valueOf(doubleVal)
doubleVal + ""
doubleVal.toString()
Thanks.

doubleVal + "" is most likely the worst since it has to do a concatanation with an empty string. However, the other two are equivalent. The source code from OpenJDK:
// java.lang.String
public static String valueOf(double d) {
return Double.toString(d);
}
// java.lang.Double
public static String toString(double d) {
return new FloatingDecimal(d).toJavaFormatString();
}

I don't think there's a performance difference. Go for the most readable!
The first one is exactly equivalent to doublevar.toString() (check the javadoc). The second one is more suited for concatenating longer strings.
If you need to format the way your number is represented as a String, you anyway need to look into other classes

The first and the third are good, the second is bad.
The reason that the second is bad is because the code doesn't show what you want to do. The code says that you want to concatentate the value with an empty string, when you actually want only the conversion that happens before the concatenation.

I prefer to use Integer.toString(int), when you use String.valueOf(int), it internally calls to Integer.toString(int) (same with long, float and double). But for readability, it would be better to use String.valueOf()

There are slight semantic differences depending on whether you're using the primitive double type, or its object wrapper Double.
Anything that will work for a primitive double will also work for the object wrapped Double, but the opposite will not work. (That is, a primitive double will not be accepted if the parameter is of type Double.)
Also, the Double type's value may be null, but the primitive double type cannot.
Beyond that, there isn't much difference at all. For the code snippets you've provided, there isn't any worth really talking about.

i) String.valueOf(int i)
ii) Integer.toString(int i)
After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)
Just two different ways of doing the same thing

In String type we have several method valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
every implementation of specific method like you have presented: So for double
Double.toString(dobule d)
and so on
In my opinion this is not some historical thing, but is more useful for developer to use the method valueOf from String class than from proper type, because is less changes to make when we want to change the type that we operate on.
Sample 1:
public String doStaff(int num) {
//Do something with num
return String.valueOf(num);
}
Sample2:
public String doStaff(int num) {
//Do somenthing with num
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
My conclusion is that using the valueOf method from String class is more flexible and that why is available there.

From the official source:
public static String valueOf(double d) {
return Double.toString(d);
}
So the first and the third are not really different, as long as doubleVal is double and not Double. This is because in the case of a Double, you will call
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
The second is certainly worse because of the need to concatenate.
CONCLUSION:
Following the question, I must assume that the most efficient way is to call the toString() method.

Java string.valueOf() method converts different types of value such as long,int,double,float into String.
Double double_val=45.9;
String string_conversion=String.valueOf(double_val);

Related

Is it standard way to use javaargs instead of overloading in Java?

Is it a standard way to code or any other alternatives are there? I thinking this a while about the code that I've written. Finally gave up and thought to check with you guys.
Here is the scenario I had.
private String functionNameXYZ(String a,String b) {
//Logic goes here
}
private String functionNameXYZ(String a,String b,String c) {
//Same logic goes here , Nothing much difference because of String c
}
So I tho
ught to skip two functions for same purpose and I created a single function as below.
private String functionNameXYZ(String a, String b,String... c){
return performlogic(a,b,(c.lenght!=0)? c[0]:null);
}
private String performlogic(String a,String b, String c) {
//logic , return "string"
}
Which is standard way of coding? Was it to seperate logic into new method instead of repeating[Second case] or Was it other way? Kindly suggest if you find any better ways?
If your only two valid options are two String arguments and three String arguments, using varargs is a tad overkill, and worse - it's confusing, as it implies that you could also pass five or ten or a gazillion arguments. Instead, you could do something much simpler:
private String functionNameXYZ(String a, String b) {
functionNameXYZ(a, b, null);
}
private String functionNameXYZ(String a, String b, String c) {
// One place for the logic
}
Your first scenario is fine, except you want to maybe take any large bulk of common code in the functions and put it in a separate function (or more easily, have the function with less params call the one with more).
The overloading is fine, but rewriting the same code both places is not good practice.
Also, since Java doesn't have default parameters, I'm not too keen on having a public method's argument that is nullable, even if noted on the JavaDocs. Overloading is the way to go.
I think you need to ask yourself a question: what input is legal?
If your program should handle 2...n arguments, then absolutely go with the varargs. However if the legal input to your function is either exactly 2 or 3 arguments, then you should use the pattern:
private String functionNameXYZ(String a, String b) {
// logic of function
}
private String functionNameXYZ(String a, String b, String c) {
// place the logic for handling 'c' input then call
functionNameXYZ(a, b);
}
Alternatively, as the other poster mentioned:
private String functionNameXYZ(String a, String b) {
functionNameXYZ(a, b, null);
}
private String functionNameXYZ(String a, String b, String c) {
// One place for the logic
}
Personally, I prefer the first approach as it clearly separates the logic used to handle the 'c' parameter and the others. This is commonly used when you can seperate that logic, e.g. in constructors. However, when the logic can't easily be untangled go for the second approach.

Purpose of return new?

public Double squareRoot(Double d)
{
return new Double (Math.sqrt(d.doubleValue()));
}
What is the purpose of "return new"? Would it still work if "new" was removed?
Yes, in fact you can remove even more code:
public Double squareRoot(Double d)
{
return Math.sqrt(d);
}
Even though Math.sqrt returns a double and not a Double. This is done by a java feature called Autoboxing.
But as #assylias pointed out, you asked if it is ok to just remove the new keyword. The answer to that is no. This does not compile:
public Double squareRoot(Double d)
{
return Double (Math.sqrt(d.doubleValue()));
}
The error is "Method call expected". You can't call a class' constructor as a method. You can only call a constructor by putting a new keyword in front of it.
You are not using something called 'return new', instead, the following code:
return new Double (Math.sqrt(d.doubleValue()));
actually does
new Double (Math.sqrt(d.doubleValue())) (which creates a new Double object with the value of Math.sqrt(d.doubleValue())
return value of step 1
Java also has a concept called autoboxing which allows for automatic conversion between objects of type Double and values of the type double. As result you don't need to explicitly create an object using new Double(...) because Math.sqrt(...) returns a value of double. Java will do that automagically for you. Same applies to the parameter d: you don't need to call doubleValue() on it.
So you can change the code to:
public Double squareRoot(Double d) {
return Math.sqrt(d);
}
Or better yet use the primitive double as an object of type Double is not really necessary here:
public double squareRoot(double d) {
return Math.sqrt(d);
}
Or better yet (as forivall pointed out in comments to another answer) don't bother with this method and simply call Math.sqrt(...) directly.
This new Double (Math.sqrt(d.doubleValue())); involves converting a primitive type double to its wrapper class Double, and the other way round. But it's unnecessary. Instead, you can do return Math.sqrt(d), which is an example of both autoboxing and unboxing.
"Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing."
http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
Yes, it would still work (provided you also remove the brackets around Math.sqrt(d)) - as long as you're using Java 5 or newer. That feature is called autoboxing / auto-unboxing, meaning the JVM will automatically wrap a primitive in it's corresponding wrapper type.
However, the disadvantage of writing return new Double(Math.sqrt(d)) is that is slightly less efficient. If you use return Double.valueOf(Math.sqrt(d)) (or just return Math.sqrt(d); is that the first option will create a new Double object, whereas the latter two options will try to re-use an earlier created Double instance.
See the Double.valueOf() Javadoc for details.

Integer.toString(int i) vs String.valueOf(int i) in Java

I am wondering why the method String.valueOf(int i) exists ? I am using this method to convert int into String and just discovered the Integer.toString(int i) method.
After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)
In String type we have several method valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
every implementation of specific method like you have presented: So for integers we have
Integer.toString(int i)
for double
Double.toString(double d)
and so on
In my opinion this is not some historical thing, but it is more useful for a developer to use the method valueOf from the String class than from the proper type, as it leads to fewer changes for us to make when we want to change the type that we are operating on.
Sample 1:
public String doStuff(int num) {
// Do something with num...
return String.valueOf(num);
}
Sample2:
public String doStuff(int num) {
// Do something with num...
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
In my conclusion, using the valueOf method from String class is more flexible and that's why it is available there.
One huge difference is that if you invoke toString() in a null object you'll get a NullPointerException whereas, using String.valueOf() you may not check for null.
Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).
The String class provides valueOf methods for all primitive types and Object type so I assume they are convenience methods that can all be accessed through the one class.
NB Profiling results
Average intToString = 5368ms, Average stringValueOf = 5689ms (for 100,000,000 operations)
public class StringIntTest {
public static long intToString () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = Integer.toString(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static long stringValueOf () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = String.valueOf(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static void main(String[] args) {
long intToStringElapsed = 0;
long stringValueOfElapsed = 0;
for (int i = 0; i < 10; i++) {
intToStringElapsed += intToString();
stringValueOfElapsed+= stringValueOf();
}
System.out.println("Average intToString = "+ (intToStringElapsed /10));
System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
}
}
From the Java sources:
/**
* Returns the string representation of the {#code int} argument.
* <p>
* The representation is exactly the one returned by the
* {#code Integer.toString} method of one argument.
*
* #param i an {#code int}.
* #return a string representation of the {#code int} argument.
* #see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
So they give exactly the same result and one in fact calls the other. String.valueOf is more flexible if you might change the type later.
If you look at the source code for the String class, it actually calls Integer.toString() when you call valueOf().
That being said, Integer.toString() might be a tad faster if the method calls aren't optimized at compile time (which they probably are).
The implementation of String.valueOf() that you see is the simplest way to meet the contract specified in the API: "The representation is exactly the one returned by the Integer.toString() method of one argument."
To answer the OPs question, it's simply a helper wrapper to have the other call, and comes down to style choice and that is it. I think there's a lot of misinformation here and the best thing a Java developer can do is look at the implementation for each method, it's one or two clicks away in any IDE. You will clearly see that String.valueOf(int) is simply calling Integer.toString(int) for you.
Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object). Only difference is one extra call, which the compiler eliminates to a single call anyway.
So it matters not which you call, other than maybe code-consistency. As to the comments about nulls, it takes a primitive, therefore it can not be null! You will get a compile-time error if you don't initialize the int being passed. So there is no difference in how it handles nulls as they're non-existent in this case.
You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.
Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String, then various calls to String.valueOf(SomeType) may be more readable than various SomeType.toString calls.
my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.
There have no differences between Integer.toString(5) and String.valueOf(5);
because String.valueOf returns:
public static String valueOf(int i) {
return Integer.toString(i);
}
public static String valueOf(float f) {
return Float.toString(f);
}
etc..
Using the method, String.valueOf() you do not have to worry about the data(whether it is int,long,char,char[],boolean,Object), you can just call :
static String valueOf()
using the only syntax String.valueOf() can whatever you pass as a parameter is converted to String and returned..
Otherwise, if you use Integer.toString(),Float.toString() etc.(i.e. SomeType.toString()) then you will have to check the datatype of parameter that you want to convert into string.
So, its better to use String.valueOf() for such convertions.
If you are having an array of object class that contains different values like Integer,Char,Float etc. then by using String.valueOf() method you can convert the elements of such array into String form easily. On contrary, if you want to use SomeType.toString() then at first you will need to know about there their datatype classes(maybe by using "instanceOf" operator) and then only you can proceed for a typecast.
String.valueOf() method when called matches the parameter that is passed(whether its Integer,Char,Float etc.) and by using method overloading calls that "valueOf()" method whose parameter gets matched, and then inside that method their is a direct call to corresponding "toString()" method..
So, we can see how the overhead of checking datatype and then calling corresponding "toString()" method is removed.Only we need is to call String.valueOf() method, not caring about what we want to convert to String.
Conclusion: String.valueOf() method has its importance just at cost of one more call.

How to handle numbers in a generic fashion?

My question is eerily similar to "Writing a generic class to handle built-in types" including being inspired by the fact of working on a class to handle operations on matrices.
Although that question was asked using C# and pointed to an article on Generic Operators.
I don't get it. Java Number does not have an add method so you can have a method like:
public Number myAdd(Number a, Number b){
return a.add(b);
}
So how do you handle a case where you want to be able to handle multiple types of Numbers in Java?
The fundamental problem is with the Java type system which is very primitive.
Since there is no notion of a sealed set of types in Java (nor is it possible for Java to infer the types like Haskell does) there is no way to make make a general Number + Number -> Number without trickery.
For primitives (and those objects like Integer which can be automagically mapped to them) types promotion and the + operation is part of the language. (And this is actual part of the problem: what should Number a + Number b return where a and b are of different types?)
If you really want this behavior you'll have to find (or create) your own custom class that either uses reflection or a series (of checks and) casts and such. Even if you use generics (remember that generics are type-erased) casting will need to be done.
I imagine these problems are part of the reason why Number is as bland as it is.
How good do you want the result to be? If the answer is "good enough, mostly", then this should be sufficent:
public Number myAdd(Number a, Number b){
return a.doubleValue() + b.doubleValue();
}
But if you want something that, say, matches the promotion semantics of Java primitives, you're probably going to have to write it yourself. And then you'll have to figure out what the rules are for all combinations of "non-standard" Number implementations, including BigDecimal, BigInteger, AtomicDouble, AtomicLong, everything in org.apache.commons.lang.mutable, and any random implementation that somebody might decide to write next Tuesday.
It's not clear what the right thing to do is in most of these cases -- converting everything to BigDecimal, for instance, is not an option if one of the arguments is Apache Commons' Fraction.ONE_THIRD; and besides, doing the conversion in a general way presents the same problems as doing the addition in a general way. But having an add() method on Number would require every Number implementation to handle all these cases -- and that's probably why it isn't there.
I don't get it. Java Number does not
have an add method ...
Suppose that java.lang.Number did have an add method or methods, how would you define its signature? How would you define its semantics? How would you deal with "mixed mode" arithmetic?
While it is no doubt possible to answer these questions and design an API, the result is likely to be tricky to use correctly. In addition, it is most unusual for an application to need to perform "representation agnostic" arithmetic. Usually you want / need explicit control over the way that arithmetic is performed and conversions happen. (The Java primitive type promotion rules are already difficult enough for people to get their heads around!!)
All in all, I think that Sun have done us a good service by not trying to support arithmetic in the Number API.
One way of implementing a generic add method is to let the left hand argument infer the return type.
package mixins;
import java.math.BigDecimal;
public class Numbers {
public static boolean isZ(Number n) {
return n instanceof Integer || n instanceof Long || n instanceof Short || n instanceof Byte;
}
public static boolean isR(Number n) {
return n instanceof Double || n instanceof Float;
}
public static BigDecimal add(BigDecimal a, Number b) {
if (b instanceof BigDecimal) {
return a.add((BigDecimal) b);
} else if (isZ(b)) {
return a.add(new BigDecimal(b.longValue()));
} else if (isR(b)) {
return a.add(new BigDecimal(b.doubleValue()));
}
throw new IllegalArgumentException("No valid big decimal translation for " + b.getClass());
}
public static Integer add(Integer a, Number b) {
return a + b.intValue();
}
public static Long add(Long a, Number b) {
return a + b.longValue();
}
public static Float add(Float a, Number b) {
return a + b.floatValue();
}
public static Double add(Double a, Number b) {
return a + b.doubleValue();
}
}
If this is implemented as static methods, you can use static imports.
import static mixins.Numbers.*;
public class Example {
public static void main(String[] args) {
BigDecimal fortytwo = new BigDecimal(42);
BigDecimal fiftyfive = add(fortytwo, 13);
System.out.println(fiftyfive);
}
}
You cannot add any two numbers, for the reasons other pointed out, but you can add numbers of same type, and the result will also be that same type.
You can create generic arithmetics in Java, with something like this:
interface Arithmetics<T> {
T add(T val1, T val2);
}
class IntegerArithmetics implements Arithmetics<Integer> {
Integer add(Integer val1, Integer val2) { return val1 + val2; }
}
//similarly DoubleArithmetics, BigIntegerArithmetics, ...
Generic Java Math library does exactly that for you.
Actually, I've been working on a generic "real" number class (called 'Value') for a while now, but more as a design exercise than anything; and I can see why it hasn't been done sooner.
First off, you have to have to have some basic rules to work by - I chose to use Java FP (IEEE-754) rules - which means you have have to allow for results like 'infinity' and 'NaN', even if the type doesn't actually support them; and things like reciprocals have proved surprisingly tricky. But I'm getting there, and it's been a fun journey.
One thing that helped me was deciding early on that I needed to deal with "identity" values - specifically 0, 1, and -1, along with -0, +/-infinity and NaN as special cases; the reason being that (for example) multiplication by any of them usually doesn't need any calculation at all.
x * 1 = x, x * NaN = NaN, x * 0 = 0 (or NaN), and x * +/-infinity = +/-infinity; and there are similar rules for division, addition and subtraction, which means you can eliminate a lot of dross quickly and consistently.
And that leaves implementers to only have to deal with cases that do need calculation.
Of course, not all types will support all identities, but if you make them methods, you can just throw an exception when either an operand or a result is "unsupported".
Hope it helps anyone else interested in giving it a bash, but it's not as simple it looks. :-)
Personally, I use BigDecimals for almost everything (but that is mainly because I work with currency values). They handle all numeric values of any size. Because of that, in my opinion they are a generic value and could be used as such in your hypothetical example instead of the Number abstract class. Everything can be turned into a BigDecimal, why not use it?
public BigDecimal myAdd(BigDecimal a, BigDecimal b) {
return a.add(b);
}
EDIT: To address BigBrothers comment below, you could always use the doubleValue() method to create your own generic method. The only problem with this is that you may lose precision in some rare cases where someone IS passing in a BigDecimal and it is larger than a Double.maxValue
public Number myAdd(Number a, Number b) {
return new BigDecimal(a.doubleValue() + b.doubleValue());
}
A BigDecimal is a Number, so returning one is of no consequence.

Var-arg of object arrays vs. object array -- trying to understand a SCJP self test question

I'm having trouble understanding this question, and the explanation of the answer for an SCJP 1.6 self test question. Here is the problem:
class A { }
class B extends A { }
public class ComingThru {
static String s = "-";
public static void main(String[] args) {
A[] aa = new A[2];
B[] ba = new B[2];
sifter(aa);
sifter(ba);
sifter(7);
System.out.println(s);
}
static void sifter(A[]... a2) { s += "1"; }
static void sifter(B[]... b1) { s += "2"; }
static void sifter(B[] b1) { s += "3"; }
static void sifter(Object o) { s += "4"; }
}
What is the result? The answer is -434, but what throws me off is the book's explanation. It is vastly different than how the concept was explained earlier in the chapter.
"In general, overloaded var-args
methods are chosen last. Remember that
arrays are objects. Finally, an int
can be boxed to an Integer and then
"widened" to an Object."
Splitting that up, can someone please further define that explanation?
In general, overloaded var-args methods are chosen last.
Arrays are objects (I actually get that, but why is that relevant to this question).
An int can be boxed to an Integer and then "widened" to an Object.
Thanks!
The book is trying to explain why the first two overloads are never selected: because the var-args marker ... makes them be used only if every other possible overload fails. In this case, this doesn't happen -- the two sentences starting with "Remember" is explaining WHY it doesn't happen, why other possible overloads exists in the first and last case (the second case and its match with the 3rd overload of sifter is obvious): an array is an object, and an int can be boxened then widened to an Object, so the 4th overload matches the first and last ones of the calls to sifter.
When attempting to determine which method to invoke, the compiler first looks for non vararg method (e.g. sifter(Object)) before considering a vararg one (e.g. sifter(A[]...)), when both of the methods belong to the same class (more or less).
Since an array is an Object, the invocation of sifter(aa) will match sifter(Object), hence not even considering sifter(A[]...).
Starting from Java 5, the compiler may "box" primitive, i.e. convert primitive values (e.g. int) to their corresponding Object (e.g. Integer). So for sifter(6), the compiler converts the int 6 into an Integer 6, thus it would match the sifter(Object) method.

Categories

Resources