How to Convert a Number to a String in Java

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";
Code language: Java (java)

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); } }
Code language: Java (java)

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); } }
Code language: Java (java)

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)); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments