Several formats for converting an object to a string

Source: Internet
Author: User
Tags date now dateformat

In the actual development and application of Java projects, the basic function of converting objects into strings is often used. This article will summarize the commonly used conversion methods. Common methods include object. tostring (), (string) object to be converted, and string. valueof (object. These methods are analyzed one by one.

Method 1: Use object. tostring ()
See the following example:
Object object = GetObject ();
System. Out. println (object. tostring ());
In this method, because public method. tostring () already exists in the Java. Lang. Object Class, this method can be called for any Java object in a strict sense. However, you must ensure that the object is not null. Otherwise, an nullpointerexception is thrown. When this method is used, the derived class usually overwrites the tostring () method in the object.

Method 2: Use the type conversion (string) object Method
This is a standard type conversion that converts an object to a value of the string type.[Color = Red] [/color] when using this method, note that the type must be converted to the string type. Therefore, it is best to use instanceof for a type check to determine whether conversion is possible. Otherwise, a calsscastexception is thrown. In addition, it is important to note that syntax check does not report errors when an object defined as an object is converted to a string, which may lead to potential errors. Be especially careful. For example:
Object OBJ = new INTEGER (100 );
String strval = (string) OBJ;

An error occurs during running because the integer type cannot be forcibly converted to the string type. However,
Integer OBJ = new INTEGER (100 );
String strval = (string) OBJ;
If the format is code, a syntax error is reported.
In addition, because the null value can be forcibly converted to any Java class type, (string) null is also valid.

Method 3: Use string. valueof (object)
String. valueof (object) is based on object. tostring (). But it is different from object. tostring. As mentioned in the analysis in method 1 above, when using the first method, you must ensure that it is not null. However, when using the third method, you don't have to worry about whether the object is null. For ease of Problem description, let's analyze the relevant source code. The source code of string. valueof (object) in JDK is as follows:
/**
* Returns the string representation of the object argument.
*
* @ Param OBJ an object.
* @ Return if the argument is null, then a string equal
* "Null"; otherwise, the value
* Obj. tostring () is returned.
* @ See java. Lang. Object. tostring ()
*/

Public static string valueof (Object OBJ ){

Return (OBJ = NULL )? "Null": obj. tostring ();
}
From the source code above, we can clearly see that there is no need to worry about null values. However, this also gives us hidden risks. We should note that when the object is null, the value of string. valueof (object) is a string "null", not null! Pay attention to it during use. Imagine if we use
If (string. valueof (object) = NULL)
{
System. Out. println ("the input value is null! ");
}
What may happen to such a statement. Think about the differences in the execution results of the following statements visually when outputting data to the console:
System. Out. println (string. valueof (null ));
System. Out. println (null );
The output we see will be exactly the same: NULL, but do they have the same meaning?
Judge whether a string is null
S is a string and the method to judge whether it is null is:
If (null = S | "". Equals (s )){
......
}
Note: null = s and "". equals (s) cannot be written as S = NULL or S. equals (s), because "" this value is already determined and predicted, and S is unknown, so when you are not careful about it, s. equals ("") causes an nullpoint exception. Although not here, because if (null = s) exists before, it does not matter if you are used to it. Some equals methods include many other processing methods. If a fixed value is used to handle the problem, there will be fewer bugs than unconfirmed processing.

Conversion Between the string and date types
Convert string to date:
String S = "10:50:50 ";
Java. Text. simpledateformat formatdate = new java. Text. simpledateformat ("yyyy-mm-dd hh: mm: SS ");
Java. util. Date = formatdate. parse (s); // convert to date

Convert date to string

String. valueof (date );

How to obtain system time in Java
Recently I have been studying Java and often encountered some minor problems at work. After Baidu, I need to find a solution to the problem and record it. Otherwise, I will use my mind, I must have forgotten it soon. Haha.
If you want to obtain the system time, do not use the date, as long as the time, But Baidu comes out with the date and time case, there is no example of time alone. After a while, find a solution to the problem.
Import java. util. date;
Import java. Text. dateformat;

Date Now = new date (); // Date () is the construction method of the Java. util. Date class.

Dateformat d = dateformat. gettimeinstance (); // gettimeinstance () obtains the system time without date.

String STR = D. Format (now );

System. Out. println ("today is" + Str); // output

Note:

1. date Now = new date (); in this sentence, date () is Java. util. the construction method of the date class, instead of Java. SQL class, so add import Java. util. date; not import Java. SQL. date; compilation errors have been caused by such low-level errors.

2. In dateformat, gettimeinstance, getdateinstance, and getdatetimeinstance are used to create a date-time format method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.