Java Int to String - Integer.Tostring(I) VS New Integer(I).Tostring()

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Integer.toString calls the static method in the class Integer. It does not need an instance of Integer.

If you call new Integer(i) you create an instance of type Integer, which is a full Java object encapsulating the value of your int. Then you call the toString method on it to ask it to return a string representation of itself.

If all you want is to print an int, you'd use the first one because it's lighter, faster and doesn't use extra memory (aside from the returned string).

If you want an object representing an integer value—to put it inside a collection for example—you'd use the second one, since it gives you a full-fledged object to do all sort of things that you cannot do with a bare int.

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

Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).

Java toString method difference

From javadoc https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

String toString()
Returns a String object representing this Integer's value.

static String toString(int i)
Returns a String object representing the specified integer.

Why should I use Integer.toString() instead of just printing the Integer?

It's one of many "safe programming" practices you can adopt to improve clarity and prevent subtle errors which you or a future maintainer of your code could introduce. Take the following example:

private static void printMessage(int k) {
System.out.println("number" + '=' + k);
}

output: number=5

Now suppose you want to print the number first and the text last. All I'm doing is swapping the first and last items in the string concatenation:

private static void printMessage2(int k) {
System.out.println(k + '=' + "number");
}

output: 66number

Oops! The int value of = was added to k instead of being concatenated. One solution is to make the = into a String. Another solution is to explicitly convert the int to a String:

private static void printMessage2Safe(int k) {
System.out.println(Integer.toString(k) + '=' + "number");
}

output: 5=number

"Oh, but I'd never do that, anyway," you say. "Anyone in their right mind would have just made the = part of the other String." But what if you're implementing part of a basic calculator app, and you want to output the expression and its result? If you're really trying to be careful, I suppose you'll use StringBuilder.append() to concatenate the parts of the expression. But if not, then I hope you don't write the first implementation of the display method below.

public class Calculator {

public static void main(String[] args) {
display(2, '+', 3, 5);
displaySafe(2, '+', 3, 5);
}

public static void display(int num1, char operator, int num2, int result) {
System.out.println(num1 + operator + num2 + '=' + result);
}

public static void displaySafe(int num1, char operator, int num2, int result) {
System.out.println(Integer.toString(num1) + operator + Integer.toString(num2) + "=" + result);
}

}

output:

114
2+3=5

Integer.toString() changes value of int

This all is happening because your webservice response is coming later then your code execution for paramage Hashmap input process. When you are adding static value then it is working so in this case you have to add data after webservice response like below.

HashMap<String,String> paramage= new HashMap<String, String>();

Kumulos.call("login", params, new ResponseHandler() {
@Override
public void didCompleteWithResult(Object result) {

Integer field2 = 0;
ArrayList<LinkedHashMap<String, Object>> objects = (ArrayList<LinkedHashMap<String, Object>>) result;
LinkedHashMap<String, Object> item = objects.get(0);
field2 = Integer.parseInt(item.get("credentialID").toString());
ID = field2.intValue();
UName.setText(Integer.toString(ID));

paramage.put("credential", Integer.toString(ID)); //up here

//As you are making web service call for "getage" so I put this code here. You can make a callback to write this code outside for "getage" webservice call.
Kumulos.call("getage", paramage, new ResponseHandler() {
@Override
public void didCompleteWithResult(Object result) {
Integer field2 = 0;
ArrayList<LinkedHashMap<String, Object>> objects = (ArrayList<LinkedHashMap<String, Object>>) result;
LinkedHashMap<String, Object> item = objects.get(0);
//Boolean check = item.containsKey("age");
field2 = Integer.parseInt(item.get("age").toString());
int age = field2.intValue();
UAge.setText(Integer.toString(age));
}
});
}
});

Integer.toString() vs. Integer.parseInt()

Integer.parseInt converts a String to a primitive int and primitives can be compared with ==. However, Integer.toString produces a String object and == for objects checks that they are the exact same reference; use String#equals instead to compare the values of the Strings.

System.out.println(Integer.toString(3).equals("3"));
System.out.println(Integer.parseInt("3") == 3);

The above code outputs:

true
true

Delphi compiler difference between IntToStr() and Integer.ToString()?

Disclaimer: The following text contains details that only apply to Delphi 10.2.1 (and also 10.2.2) which seems to have made something worse about inlining and RVO:

The code produced by the compiler indeed differs (regardless the compiler version) as you can easily see when looking into the disassembly window.

Lets take this routine:

procedure Main;
var
i: Integer;
s: string;
begin
i := 0;
s := IntToStr(i);
s := i.ToString;
end;

Now let's run this and look into the disassembly window to check the code the compiler produced:

This is what you got with Delphi 10.1:

Project1.dpr.14: s := IntToStr(i);
00419810 8D55F8 lea edx,[ebp-$08]
00419813 8B45FC mov eax,[ebp-$04]
00419816 E80DA4FFFF call IntToStr
Project1.dpr.15: s := i.ToString;
0041981B 8D55F4 lea edx,[ebp-$0c]
0041981E 8B45FC mov eax,[ebp-$04]
00419821 E802A4FFFF call IntToStr
00419826 8D45F8 lea eax,[ebp-$08]
00419829 8B55F4 mov edx,[ebp-$0c]
0041982C E843D2FEFF call @UStrLAsg

And this is what you get with 10.2.1 (and also 10.2.2):

Project1.dpr.14: s := IntToStr(i);
00419B04 8D55F8 lea edx,[ebp-$08]
00419B07 8B45FC mov eax,[ebp-$04]
00419B0A E8C5A2FFFF call IntToStr
Project1.dpr.15: s := i.ToString;
00419B0F 33C0 xor eax,eax
00419B11 55 push ebp
00419B12 68499B4100 push $00419b49
00419B17 64FF30 push dword ptr fs:[eax]
00419B1A 648920 mov fs:[eax],esp
00419B1D 8D55F4 lea edx,[ebp-$0c]
00419B20 8B45FC mov eax,[ebp-$04]
00419B23 E8ACA2FFFF call IntToStr
00419B28 8D45F8 lea eax,[ebp-$08]
00419B2B 8B55F4 mov edx,[ebp-$0c]
00419B2E E805D0FEFF call @UStrLAsg
00419B33 33C0 xor eax,eax
00419B35 5A pop edx
00419B36 59 pop ecx
00419B37 59 pop ecx
00419B38 648910 mov fs:[eax],edx
00419B3B 68509B4100 push $00419b50
00419B40 8D45F4 lea eax,[ebp-$0c]
00419B43 E8D4CCFEFF call @UStrClr
00419B48 C3 ret
00419B49 E9CEC3FEFF jmp @HandleFinally
00419B4E EBF0 jmp $00419b40

Now the million dollar question is, what is all that extra instructions there?!

The extra instructions that you can see in both compilers is the result of missing so called return value optimization. As you might know the compiler treats results of functions that are of a managed type (like string) as hidden var parameter. Now when the compiler does the inlining it does not eliminate this parameter and directly passes the s variable to the IntToStr as it does when directly calling it. It rather reserves a temporary variable that it uses to pass to the IntToStr and then after that assigns that variable to s (that's the call @UStrLAsg you see there 3 lines after the IntToStr call).

As I mentioned above there seems to be a regression in 10.2 or 10.2.1 where they changed something about temporary variable cleanup right after the inlined call (that's the extra instructions before and after that).

Reported as RSP-19439.

To be continued ...

Integer.parseInt() and Integer.toString() runtime

Yes both of them Integer.parseInt("1000") and Integer.toString(1000) have time complexity O(N)

  • The internal code of Integer.parseInt("1000") reads the the strings char by char and covert to decimal in while loop

  • The internal code of Integer.toString(1000) reads the integers and convert every digit to char and stores in byte[] buf then creates new string from the byte array

Here is the code of Integer.parseInt():

int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
// some checks
int multmin = limit / radix;
int result = 0;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
int digit = Character.digit(s.charAt(i++), radix);
if (digit < 0 || result < multmin) {
throw NumberFormatException.forInputString(s, radix);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s, radix);
}
result -= digit;
}
return negative ? result : -result;


Related Topics



Leave a reply



Submit