Home
Map
String valueOf ExampleUse the String.valueOf method to get a string representation from ints and bools.
Java
This page was last reviewed on May 20, 2023.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.