String conversions in Java - java

I have a method which takes String argument. In some cases I want to pass int value to that method. For invoking that method I want to convert int into String. For that I am doing the following:
aMethod(""+100);
One more option is:
aMethod(String.valueOf(100));
Both are correct. I don't know which is appropriate? Which gives better performance?
Mostly this is happen in GWT. In GWT for setting size of panels and widgets I want to do this.

Using + on strings creates multiple string instances, so using valueOf is probably a bit more performant.

Since you're mostly using it in GWT, I'd go with the ""+ method, since it's the neatest looking, and it's going to end up converted to javascript anyway, where there is no such thing as a StringBuilder.
Please don't hurt me Skeet Fanboys ;)

Normally you'd use Integer.toString(int) or String.valueOf(int). They both return the same thing, and probably have identical implementations. Integer.toString(int) is a little easier to read at a glance though, IMO.

I'd assume that this:
aMethod(""+100);
turns into this by the compiler:
aMethod(new StringBuilder("").append(String.valueOf(100)).toString());
So the option of calling the String.valueOf directly is probably the better choice. You could always compile them and compare the bytecode to see for sure.

Related

Java which is the correct way of initializing and parsing value for optimisation

Something has been bothering me lately.
I would like to learn the proper way of parsing a value for optimization purpose.
I'm curious to find which method is safer and faster?
Example:
msres.setSomething(api.performReturnUID(parameter1,parameter2,parameter3));
or
int temp_storage = api.performReturnUID(parameter1,parameter2,parameter3)
msres.setSomething(temp_storage);
Should I just execute the custom function upon set or initialize first then parse?.
Speed has nothing to do with this. They're equivalent and if temp_storage isn't used for anything else, may even generate the same bytecode.

any reason to use printf over format or vice versa in java

Im learning formatting in Java and have been using printf and format methods.
To me these seem to behave exactly the same.
Is there any reason why I should use one over the other ?
Is one considered newer and/or a better one to use as standard and if so why?
The situations in which you use them can be different; if you want to print a text it's normally easier to use printf(). If you want to do something else with the String (e.g. put it into a graphical element or a logger) then you'll use String.format().
The PrintStream#printf(...) methods actually delegate to the PrintStream#format(...) methods. So no, there should be no difference.
Edit:
If you are talking about String.format(...), this performs the formatting in exactly the same manner; the difference is that it returns the formatted String instead of writing it to the stream.

Which toString technique is more efficient?

I have a class called Zebra (not her actual name). Zebra overrides the toString method to provide her own convoluted obfuscated stringification.
Which is more efficient to stringify an instance of Zebra? Presuming that I have to do this stringification millions of times per session.
zebra.toString()
""+zebra
static String BLANK (singleton)
BLANK+zebra (multiple executions).
Where the value of zebra is not assured to be the same.
I am conjecturing that the answer could be - no concern: the compiler makes them all equivalent. If that is not the answer, please describe the instantiation process that makes them different. (2) and (3) could be the same, since the compiler would group all similar strings and assign them to a single reference.
Normally, I do ""+zebra because I am too lazy to type zebra.toString().
ATTN: To clarify.
I have seen questions having been criticised like "why do you want to do this, it's impractical" If every programmer refrains from asking questions because it has no practical value, or every mathematician does the same - that would be the end of the human race.
If I wrote an iteration routine, the differences might be too small. I am less interested in an experimental result than I am interested in the difference in processes:
For example, zebra.toString() would invoke only one toString while, "+zebra would invoke an extra string instantiation and and extra string concat. Which would make it less efficient. Or is it. Or does the compiler nullify that.
Please do not answer if your answer is focused on writing an iterative routine, whose results will not explain the compiler or machine process.
Virtue of a good programmer = lazy to write code but not lazy to think.
Number 1 is more efficient.
The other options create an instance of StringBuilder, append an empty string to it, call zebra.toString, append the result of this to the StringBuilder, and then convert the StringBuilder to a String. This is a lot of unnecessary overhead. Just call toString yourself.
This is also true, by the way, if you want to convert a standard type, like Integer, to a String. DON'T write
String s=""+n; // where "n" is an Integer
DO write
String s=n.toString();
or
String s=String.valueOf(n);
As a general rule, I would never use the + operator unless it is on very small final/hard-coded strings. Using this operator usually results in several extra objects in memory being created before your resulting string is returned (this is bad, especially if it happens "millions of times per session").
If you ever do need to concatenate strings, such as when building a unique statement dynamically (for SQL or an output message for example). Use a StringBuilder!!! It is significantly more efficient for concatenating strings.
In the case of your specific question, just use the toString() method. If you dont like typing, use an IDE (like eclipse or netbeans) and then use code completion to save you the keystrokes. just type the first letter or 2 of the method and then hit "CTRL+SPACE"
zebra.toString() is the best option. Keep in mind zebra might be null, in which case you'll get a NullPointerException. So you might have to do something like
String s = zebra==null ? null : zebra.toString()
""+zebra results in a StringBuilder being created, then "" and zebra.String() are appended separately, so this is less efficient. Another big difference is that if zebra is null, the resulting string will be "null".
If the Zebra is Singleton class or the same instance of zebra is being used then you can store the result of toString in Zebra and reuse it for all future calls to toString.
If its not the case then in implementation of toString cache the part which is unchanges everytime in constructing String at one place, this was you can save creating some string instances every time.
Otherwise I do not see any escape from the problem you have :(
Option 1 is the best option since every option calls the toString() method of zebra, but options 2 and 3 also do other (value free) work.
zebra.toString() - Note that this calls the toString() method of zebra.
""+zebra - This also calls the toString() method of zebra.
static String BLANK; BLANK+zebra; - This also calls the toString() method of zebra.
You admit "I'm lazy so I do stupid stuff". If you are unwilling to stop being lazy, than I suggest you not concern yourself with "which is better", since lazy is likely to trump knowledge.
Since the object's toString method will be invoked implicitly in cases where it is not invoked explicitly, a more "efficient" way doesn't exist unless the "stringification" is happening to the same object. In that case, it's best to cache and reuse instead of creating millions of String instances.
Anyway, this question seems more focused on aesthetics/verbosity than efficiency/performance.
If you want to know things like this you can code small example routines and look at the generated bytecode using the javap utility.
I am conjecturing that the answer could be - no concern: the compiler makes them all equivalent. [...] Normally, I do ""+zebra because I am too lazy to type zebra.toString().
Two things:
First: The two options are different. Think about zebra being null.
Second: I'm to lazy to do this javap stuff for you.

Efficient Method of Converting int to String in Java

Integer.toString(int);
and
String.valueOf(int);
Which one among the above two methods is the efficient way of converting an int to String?
Thanks in advance.
String.valueOf calls Integer.toString, so I guess you could argue that Integer.toString is marginally more efficient.
EDIT: With a modern compiler the calls will be inlined so there should be no difference at all between the two. With an ancient compiler the difference should still be negligible.
I think that the String.valueOf() method was just provided for the purpose of flexibility, Since the purpose is closely related with String class(in fact for the conversion to String). While the (Integer/Float/etc).toString() method is the authentic method for the purpose of String conversion. You can refer them as slightly overloaded method.
Actually it doesn't matter which method you use. But I think Integer.toString(int); is more efficient because, String.toString(int); is internally calling the same method.

this["var"+"name"] in java

In AS3 I can write this["foo"] for access to a variable foo. I can construct any string in brackets. Is there a way to do this in Java?
You can use Java's reflection API to achieve the same effect, albeit much less elegantly. See here for a tutorial.
No, you can't do this. But you don't need to. There's an easier way to call variables. You just need to use this.foo to refer to the variable. Now, if you're trying to do something like
String var = "foo";
this[var] = "something else";
You may be able to do that with java reflection, but it would have quite a bit of overhead and I believe it would be quite inefficient.
No. If you want such kind of access, you should consider using Set interface (or reflection api, as noted before me).

Categories