Type casting in Java

Java is a strongly typed programming language, which means that every expression and every variable has a strictly defined type already at the time of compilation. However, a casting mechanism is defined - a way to convert the value of a variable of one type to a value of another type.

There are several types of casting in Java:

  • Identity Conversion of an expression of any type to exactly the same type is always allowed and happens automatically.
  • Widening primitive. Indicates that a transition from a less capacious type to a more capacious one is taking place. For example, from byte (1 byte long) to int (4 bytes long). Such conversions are safe in the sense that the new type is always guaranteed to contain all the data that was stored in the old type, and thus no data loss occurs. This type of casting is always allowed and happens automatically.
  • Narrowing (downcasting) a primitive type (narrowing primitive). Means that the transition is made from a more capacious type to a less capacious one. With such a conversion, there is a risk of losing data. For example, if a number of type int was greater than 127, then when it is cast to byte, the values ​​of bits older than the eighth will be lost. In Java, such a conversion must be performed explicitly, while all the most significant bits that do not fit in the new type are simply discarded - no rounding or other actions are performed to obtain a more correct result.
  • Widening reference. Means an implicit bottom-up cast or transition from a more specific type to a less specific type, i.e. transition from descendant to ancestor. It is always allowed and happens automatically.
  • Narrowing reference. Indicates a downcast, that is, a cast from parent to child (subtype). This is only possible if the source variable is a subtype of the type being cast. If there is a type mismatch, a ClassCastException is thrown at run time. Requires an explicit type specification.
  • Conversion to string (to String). Any type can be cast to a string, i.e. to an instance of the String class.
  • Forbidden transformations. Not all casts between arbitrary types are allowed. For example, forbidden conversions include conversions from any reference type to primitive and vice versa (except for conversion to a string). In addition, it is impossible to bring to each other classes that are on different branches of the inheritance tree, etc.

When casting reference types, nothing happens to the object itself, only the type of the link through which the object is accessed changes.

To check the possibility of casting, you need to use the instanceof operator:

Parent parent = new Child();
if (parent instanceof Child) {
    Child child = (Child) parent;
}


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed