Java valueOf and copyValueOf String Examples

Use the String.valueOf method to get a string representation from ints and bools.

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."StringsStatic

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.intboolean
Tip: We must use the equals method to compare the Strings. This compares their contents, not just references.
Java program that uses valueOf 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); } } } Output 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.
Java program that uses copyValueOf 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); } } Output 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.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.