Advertisement
Google Ad Slot: content-top
Java Type Conversion
In Java, type conversion refers to converting data from one type to another.
Implicit Type Conversion (Widening or Automatic Type Casting):
- The conversion happens automatically when a smaller data type is converted to a larger data type.
- Example:
inttolong.
Example
int num = 10;
long longNum = num; // int to long (widening)
float floatNum = num; // int to float (widening)
Explicit Type Conversion (Narrowing)
- Must be specified explicitly using a cast operator.
- Converts data from a larger size to a smaller size, which might result in data loss.
- Syntax:
(targetType) value
Example
double num = 10.5;
int intNum = (int) num; // double to int (narrowing)
int aa=600;
byte byteNum=(byte)aa;
Type Conversion Between Strings and Primitives:
- Primitive to String: Use
String.valueOf()or concatenation. - String to Primitive: Use wrapper classes like
Integer.parseInt()orDouble.parseDouble().
Example
int num = 10;
String str = String.valueOf(num); // "10"
String str2 = "25";
int num2 = Integer.parseInt(str2); // 25
Automatic Type Promotion in Expressions:
In expressions, smaller types (byte, short, char) are automatically promoted to int.
Example
byte a = 10;
byte b = 20;
int result = a + b; // Automatically promoted to int
System.out.println("Result: " + result);