November 12, 2020 Summarize the toString method for converting numbers to strings.
Used to convert numeric type to String type. Specify the argument to be converted to a String type character string in the argument, and return the String type character string as the return value.
Convert a number to a string
public class Main {
pubic static void main(String[] args) {
int num1 = 1234;
int num2 = 5678;
System.out.println(num1 + num2);
//Convert a number to a string
String str1 = Integer.toString(num1);
String str2 = Integer.toString(num2);
System.out.println(str1 + str2);
}
}
Execution result
6912
12345678
In order to use the toString method in your own class, you need to override it. Add @Override
to override.
Override the toString method in your own class
class Age {
int age = 21;
@Override
public String toString() {
return "age =" + age;
}
}
public static Main() {
public static void main(String89 args) {
Age age = new age();
String str = profile.toString();
System.out.println(str);
}
}
Execution result
age = 22
The toString method is defined in the java.lang.Object class, so you can use it in any class. Therefore, the toString method may be used unknowingly.
python
import java.util.HashMap;
public class Main{
public static void main(String[] args){
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println(map);
}
}
Execution result
{key1=value1, key2=value2, key3=value3}
In this code, the object of java.util.HashMap is specified in the argument of System.out.println ()
at the end, and the code confirms the elements in the object. If a reference type other than java.lang.String is specified as an argument, it will be the same as writing System.out.println (map.toString ());
, and the object's toString ( The character string is output by the) method.
[Introduction to Java] Converting numbers to strings with toString (explaining overrides) Useful usage of [Java] toString () method
Recommended Posts