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.
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
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().
Automatic Type Promotion in Expressions:
In expressions, smaller types (byte, short, char) are automatically promoted to int.