slug
type
status
category
summary
date
tags
password
icon
Casting in Java
Casting in Java is used to convert a variable from one data type to another. There are two types of casting: implicit casting (automatic type conversion) and explicit casting (manual type conversion).
- Implicit Casting (Widening Conversion):
- Happens automatically when converting a smaller data type to a larger data type.
- No data loss occurs.
- Example:
- Explicit Casting (Narrowing Conversion):
- Must be done manually.
- There can be data loss.
- Example:
Ranges of Variables
Different data types in Java have different ranges, based on the number of bits used to store them. Here are the ranges for some common primitive data types:
- byte:
- Size: 8 bits
- Range: -128 to 127
- Example:
- short:
- Size: 16 bits
- Range: -32,768 to 32,767
- Example:
- int:
- Size: 32 bits
- Range: -2^31 to 2^31-1 (approximately -2.1 billion to 2.1 billion)
- Example:
- long:
- Size: 64 bits
- Range: -2^63 to 2^63-1 (approximately -9.2 quintillion to 9.2 quintillion)
- Example:
- float:
- Size: 32 bits
- Range: Approximately ±3.40282347E+38F (6-7 significant decimal digits)
- Example:
- double:
- Size: 64 bits
- Range: Approximately ±1.79769313486231570E+308 (15 significant decimal digits)
- Example:
- char:
- Size: 16 bits
- Range: 0 to 65,535 (unsigned)
- Example:
- boolean:
- Size: Not precisely defined; typically 1 bit
- Values: true or false
- Example:
Example: Combining Casting and Range
When working with different data types, it’s crucial to be aware of their ranges and ensure that the casting does not lead to unexpected results due to range overflow or truncation.
In this example,
intVal
is cast to a byte
, which causes overflow because the byte
range is only -128 to 127. Therefore, the output for byteVal
is -128, demonstrating the importance of understanding variable ranges when casting.- 作者:现代数学启蒙
- 链接:https://www.math1234567.com/article/casting
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章