Home
Java
String valueOf Example
Updated May 20, 2023
Dot Net Perls
ValueOf. This static method converts a value (like an int or boolean) into a String. We do not call it on a String instance—instead we use the String class itself.
A static method, we use valueOf to get string representations of things. For example contain the int 100. This is not a string. With valueOf we get "100."
An example. Let's try the String.valueOf method. Here we use it with an int argument and then a boolean argument (100 and false). It returns a string after each call.
Integer Max
boolean
Tip We must use the equals method to compare the Strings. This compares their contents, not just references.
String equals
public class Program { public static void main(String[] args) { // Convert 100 to a String and test it. String value = String.valueOf(100); if (value.equals("100")) { System.out.println(true); } // Convert "false" to a String. String literal = String.valueOf(false); if (literal.equals("false")) { System.out.println(true); } } }
true true
CopyValueOf. This method receives a char array and returns a string with the same characters. It can take an offset and a count, or convert the entire array.
Note The copyValueOf method is the same as the String constructor that receives a char array.
public class Program { public static void main(String[] args) { char[] letters = { 'a', 'b', 'c' }; // Use copyValueOf to convert char array to String. String result = String.copyValueOf(letters); System.out.println(result); } }
abc
Some notes, valueOf. For things like ints and booleans, we cannot use a toString method. These are not objects—they are values. So we have to use the static String.valueOf method.
Some notes, syntactic sugar. For beautiful-looking programs, we need beautiful syntax. But the String.valueOf method is not often needed—instead, we prefer real objects in Java.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen