Java Type Casting
In this page:
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
public class Main {
public static void main(String[] args) {
int num = 10;
long widened = num; // automatic: no data lost
System.out.println(widened);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: