public class Test {
public static void main(String[] args) {
Integer obj1 = Integer.valueOf(12);
Integer obj2 = Integer.valueOf("12");
System.out.println(obj1.intValue() + " " + obj2.intValue());
Integer obj3 = Integer.valueOf("1010", 2);
Integer obj4 = Integer.valueOf(1010, 2);//Compile time error.
}
}
//As valueOf() method takes both String and the repective type as argument, but then why
does last statement shows Compile time error where I am trying to use valueOf() method with radix.
Because there is no such overload. Read the documentation.
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
Albeit a good question,I don't know why your question was downvoted,it might be so because your comment was not seen by most of them!
The first part is indeed correct as answered by Jeroen Vannevel,there is no such overloaded version of Integer.valueOf() available in java-library!
The java.lang.Integer.valueOf(String s, int radix) method returns an Integer object holding the value extracted from the specified String s when parsed with the radix given by the second argument radix. So,here String is parsed into Integer object!!!
On the other hand,you are talking about Integer.valueOf(1010, 2). The number 1010 is already an Integer and so it can't be parsed again back to Integer! Also,if you want BinaryString---simply use java.lang.Integer.toBinaryString(). For your satisfaction,if you are still thinking of parsing,then proceed below :-
The solution to end your doubt is
how will you convert Integer.valueOf(1010,16) again into Integer
object???? It'll be containing String(hexadecimal representation of 3F2---see F here)!!!
I hope you have got the reason!!!
Hence,this was not provided in the java-library.
Related
I'm sure this is a small, stupid error that I just can't see.
I'm getting a compiling error in this code:
private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }
in my length.
Compiling error is:
"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList "
How can I fix this? I do want to use Math.random();
Also not sure if this makes a difference, but this is is being done within a String method.
Thanks in advance!
if cities is of type ArrayList you have to use cities.size() instead of cities.length.
There are a couple of errors here.
First: If your method is not void is because you're gonna return something, in your method you should return a String.
Second: The result of Math.floor(Math.random()*cities.length) it's a double, so you can't store on a simple int, you should parse it or just change the int for double
Third: If you wanna return that match variable you should parse it to a String like you're declaring or just change the declaration to double.
So, the easier fix would be just changing the string and int for double and return it like this:
private static double setQuestions(){
double match = Math.floor(Math.random()*cities.length);
return match;
}
Remember if you want to use the double returned you should store it when you call it, like this:
double result = setQuestions();
Hope it helps!
The code has three problems:
First, the variable "cities" is an ArrayList, as the compiller error wrote. ArrayList is a Collection which implements the interface List. The size of any implementations of List is accessable by method size(). Than, you should change cities.length by cities.size() or you turn cities as array.
Second, you defined the variable "match" as an int value but method floor from Math return a double. If you really want "match" to be a int, than you can use the cast against the method floor, that is, you code become: int match = (int) Math.random()*cities.size();
Third, your method requires an String as return, than you should return the String object correctly.
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);
HashMap<String, String> config = Feeds.config;
String num = config.get("NumOfFeeds");
System.out.println(num);
feedsAmount = ((Integer)num).intValue();
System.out.println(feedsAmount);
I've also tried Integer.parseInt(num) and Integer.decode(num) and Integer.valueof(bu)
Results as follows: 40
Exception in thread "main" java.lang.NumberFormatException: For input string:"40"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at fetch_RSS.<init>(fetch_RSS.java:40)
at testing.main(testing.java:27)
The problem was caused by different encoding from the txt file I'm reading from and the encoding in Elipse which is the macRoman by default.
The correct way of working is this:
String num = config.get("NumOfFeeds");
int feeds = Integer.parseInt(num);
This, only when you are sure that the String is representing a number the valid way.
-30 // correct
0 // correct
2000 // correct
"40" // invalid
40 // valid
2.000 // invalid
2.000.000 // invalid
20,0 // invalid
2,000,000 // invalid
Your exception got raised in Integer.java:458.
Looking into the source code of Integer I see that some characters of your String "40" returned a negative value (most probably -1) for Character.digit(s.charAt(i++), radix) where i is iterating over String's characters and radix is 10.
This should not happen normally. But it happens when the String is "4o" and not "40" like #Løkling's wild guess in the comments.
You should debug here to see what really happens.
Of course you can't cast from String to Integer. A String is not a Integer, and Integer is not a String.
You have to use int i = Integer.parseInt(..). It works if the string is a properly formatted integer.
For a cast to succeed in Java, the reference being cast must point to an object that is actually an instance of the type being cast to. A reference to String can't be cast to Integer because an object couldn't possibly be both things.
(This is somewhat unlike a cast in C, which is basically just saying, reinterpret the data stored here according to a different datatype. It would still be incorrect in C to use casting as a method to convert a string representing a number to a numeric value.)
Integer.parseInt is what you are looking for here. What problem are you having with it?
Remember : In java, we can only cast between objects if they are EXPLICITLY of the same type ! In other languages , like python, we can do the casting you requested here, because those languages allow "duck typing".
You must use Integer.parseInt("1234"), to create an Integer object from a String.
Alternatively you could create an Object wrapper to your data :
class MyObject
{
Object input;
public MyObject(Object input)
{
this.input=input;
}
public Integer getInt()
{
return Integer.parseInt(input.toString());
}
public String getString()
{
return input.toString();
}
}
This would be overkill for your simple problem, however :)
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.
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.