Type Conversion
Introduction to Type Conversion
Type conversion, also known as type casting, is the process of converting a value from one data type to another in Java.
Types of Type Conversion
graph TD
A[Type Conversion] --> B[Implicit Conversion]
A --> C[Explicit Conversion]
Implicit (Widening) Conversion
Source Type |
Target Type |
Conversion Type |
byte |
short, int, long, float, double |
Automatic |
short |
int, long, float, double |
Automatic |
char |
int, long, float, double |
Automatic |
int |
long, float, double |
Automatic |
long |
float, double |
Automatic |
float |
double |
Automatic |
Explicit (Narrowing) Conversion
Source Type |
Target Type |
Conversion Method |
double |
float, long, int, short, char, byte |
Casting |
float |
long, int, short, char, byte |
Casting |
long |
int, short, char, byte |
Casting |
int |
short, char, byte |
Casting |
Code Example: Implicit Conversion
public class ImplicitConversionDemo {
public static void main(String[] args) {
// Implicit conversion from int to long
int intValue = 100;
long longValue = intValue;
// Implicit conversion from int to double
int number = 500;
double doubleNumber = number;
System.out.println("Int to Long: " + longValue);
System.out.println("Int to Double: " + doubleNumber);
}
}
Code Example: Explicit Conversion
public class ExplicitConversionDemo {
public static void main(String[] args) {
// Explicit conversion from double to int
double doubleValue = 3.14;
int intValue = (int) doubleValue;
// Explicit conversion from long to int
long longValue = 1000000L;
int truncatedInt = (int) longValue;
System.out.println("Double to Int: " + intValue);
System.out.println("Long to Int: " + truncatedInt);
}
}
Conversion Between Primitives and Strings
public class StringConversionDemo {
public static void main(String[] args) {
// Primitive to String
int number = 42;
String stringNumber = String.valueOf(number);
// String to Primitive
String textValue = "123";
int parsedNumber = Integer.parseInt(textValue);
System.out.println("Primitive to String: " + stringNumber);
System.out.println("String to Primitive: " + parsedNumber);
}
}
Potential Conversion Risks
graph TD
A[Conversion Risks] --> B[Data Loss]
A --> C[Overflow]
A --> D[Precision Reduction]
Best Practices
- Be aware of potential data loss
- Use appropriate casting methods
- Check value ranges before conversion
- Handle potential exceptions
Common Conversion Methods
Integer.parseInt()
Double.parseDouble()
String.valueOf()
- Explicit casting operators
Learning with LabEx
Practice type conversion techniques in LabEx's interactive Java programming environment to gain practical experience and understanding.