← Back to Core Java Course | Chapter 14: Advanced Topics | Lesson 2 of 6

Java Type Casting

Widening Casting

Widening casting converts a smaller numeric type to a larger one automatically (like int to long), since no data can be lost in the conversion. Common examples include byte to short, int to long, and float to double, all of which Java performs implicitly without any special syntax.

Example: Widening Casting

java
public class Main {
	public static void main(String[] args) {
		int num = 10;
		long widened = num; // automatic: no data lost
		System.out.println(widened);
	}
}

Narrowing Casting

Narrowing casting converts a larger numeric type to a smaller one and requires an explicit cast, since data loss (like truncating a double's decimal portion) is possible. The compiler forces the explicit cast precisely because it wants the developer to consciously acknowledge that some precision could be lost.

Example: Narrowing Casting

java
public class Main {
	public static void main(String[] args) {
		double d = 9.78;
		int narrowed = (int) d; // explicit cast required: decimal truncated
		System.out.println(narrowed);
	}
}

Reference Upcasting

Upcasting treats a subclass reference as its superclass type, which happens implicitly and safely since every subclass instance genuinely is an instance of its supertype too. This is the foundation of polymorphism in Java, letting code work generically with a superclass type while still holding any of its subclasses.

Example: Reference Upcasting

java
class Animal {}
class Dog extends Animal {}
public class Main {
	public static void main(String[] args) {
		Dog dog = new Dog();
		Animal a = dog; // implicit and safe
		System.out.println(a instanceof Dog);
	}
}

Reference Downcasting

Downcasting treats a superclass reference as a more specific subclass type, requiring an explicit cast and risking a ClassCastException at runtime if the object isn't actually an instance of that subclass.

Example: Reference Downcasting

java
class Animal {}
class Dog extends Animal {}
public class Main {
	public static void main(String[] args) {
		Animal a = new Dog();
		Dog dog = (Dog) a; // explicit, risks ClassCastException
		System.out.println(dog);
	}
}

Converting Types to Strings

Converting any value to a String is usually done with String.valueOf() or simple concatenation ("" + value), both of which call the value's own string representation logic under the hood.

Example: Converting Types to Strings

java
public class Main {
	public static void main(String[] args) {
		int num = 42;
		String s1 = String.valueOf(num);
		String s2 = "" + num;
		System.out.println(s1 + " " + s2);
	}
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.