Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Java Type Casting in Java

Java Type Casting in Java

? Java Type Casting

Type casting in Java is the process of converting one data type into another. There are two types:


? 1. Widening Casting (Implicit Casting)

  • Also known as automatic type conversion.

  • Happens when converting a smaller type to a larger type size.

  • byte ? short ? int ? long ? float ? double

Example:

int num = 100;double d = num;  // int is automatically cast to doubleSystem.out.println(d);  // Output: 100.0

? 2. Narrowing Casting (Explicit Casting)

  • Must be done manually by the programmer.

  • Converts a larger type into a smaller size type.

  • Can lead to data loss.

Syntax:

dataType variableName = (dataType) value;

Example:

double d = 9.78;int i = (int) d;  // Explicit casting: double to intSystem.out.println(i);  // Output: 9 (decimal part is lost)

? Special Cases

a. Casting between char and int

char ch = 'A';int ascii = (int) ch;  // Output: 65int num = 66;char letter = (char) num;  // Output: 'B'

b. Casting Objects (Reference Type Casting)

There are two types:

  • Upcasting: Subclass ? Superclass (Implicit)

  • Downcasting: Superclass ? Subclass (Explicit)

Example:

class Animal {    void sound() {        System.out.println("Animal sound");    }}class Dog extends Animal {    void sound() {        System.out.println("Dog barks");    }    void fetch() {        System.out.println("Dog fetches");    }}Animal a = new Dog();  // Upcastinga.sound();             // Output: Dog barksDog d = (Dog) a;       // Downcastingd.fetch();             // Output: Dog fetches

? Summary Table

Casting TypeFrom ? ToRequires Cast?Risk of Data Loss
Wideningint ? doubleNoNo
Narrowingdouble ? intYesYes
Object UpcastSubclass ? SuperclassNoNo
Object DowncastSuperclass ? SubclassYesYes (if invalid)

Let me know if you want a cheat sheet or exercises on this topic!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql