Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

14. Converting int to String

As usual, in Java, we can accomplish a task in multiple ways. For instance, we can convert an int (primitive integer) to String via Integer.toString(), as follows:

public String intToStringV1(int v) {
  return Integer.toString(v);
}

Alternatively, you can accomplish this task via a quite common hack (the code reviewer will raise his eyebrow here), consisting of concatenating an empty string with the integer:

public String intToStringV2(int v) {
  return "" + v;
}

String.valueOf() can also be used as follows:

public String intToStringV3(int v) {
  return String.valueOf(v);
}

A more esoteric approach via String.format() is as follows:

public String intToStringV4(int v) {
  return String.format("%d", v);
}

These methods also work for a boxed integer and, therefore, for an Integer object. Since boxing and unboxing are costly operations, we strive to avoid them unless they are really necessary. However...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard