How to Convert a Number to a String in Java

0 min read 124 words

The challenge

We need a function that can transform a number into a string.

What ways of achieving this do you know?

Examples:

Solution.numberToString(123); // returns "123";   
Solution.numberToString(999); // returns "999";

The solution in Java code

The easiest way to do this is to use the String.valueOf method to take an integer and return a string:

class Solution {
  public static String numberToString(int num) {
    return String.valueOf(num);
  }
}

This can also be done the other way around, using the Integer.toString method:

class Solution {
  public static String numberToString(int num) {
    return Integer.toString(num);
  }
}

Test cases to validate our Java code

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class NumberStringExampleTests {
  @Test
  public void tests() {
    assertEquals("67", Solution.numberToString(67));
    assertEquals("123", Solution.numberToString(123));
    assertEquals("999", Solution.numberToString(999));
  }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags