Java-automatic type conversion

Java-automatic type conversion

About type conversion

System.out.println("Mr. Naito"+26+"I'm old")

//console
Naito is 26 years old

Operations such as "+" must be of the same data type When operating on different types, convert the types to the same type

In Java, this type conversion method includes automatic conversion and manual conversion. If you add String type and int type The int type is automatically converted to the String type and the strings are combined.

Precautions for calculating numerical values

System.out.println(5/2);  //Calculation between int types
System.out.println(5.0/2.0);  //Calculation between double types

//console
2 int type
2.5 double type

Precautions for numerical calculation Calculation between int types will result in int type Calculation between double types will result in double type

Dividing 5 of int type by 2 of int type Note that the result is "2" instead of "2.5"

Automatic type conversion at the time of calculation

System.out.println(5.0/2);
                   5.0/2.0  //Convert to double type

//console
2.5 double type

Int and double type calculations result in double type Because int type is converted to double type in the process of calculation Therefore, the result of "5 / 2.0" or "5.0/2" is 2.5.

Because integers can always be represented as decimals, like 5 to 5.0 Java automatically performs type conversion

Recommended Posts

Java-automatic type conversion
Java type conversion
Uri → String, String → Uri type conversion
[Java] Date type conversion
[Java] List type / Array type conversion
[Java] Type conversion speed comparison
Java Primer Series (Type Conversion)
[Easy-to-understand explanation! ] Reference type type conversion in Java
[Java ~ Variable definition, type conversion ~] Study memo
Pass type
Java-forced conversion
[Basic knowledge of Java] About type conversion
Example of using ArAutoValueConverter (field type conversion)
Directory type
Java 8 LocalDateTime type conversion stuff (String, java.util.Date)
[Java] Calculation mechanism, operators and type conversion
Type conversion from java BigDecimal type to String type
Human type
Register request parameter type conversion with SpringBoot + MVC
[Introduction to Java] About type conversion (cast, promotion)
Java type conversion (String, int, Date, Calendar, etc.)