search
HomeJavajavaTutorialDifference between valueOf and toString,(String) in Java

In the actual development and application of java projects, it is often necessary to use the basic function of converting objects to String. This article will provide a summary of commonly used conversion methods. Commonly used methods include Object.toString(), (String) the object to be converted, String.valueOf(Object), etc. These methods are analyzed one by one below.


Method 1: Use the Object.toString() method please see below Example:
Object object = getObject();
System.out.println(object.toString());

In this usage method, because there is a public method .toString() in the java.lang.Object class, this method can be called on any java object in the strict sense. But be careful when using it, you must ensure that the object is not a null value, otherwise a NullPointerException will be thrown. When using this method, usually the derived class will override the toString() method in Object.

Method 2: Use the type conversion (String) object method. This is a standard type conversion. , convert the object into a String type value. When using this method, it should be noted that the type must be convertible to String type. Therefore, it is best to use instanceof to do a type check to determine whether it can be converted. Otherwise, it is easy to throw CalssCastException. In addition, special care is required because it is defined as Object The syntax check will not report an error when an object of type is converted to String, which may lead to potential errors. Be extra careful at this time. For example:
Object obj = new Integer(100);
String strVal = (String) obj;
There will be an error at runtime because the Integer type is forced to be converted to the String type and cannot be passed. However,
Integer obj = new Integer(100);
String strVal = (String)obj;
If this is the format code, A syntax error will be reported.

In addition, because the null value can be cast to any java class type, (String)null is also legal.

Method 3: Using String.valueOf(Object) The basis of String.valueOf(Object) is Object.toString(). But it is different from Object#toString(). As mentioned in the previous analysis of method 1, when using the latter, it must be ensured that it is not null. But when using the third method, you don't have to worry about whether the object is a null value. In order to facilitate the explanation of the problem, let's analyze the relevant source code. The source code of String.valueOf(Object) in Jdk is as follows:
public static String valueOf(Object obj) {
return (obj == null) ? " null" : obj.toString(); }
From the above source code, we can clearly see the reason why there is no need to worry about null values. However, this also gives us hidden dangers. We should note that when object is null, the value of String.valueOf(object) is the string "null", not null! ! ! Remember to pay attention during use. Just imagine what problems may occur if we use statements like if(String.valueOf(object)==null){System.out.println("The value passed in is null!");}. Think again, when outputting to the console, what is the visual difference in the execution results of the following statements:

System.out.println(String.valueOf(null ));//It is the string "null"

System.out.println(null);//It is the empty value null
The output we see will be exactly the same thing: null, but do they mean the same thing?

Related recommendations】

1. Detailed explanation of valueOf method examples in java

2. valueOf, parseInt, toString in Java The difference between the three

3. In-depth understanding of the valueOf function and toString method

4. Introduction to the object conversion function toString() and valueOf()

5. Use toString() method to return the time as a string

The above is the detailed content of Difference between valueOf and toString,(String) in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use