Java Primer Series (Type Conversion)

Introduction

Hello. This article is a summary article about type conversion for "people who are starting Java from now on" and "people who are going to Java after a long time".

It does not explain programming itself, such as what variables are, so it may not be suitable for programming beginners.

Please refer to Previous Chapter for the explanation of Java variable declaration method and type.

The following articles are being prepared as an introductory Java series.

-Variables and Types --Type conversion ← Now here --Variable scope (in preparation) --String operation (in preparation) --Array operation (in preparation) --Operator (in preparation) --Conditional branch (in preparation) --Repeat processing (in preparation) --About the class (in preparation) --Abstract class (in preparation) --Interface (in preparation) --Encapsulation (in preparation) --About the module (in preparation)

What is type conversion?

You need to specify the type when declaring the variable, There are various cases where the value of that variable is converted to another type.

When performing four arithmetic operations on variables of int type Sometimes you want to convert to long type, sometimes you want to convert to double type,

Sometimes you want to attach a numeric type to a string type for display on the screen There are various things.

The term is also known as casting type conversion.

The way to specify a type conversion (cast) is to enclose the type name in ().

int a = 5;
double b = (int)a;

In addition, type conversion called promotion is performed when performing four arithmetic operations. (See below)

Basic type (primitive type) conversion

Conversion from byte type to int type and long type Conversion from int type to long type, etc.

The value is not lost when converting from small size to large size.

class Main {
  public static void main(String[] args) {
    byte a = 127;
    byte b = -128;
    int c = (int)a;
    int d = (int)b;
    System.out.println(c); // ->"127" is output
    System.out.println(d); // -> 「-128 "is output

    int e = 2147483647;
    int f = -2147483648;
    long g = (long)e;
    long h = (long)f;
    System.out.println(g); // ->"2147483647" is output
    System.out.println(h); // -> 「-2147483648 "is output
  }
}

Conversely, when converting from a large size to a small size, the ** value will be lost **.

As for how it is lost, the higher bits are lost in bit units. In the example below, it is expressed in hexadecimal for easy understanding.

class Main {
  public static void main(String[] args) {
    int a = 0x12345;
    byte b = (byte)a;
    short c = (short)a;
    System.out.printf("0x%05x\n", a); // ->"0x12345" is output
    System.out.printf("0x%05x\n", b); // ->"0x00045" is output
    System.out.printf("0x%05x\n", c); // ->"0x02345" is output
  }
}

For type conversion of decimal point types such as float and double and integer types such as int and long It's quite complicated, so I'll omit it in this article (introductory level).

Reference type (class type) conversion

When class A inherits class B You can convert from A to B and from B to A.

public class OyaClass {
  public void print() {
    System.out.println("I am OyaClass! ");
  }
}

public class ChildClass extends OyaClass {
  private String moji;
  public ChildClass(String moji) {
    this.moji = moji;
  }
  public void print() {
    System.out.println("I am ChildClass! " + moji);
  }
}

class Main {
  public static void main(String[] args) {
    ChildClass cc = new ChildClass("Yes! Yes!");
    cc.print(); // -> 「I am ChildClass! Yes! Yes!Is output

    OyaClass oc = cc;
    oc.print(); // -> 「I am ChildClass! Yes! Yes!Is output

    ChildClass cc2 = (ChildClass)oc;
    cc2.print(); // -> 「I am ChildClass! Yes! Yes!Is output

    OyaClass oc2 = new OyaClass();
    oc2.print(); // -> 「I am OyaClass!Is output

    ChildClass cc3 = (ChildClass)oc2; // ->An exception occurs.
    cc3.print();
  }
}

Even if the variable type is changed as described above, the entity (instance) will be the one created by new. When trying to type convert an entity created as the last parent class to a child class I get an exception.

Exception in thread "main" java.lang.ClassCastException:
class OyaClass cannot be cast to class ChildClass
(OyaClass and ChildClass are in unnamed module of loader 'app')
 at Main.main(Main.java:15)

Type conversion of reference type (class type) is omitted further in this chapter. More details will be provided in the "Abstract Classes" and "Interfaces" chapters.

Conversion to string

All types including null can be converted to String type. It is converted to a character string by connecting it with a character string with the + operator.

class Main {
  public static void main(String[] args) {
    int a = -100;
    double b = 123.456;
    Integer c = null;
    int d = 100;

    String sa = "" + a;
    String sb = "" + b;
    String sc = "" + c;
    String sad = "" + a + d;
    String sad2 = "" + (a + d);
    System.out.println(sa);   // -> 「-100 "is output
    System.out.println(sb);   // -> 「123.456 "is output
    System.out.println(sc);   // ->Output as "null"
    System.out.println(sad);  // -> 「-"100100" is output
    System.out.println(sad2); // ->"0" is output
  }
}

Conversion that causes an error

--Conversion from basic type to reference type (excluding string conversion) --Conversion from reference type to base type

Conversions such as will result in an error. キャストコンパイルエラー.png

Promotion (promotion)

When variables of type such as byte, short, char are subjected to four arithmetic operations (addition, subtraction, multiplication and division) After being converted to int type, four arithmetic operations (addition, subtraction, multiplication and division) are performed.

This "after being converted to int type" is called promotion.

As described below, Not only when multiplying int type and byte type variables When a byte type and a byte type variable are multiplied, it is also converted to an int type. The byte type can only enter values from -128 to 127, but values that exceed that are output.

class Main {
  public static void main(String[] args) {
    int a = 40;
    byte b = 30;
    byte c = 20;

    System.out.println(b*a); // ->"1200" is output
    System.out.println(b*c); // ->"600" is output
  }
}

So what happens if you add the following line to the end of the above program?

class Main {
  public static void main(String[] args) {
    int a = 40;
    byte b = 30;
    byte c = 20;

    System.out.println(b*a); // ->"1200" is output
    System.out.println(b*c); // ->"600" is output
    byte d = b * c;
  }
}

This will result in a compilation error. It is proof that "b * c" is converted to int type. 昇格のコンパイルエラー.png

in conclusion

The above is the explanation of type conversion, but how was it?

Probably, if you are just starting to study Java, I think that it will only be "Hey", but If you are programming Java, you will definitely encounter type conversion, so I hope you will remember it at that time.

end.

Recommended Posts

Java Primer Series (Type Conversion)
Java type conversion
[Java] Date type conversion
[Java] List type / Array type conversion
[Java] Precautions for type conversion
[Java] Type conversion speed comparison
Java Primer Series (Variables and Types)
Java date data type conversion (Date, Calendar, String)
[Easy-to-understand explanation! ] Reference type type conversion in Java
[JAVA] Stream type
[Java ~ Variable definition, type conversion ~] Study memo
[Java] Enumeration type
Java Optional type
Java study # 3 (type conversion and instruction execution)
Java double type
[Basic knowledge of Java] About type conversion
Java-automatic type conversion
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
[Introduction to Java] About type conversion (cast, promotion)
[Java] Full-width ⇔ half-width conversion
[Java] Data type ①-Basic type
Uri → String, String → Uri type conversion
Java class type field
Type determination in Java
[Java] About enum type
Endian conversion with JAVA
Java learning memo (data type)
Try functional type in Java! ①
[Java Bronze] Learning memo (interface, static method, type conversion, etc.)
Java study # 7 (branch syntax type)
[Java] Data type / matrix product (AOJ ⑧ Matrix product)
java (use class type for field)
Get stuck in a Java primer
[Java] Correct comparison of String type
[Java] Conversion from array to List
Java array / list / stream mutual conversion list
Java8 list conversion with Stream map
How to use Java enum type
Java review (2) (calculation, escape sequence, evaluation rule, type conversion, instruction execution statement)