Casting is a way to convert a variable from one data type to another. In Java, there are two types of casting: implicit and explicit.
int
to a long
.Converting refers to changing the representation of an object or value from one form to another. It can involve converting between different data types, formats, or structures. For example, converting a String
to an int
using Integer.parseInt()
, or converting a Date
object to a String
using a SimpleDateFormat
.
Animal
objects that also contains Dog
objects, you may need to cast an Animal
object to a Dog
object to access Dog
- specific methods.double
to an int
.int
or a double
.// Implicit Casting (Widening Conversion)
int numInt = 10;
long numLong = numInt; // Implicitly convert int to long
System.out.println("Implicit Casting: " + numLong);
// Explicit Casting (Narrowing Conversion)
double numDouble = 10.5;
int numInt2 = (int) numDouble; // Explicitly convert double to int
System.out.println("Explicit Casting: " + numInt2);
// Casting in Object Hierarchy
class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
public void fetch() {
System.out.println("Fetching...");
}
}
public class CastingExample {
public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound();
// Cast Animal to Dog
Dog dog = (Dog) animal;
dog.fetch();
}
}
// Converting String to int
String strNumber = "123";
int intNumber = Integer.parseInt(strNumber);
System.out.println("Converted String to int: " + intNumber);
// Converting Date to String
import java.text.SimpleDateFormat;
import java.util.Date;
public class ConvertingExample {
public static void main(String[] args) {
Date currentDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy - MM - dd");
String dateString = sdf.format(currentDate);
System.out.println("Converted Date to String: " + dateString);
}
}
ClassCastException
is thrown. For example, trying to cast an Animal
object that is actually a Cat
to a Dog
.double
with a decimal part to an int
will truncate the decimal part.Integer.parseInt()
, a NumberFormatException
is thrown if the string does not represent a valid number.ParseException
or incorrect output.instanceof
: Before casting an object, use the instanceof
operator to check if the object is of the target type. This helps prevent ClassCastException
.Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.fetch();
}
Integer.parseInt()
or SimpleDateFormat.parse()
, use try - catch blocks to handle exceptions gracefully.String strNumber = "abc";
try {
int intNumber = Integer.parseInt(strNumber);
System.out.println(intNumber);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + e.getMessage());
}
In Java, casting and converting are essential operations with distinct purposes. Casting is mainly used for type conversions within the same data type system, such as between primitive types or in the object hierarchy. Converting, on the other hand, is used to change the representation of data between different types, formats, or structures. By understanding the core concepts, typical usage scenarios, common pitfalls, and best practices of casting and converting, developers can write more robust and efficient Java code.
A: Casting is about changing the type of a variable within the same data type system, either implicitly or explicitly. Converting is about changing the representation of data between different types, formats, or structures.
A: Use casting when you need to convert between compatible data types, such as different primitive types or objects in an inheritance hierarchy. Use converting when you need to change the format or type of data, like converting a string to a number or a date to a string.
ClassCastException
?A: Use the instanceof
operator to check if an object is of the target type before casting it.