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).
  1. Implicit Casting (Widening Conversion):
      • Happens automatically when converting a smaller data type to a larger data type.
      • No data loss occurs.
      • Example:
    1. 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:
      1. byte:
          • Size: 8 bits
          • Range: -128 to 127
          • Example:
        1. short:
            • Size: 16 bits
            • Range: -32,768 to 32,767
            • Example:
          1. int:
              • Size: 32 bits
              • Range: -2^31 to 2^31-1 (approximately -2.1 billion to 2.1 billion)
              • Example:
            1. long:
                • Size: 64 bits
                • Range: -2^63 to 2^63-1 (approximately -9.2 quintillion to 9.2 quintillion)
                • Example:
              1. float:
                  • Size: 32 bits
                  • Range: Approximately ±3.40282347E+38F (6-7 significant decimal digits)
                  • Example:
                1. double:
                    • Size: 64 bits
                    • Range: Approximately ±1.79769313486231570E+308 (15 significant decimal digits)
                    • Example:
                  1. char:
                      • Size: 16 bits
                      • Range: 0 to 65,535 (unsigned)
                      • Example:
                    1. 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.
                       
                       
                       
                      数字化工具在日常教学中的应用What is e in mathematics?
                      Loading...