Java Type Casting

In Java, type casting is the process of converting a value from one data type to another. For example, converting an int to a double, or a double back to an int. This is necessary when different types of data interact with each other in a program.

There are two types of casting in Java: Widening Casting (automatic) and Narrowing Casting (manual).

1. Widening Casting (Implicit / Automatic)

Widening casting happens when a value is converted from a smaller data type to a larger data type. Java performs this conversion automatically because there is no risk of losing data — the larger type can hold everything the smaller type can.

Widening Order

byte → short → int → long → float → double

Each type in this chain can be automatically converted to any type that comes after it.

Example

public class WideningDemo {
    public static void main(String[] args) {
        int myInt = 100;
        double myDouble = myInt;   // automatic widening

        System.out.println("int value: " + myInt);       // 100
        System.out.println("double value: " + myDouble); // 100.0
    }
}

Output:

int value: 100
double value: 100.0

The int value 100 was automatically converted to the double value 100.0 without any loss of data.

More Widening Examples

byte b = 10;
short s = b;     // byte → short
int i = s;       // short → int
long l = i;      // int → long
float f = l;     // long → float
double d = f;    // float → double

System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("int: " + i);
System.out.println("long: " + l);
System.out.println("float: " + f);
System.out.println("double: " + d);

2. Narrowing Casting (Explicit / Manual)

Narrowing casting happens when a value is converted from a larger data type to a smaller data type. Java does not do this automatically because there is a risk of losing data (e.g., decimal parts may be cut off, or the number may not fit).

Narrowing must be done manually by placing the target type in parentheses before the value — this is called an explicit cast.

Syntax

smallerType variableName = (smallerType) largerValue;

Example

public class NarrowingDemo {
    public static void main(String[] args) {
        double myDouble = 9.78;
        int myInt = (int) myDouble;   // manual narrowing

        System.out.println("double value: " + myDouble);  // 9.78
        System.out.println("int value: " + myInt);        // 9
    }
}

Output:

double value: 9.78
int value: 9

The decimal part .78 is lost during the conversion. Java does not round the number — it simply removes everything after the decimal point (truncation).

Another Narrowing Example

long bigNumber = 1234567890123L;
int smallNumber = (int) bigNumber;
System.out.println("long: " + bigNumber);
System.out.println("int: " + smallNumber);   // Result may be unexpected due to overflow

When the long value is too large to fit in an int, the result becomes unpredictable (overflow). This is why narrowing must be done with care.

Casting Between char and int

In Java, characters (char) are stored internally as integer Unicode values. It is possible to cast between char and int.

public class CharIntCast {
    public static void main(String[] args) {
        char letter = 'A';
        int code = letter;                // widening: char to int
        System.out.println("Char: " + letter);  // A
        System.out.println("Code: " + code);    // 65

        int number = 66;
        char ch = (char) number;          // narrowing: int to char
        System.out.println("Char from 66: " + ch);  // B
    }
}

Output:

Char: A
Code: 65
Char from 66: B

Type Casting with Expressions

Type casting can be applied directly within expressions, which is common when doing arithmetic with mixed types.

public class ExpressionCast {
    public static void main(String[] args) {
        int a = 7;
        int b = 2;

        // Integer division - no decimals
        System.out.println("Integer division: " + (a / b));       // 3

        // Casting to double for accurate result
        System.out.println("Decimal division: " + ((double) a / b));  // 3.5
    }
}

Widening vs Narrowing – Summary Table

FeatureWidening CastingNarrowing Casting
DirectionSmaller → Larger typeLarger → Smaller type
Done byJava automaticallyProgrammer manually
Risk of data lossNoYes
SyntaxNo special syntax neededUse (type) before value
Exampledouble d = 5;int i = (int) 9.8;

Type Casting with Strings

Converting numbers to strings and back is a common task. Java provides built-in methods for this.

Number to String

int num = 42;
String str = String.valueOf(num);   // or Integer.toString(num)
System.out.println("String: " + str);   // "42"

String to Number

String str = "99";
int num = Integer.parseInt(str);
double d = Double.parseDouble("3.14");

System.out.println("int: " + num);   // 99
System.out.println("double: " + d);  // 3.14

Summary

  • Type casting converts a value from one data type to another.
  • Widening casting is automatic and safe — moves from smaller to larger types.
  • Narrowing casting is manual and may lose data — requires (type) syntax.
  • Characters can be cast to integers and back using their Unicode values.
  • Use Integer.parseInt() and Double.parseDouble() to convert Strings to numbers.
  • Use String.valueOf() to convert numbers to Strings.

Leave a Comment

Your email address will not be published. Required fields are marked *