TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf