[Introduction to Java] About type conversion (cast, promotion)

Purpose

For those who have just started learning programming including the Java language, and those who have already learned it, for review I am writing to learn type conversion.

Last time, I learned about Variables and Types. This time about ** type conversion **.

[Introduction to Java Table of Contents] -Variables and types ・ Type conversion ← Now here -Variable Scope -String operation -Array operationOperator ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) -Exception handlingAbout lambda expressionAbout Stream API

Type conversion

It is to convert the data type. Here's how to do it.

-Implicit type conversion ・ Type conversion by casting

Let's look at each one.

Implicit type conversion

It is possible to substitute a small type for a large type. Even if we programmers do not explicitly convert the type, it will convert the type at compile time.

Substitution from the left type to the right type is OK! byte → short、char → int → long → float → double

Main.java


class Main {
  public static void main(String args[]) {
    int number = 10;

    //int type number becomes float type
    float numberFloat = number;

    System.out.println(numberFloat); // 10.0 ← with a decimal point
  }
}

** Please note that implicit type conversion is not possible for the following. ** ** ・ When changing char type to short type ・ When changing short type to char type Both are 16-bit data types, but the range of values that can be handled is different. You must perform type conversion by casting as described below.

Main.java


class Main {
  public static void main(String args[]) {
    //・ Char → short
    char a = 100;
    //I get an error
    // short b = a; // Type mismatch: cannot convert from char to short
    
    short b = (short) a; //Converting to short type by type conversion by cast
    System.out.println(b); // 100

    

    //・ Short → char
    short c = 100;
    //I get an error
    // char d = c; // Type mismatch: cannot convert from short to char
    
    char d = (char) c; //Converting to char type by type conversion by cast
    System.out.println(d); // d
  }
}

-It is impossible to substitute a large type for a small type. A compile error occurs. Substitution from the right type to the left type is NG! byte → short、char → int → long → float → double

Main.java


class Main {
  public static void main(String args[]) {
    int numberInt = 10;

    //You cannot assign from a large type to a small type.
    byte numberByte = numberInt; // Type mismatch: cannot convert from int to byte

    System.out.println(numberByte);
  }
}

Also, please note that there is a risk that the accuracy will drop due to the following type conversions **.

Main.java


class Main {
  public static void main(String args[]) {
    //Define a variable with the maximum value of each type
    int intMax = Integer.MAX_VALUE;
    long longMax = Long.MAX_VALUE;
    float floatMax = Float.MAX_VALUE;

    //The number of effective digits of the float type is 7 decimal digits.(24 digits in binary)
    
    // int → float
    float floatFromIntMax = intMax;
    System.out.println(intMax); // 2147483647
    //↓ Values after 7 effective digits are lost (results different from those before type conversion are output)
    System.out.println(floatFromIntMax); // 2.14748365E9

    // long → float
    float floatFromLongMax = longMax;
    System.out.println(longMax); // 9223372036854775807
    //↓ Values after 7 effective digits are lost (results different from those before type conversion are output)
    System.out.println(floatFromLongMax); // 9.223372E18


    //The number of effective digits in double type is approximately 15 decimal digits.(53 digits in binary)

    // long → double
    double doubleFromLongMax = longMax;
    System.out.println(longMax); // 9223372036854775807
    //↓ Values after 15 effective digits are lost (results different from those before type conversion are output)
    System.out.println(doubleFromLongMax); // 9.223372036854776E18

    // float → double
    double doubleFromFloatMax = floatMax;
    System.out.println(floatMax); // 3.4028235E38
    //↓ Values after 15 effective digits are lost (results different from those before type conversion are output)
    System.out.println(doubleFromFloatMax); // 3.4028234663852886E38

  }
}

Type conversion by cast

You cannot assign from a large type to a small type. Explicitly perform type conversion using ** () ** cast operator.

Main.java


class Main {
  public static void main(String args[]) {
    double numberDouble = 3.14;

    //You cannot assign from a large type to a small type.
    // int numberInt = numberDobule; // Type mismatch: cannot convert from double to int

    //Forcibly converted to int type using cast operator
    int numberInt = (int)number; 
    System.out.println(numberInt); //Is output as 3
  }
}

Please note that some patterns cannot be converted. Strings cannot be converted to int types using the cast operator.

Main.java


class Main {
  public static void main(String args[]) {
    //Examples that cannot be converted
    String str = "Good morning";
    int num = (int)str; // Cannot cast from String to int
    System.out.println(str);
  }
}

** Notes on casting **

Please note that some data will be lost due to type conversion by casting.

-When the type is converted from a large size to a small size, the value of the high-order bit is truncated (data overflow).

Main.java


class Main {
  public static void main(String args[]) {
    short x = 257; //16 bit-> 0000 0001 0000 0001
    byte y = (byte)x; //8 bits-> 0000 0001
    System.out.println(y); //Is output as 1
  }
}

-When converting from a decimal to an integer, the decimal point is truncated.

Main.java


class Main {
  public static void main(String args[]) {
    //Also, when converting from a decimal to an integer, the decimal point is truncated.
    double d = 10.23;
    int i = (int)d;
    System.out.println(i); //Is output as 10

    float f = 33.44f;
    int i2 = (int)f;
    System.out.println(i2); //33 is output
  }
}

Promotion (promotion)

Java may automatically perform type conversions not intended by the programmer. This is explained below.

If one of the operands (operation target) is long type and the other operand is not float type or double type, the other operand will be converted to long type.

Main.java


class Main {
  public static void main(String args[]) {
    int a = 1;
    long b = 2;

    //Variable a is converted to long type before operation
    int c = a + b; // Type mismatch: cannot convert from long to int
  }
}

↓ ** Solution **

Main.java


class Main {
  public static void main(String args[]) {
    int a = 1;
    long b = 2;

    int c = (int)(a + b); //The error disappears by casting the operation result to int type.
    System.out.println(c); // 3
  }
}

If one of the operands (operation target) is of float type and the other operand is not of double type, the other operand will be converted to float type.

Main.java


class Main {
  public static void main(String args[]) {
    int a = 1;
    float b = 2.0f;

    //Variable a is converted to float type before operation
    int c = a + b; // Type mismatch: cannot convert from float to int
  }
}

↓ ** Solution **

Main.java


class Main {
  public static void main(String args[]) {
    int a = 1;
    float b = 2.0f;

    int c = (int)(a + b); //The error disappears by casting the operation result to int type.
    System.out.println(c); // 3
  }
}

If one of the operands (operation target) is of double type, the other operand will be converted to double type.

Main.java


class Main {
  public static void main(String args[]) {
    int a = 1;
    double b = 2.0;

    //Variable a is converted to double type before operation
    int c = a + b; // Type mismatch: cannot convert from double to int
  }
}

↓ ** Solution **

Main.java


class Main {
  public static void main(String args[]) {
    int a = 1;
    double b = 2.0;

    int c = (int)(a + b); //The error disappears by casting the operation result to int type.
    System.out.println(c); // 3
  }
}

If the operand (operation target) is neither long type, float type, nor double type, both operands will be converted to int type.

Main.java


class Main {
  public static void main(String args[]) {
    byte a = 1;
    byte b = 2;

    //Variable a before operation,b is converted to int type
    byte c = a + b; // Type mismatch: cannot convert from int to byte
  }
}

↓ ** Solution **

Main.java


class Main {
  public static void main(String args[]) {
    byte a = 1;
    byte b = 2;

    byte c = (byte)(a + b); //The error disappears by casting the operation result to byte type.
    System.out.println(c); // 3
  }
}

I think that promotion (promotion) may lead to unintended results and errors. You have to be careful about the numerical promotion at the time of calculation.

At the end

I learned about type conversion. Next time, I will delve into Variable Scope.

Recommended Posts

[Introduction to Java] About type conversion (cast, promotion)
[Introduction to Java] About lambda expressions
[Introduction to Java] About Stream API
[Java] Introduction to Java
Introduction to java
[Basic knowledge of Java] About type conversion
Type conversion from java BigDecimal type to String type
[Java] About enum type
Introduction to java command
[Java] char type can be cast to int type
[Java] Date type conversion
Java variable declaration, initialization, data type (cast and promotion)
[Java] Things to note about type inference extended in Java 10
[Java] List type / Array type conversion
[Java] Precautions for type conversion
[Java] Type conversion speed comparison
[Java] Introduction to lambda expressions
[Java] Introduction to Stream API
Java Primer Series (Type Conversion)
[Introduction to rock-paper-scissors games] Java
Introduction to Functional Programming (Java, Javascript)
Initial introduction to Mac (Java engineer)
[Java] Conversion from array to List
How to use Java enum type
[Introduction to Java] Variables and types (variable declaration, initialization, data type)
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
[Java Siler] About type inference by var
[Java] Implicit type cast (AOJ10-sum of numbers)
Java date data type conversion (Date, Calendar, String)
Introduction to java for the first time # 2
[Java ~ Variable definition, type conversion ~] Study memo
About the procedure for java to work
Java study # 3 (type conversion and instruction execution)
Introduction to algorithms with java --Search (depth-first search)
How to do base conversion in Java
[Introduction to Java] How to write a Java program
[Java] Convert Object type null to String type
[Introduction to Java] About array operations (1D array, 2D array declaration, instantiation, initialization and use)
Output of the book "Introduction to Java"
[Java] Introduction
Introduction to monitoring from Java Touching Prometheus
[Introduction to Java] Variable declarations and types
Introduction to kotlin for iOS developers ④-Type
Java 8 LocalDateTime type conversion stuff (String, java.util.Date)
[Java] Calculation mechanism, operators and type conversion
[Introduction to Java] About iterative processing (while, do-while, for, extension for, break, continue)
Introduction to Java Web Apps Performance Troubleshooting
Introduction to algorithms with java --Search (breadth-first search)
Introduction to algorithms with java --Search (bit full search)
Road to Java Engineer Part1 Introduction & Environment Construction
About var used in Java (Local Variable Type)
[Monthly 2017/04] Introduction to groovy !! ~ Java grammar / specification comparison ~
A story about trying to operate JAVA File
Introduction to kotlin for iOS developers ③-About gradle
[Note] About the introduction to Swift practice Chapter 11
Java type conversion (String, int, Date, Calendar, etc.)
An introduction to Groovy for tedious Java engineers
[Introduction to Java] Basics of java arithmetic (for beginners)
Introduction to Ruby 2
About Java interface
[Java] About Java 12 features