Casting and Ranges of Variables
Casting and Ranges of Variables
Casting Variables
- Casting refers to the process of converting a variable from one data type to another.
- In Java, casting is achieved using the cast operator (round brackets), which is followed by the data type you want to convert to. Example: double myDouble = (double) myInt;
- Variables can be cast into types that use less memory, such as converting a double to an int. This is known as downcasting.
- Be mindful when downcasting, as it can lead to data loss if the original value has a higher precision than the new type can accommodate.
- Variables can also be cast into types that use more memory or offer more precision, such as converting an int to a double. This is known as upcasting.
- Upcasting is safer as it doesn’t lead to data loss, but it does use more memory.
Ranges of Variables
- Each primitive data type in Java has a specific range of values that it can store.
- The range is determined by the number of bits allocated for that type and how those bits are interpreted.
- The data type byte has a range from -128 to 127.
- The short data type range is from -32,768 to 32,767.
- The int data type range is from -2,147,483,648 to 2,147,483,647.
- The long data type range is from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
- For float and double data types, the range is much larger but they vary in precision.
- Float can hold 6-7 decimal digits while double can hold up to 15 decimal digits.
- The char type’s range is usually from 0 to 65,535, encompassing the Unicode character set.
- The boolean type has only two possible values: true or false.