stay java In the actual development and application of the project , It's often necessary to turn an object into String This basic function . This paper will summarize the common conversion methods . Common methods are Object.toString(),(String) Object to convert ,String.valueOf(Object) etc. . These methods are analyzed one by one .
Method 1: use Object.toString() Methods take a look at the following example :
Object object = getObject();
System.out.println(object.toString());

In this way of use , because Java.lang.Object Class already has public Method .toString(), So for any strict sense of java Object can call this method . But pay attention when using , Must ensure object No null value , Otherwise, it will throw NullPointerException abnormal . In this way , Usually derived classes override Object Inside toString() Method .


Method 2: Using type conversion (String)object Method. This is the standard type conversion , take object Turn into String Type value . When using this method , It should be noted that the type must be converted to String type . So it's best to use it instanceof Do a type check , To see if it can be converted . Otherwise, it's easy to throw CalssCastException abnormal . Besides , The reason to be particularly careful is defined as Object Objects of type are being converted to String Grammar checking does not report errors , This can lead to potential errors . Be very careful at this time . Such as :
Object obj = new Integer(100);
String strVal = (String)obj;
There will be an error at run time , Because the Integer Type cast to String type , Unable to get . however ,
Integer obj = new Integer(100);
String strVal = (String)obj;
Such as format code , A syntax error will be reported .

Besides , because null Value can be cast to any java Class types ,(String)null It's also legal .


Method 3: use String.valueOf(Object) String.valueOf(Object) The foundation is Object.toString(). But it has something to do with Object#toString() It's different . In the front, the method 1 It is mentioned in the analysis of , When using the latter, it is necessary to ensure that null. But with the third method , There will be no need to worry about object Is it null It's worth the question . For the sake of explaining the problem , Let's analyze the relevant source code .Jdk in String.valueOf(Object) Source code is as follows :
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString(); }
You can see clearly from the source code above null It's worth the reason not to worry . however , This just gives us the hidden danger . We should take note of , When object by null when ,String.valueOf(object) The value of is a string ”null”, instead of null!!! Remember to pay attention to . Just imagine , If we use if(String.valueOf(object)==null){System.out.println(“ The value passed in is null!”);} What's wrong with such a statement . Think again , When outputting to the console , Visually, what's the difference between the results of execution of the following statements :

System.out.println(String.valueOf(null));// Is string “null”


System.out.println(null);// It's a null value null
The output we see as like as two peas :null, But they have different meanings .

Java The difference between .toString() ,(String),valueOf() More articles on methods

  1. distinguish javascript Medium toString(),toLocaleString(),valueOf() Method

    First, we create an object at will , It's very simple , open FF Browser's Firebug Switch to the console or open webkit Review element function of browser . Enter the following : var obj1=[1,2,3,4,5] var obj2=[ ...

  2. In short JavaScript Medium tostring( ) And valueOf( ) Method

    explain All objects inherit toString() and valueOf() Method , Object to string , Object to number conversion , This is done by calling one of the two methods of the object to be transformed . explain toString( ) The purpose of the method is to : ...

  3. JS Medium toString() and valueOf() Method

    1.toString() Method : It is mainly used for Array.Boolean.Date.Error.Function.Number And so on . Date type toString() Method returns a readable date and string ...

  4. java in byte turn string What are the methods of ?

    1. The first one is byte b = 1; String valueOf = String.valueOf(b) 2. The second kind byte b = 1; String st = Byte.toString(b); ...

  5. Java Medium toString() Method

    Java Medium toString() Method Catalog Java Medium toString() Method 1.     Object's toString Method 2.     The basic type of toString Method 3.     Array of toString ...

  6. JavaScript Of reference types Array Array of toString() and valueof() Differences in methods

    One . Transformation method 1. stay JavaScript Almost all objects in have toLocaleString().toString and valueof() Method , because , All objects are inherited from Object, And the methods mentioned above are Obj ...

  7. java Algorithm : Statistics - Convert numbers to strings , Then use the string String.valueOf() Method to judge

    subject : Calculated figures k stay 0 To n The number of times in ,k May be 0~9 A value of . Examples Examples 1: Input : k = 1, n = 1 Output : 1 explain : stay [0, 1] in , We found that 1 There is ...

  8. 【Java】Java Commonly used String Method

    This article is reproduced in :java Commonly used String Method 1 length() Length of string String a = "Hello Word!"; System.out.println(a.len ...

  9. java Does the array have length() Method ?string No, lenght() Method ?

    java Does the array have length() Method , To find the length of an array, you can use the length attribute . int[] arr={1,2,3,4,5}; int length=arr.length;// Find the length of the array -- ...

Random recommendation

  1. Erlang stay Windows On the development environment to build the whole process to explain the directory

    I'll follow the list below step by step , stay windows To develop Erlang Some of the tools used , And knowledge . I'll keep adding and fixing . Erlang Runtime environment Erlang Development tool selection Rebar To build , compile , test , Hair ...

  2. Brush questions while working :70 Oh, my God leetcode: day 78

    Graph Valid Tree The main points of : The problem itself is not difficult , The key is that this question involves several related questions , Only by making clear the differences and connections between them can we solve similar problems :isTree Just like isCycle More checking connectivity , So this series of questions is divided into the following three parts from the structure g ...

  3. iOS-XMPP client

    First of all, we make our own IOS Client program Let's take a look at the renderings we've finished First download xmppframework This framework spot ZIP download Next , use Xcode Build a new project Drag these files into the new project Join in frame ...

  4. Use public key To do it SSH authentication

    public key authentication( Public key authentication ) Yes, by typing the user name . An alternative to password login to the server . This method is safer and more adaptable , But it's more difficult to configure . In the traditional password authentication method , By proving that you know ...

  5. cocoa NSFileManager

    NSFileManager Contains a directory for querying the word library . establish . rename . Delete directory and get / How to set file properties ( Readability , Programmability and so on ). Every program has its own sandbox , Through it you can read / Write file . Writing in sandbox ...

  6. Thread A few concepts that are often confused sleep、wait、yield、interrupt ( turn )

    Original website :http://blog.csdn.net/partner4java/article/details/7993420sleep: Sleep the currently executing thread for a specified number of milliseconds ( Suspend execution ), This operation is affected by ...

  7. Mysql Study ( MOOC study notes 2) Database creation and deletion

    Create database { } Mandatory   | Choose from before and after    [ ] Optional Create {database | schema} [if not exists] db_name [default] charact ...

  8. C#(.NET) HMAC SHA256 Realization

    HMAC SHA256 The implementation of is relatively simple , It can be implemented in many languages , Next I use C# Language implementation , One result is that BASE64, The other is living in 64 position . C# HMAC SHA256 (Base64) using Syst ...

  9. synchronous-request-with-websockets

    https://stackoverflow.com/questions/13417000/synchronous-request-with-websockets

  10. Grafana elasticsearch application

    In the early days , Project based on ES+echart Wrote some dashboard display pages , although ES With this char The interface has a natural advantage , But actually writing the code , Or a lot of repetitive work , I found out in an accident that Grafana, See it offers a lot of dashboards ...