杰瑞科技汇

Java中short与long类型有何区别?

Of course! In Java, short and long are primitive data types used to represent integer numbers. They are part of the family of integer types, which also includes byte, int, and char.

Java中short与long类型有何区别?-图1
(图片来源网络,侵删)

Here's a detailed breakdown of each, followed by a comparison.


short Data Type

The short data type is a 16-bit signed two's complement integer. This is the key information to understand its behavior.

Key Characteristics of short:

  1. Size: 16 bits (2 bytes).
  2. Range: Because it's a signed integer, one bit is reserved for the sign (positive or negative).
    • Minimum value: -32,768 (-2¹⁵)
    • Maximum value: 32,767 (2¹⁵ - 1)
  3. Default Value: 0
  4. Memory Usage: It uses less memory than an int (which is 32 bits). However, due to modern computer architecture, using a short is often not more memory-efficient than an int because operations on int are typically faster. The JVM usually handles int natively.
  5. Use Case: It's very rarely used in modern Java development. Its primary purpose is for memory conservation in very large arrays where you know the values will always fit within the short range (e.g., representing pixel values in an image).

Example of short:

public class ShortExample {
    public static void main(String[] args) {
        // Declare and initialize a short variable
        short smallNumber = 15000;
        System.out.println("smallNumber: " + smallNumber);
        System.out.println("Size in bits: " + Short.SIZE); // Prints 16
        System.out.println("Min value: " + Short.MIN_VALUE); // Prints -32768
        System.out.println("Max value: " + Short.MAX_VALUE); // Prints 32767
    }
}

Important Casting Note for short:

You cannot assign an int literal to a short variable without an explicit cast, because Java assumes all integer literals are int by default, and this could lead to data loss.

// This will cause a COMPILE-TIME ERROR
// short myShort = 100000; // 100000 is outside the short range
// This is also a COMPILE-TIME ERROR
// int anotherInt = 50;
// short myShort = anotherInt; // Incompatible types: possible lossy conversion
// The correct way is to use an explicit cast
short myShort = (short) 100000; // The value 100000 is truncated to fit into a short
System.out.println(myShort); // Output will be -31072 (because 100000 % 32768 = 31072, and it overflows the positive range)

long Data Type

The long data type is a 64-bit signed two's complement integer. It's used when you need to represent numbers larger than what an int can hold.

Java中short与long类型有何区别?-图2
(图片来源网络,侵删)

Key Characteristics of long:

  1. Size: 64 bits (8 bytes).
  2. Range: A much wider range than int or short.
    • Minimum value: -9,223,372,036,854,775,808 (-2⁶³)
    • Maximum value: 9,223,372,036,854,775,807 (2⁶³ - 1)
  3. Default Value: 0L (The L suffix is important).
  4. Use Case: Essential for large numbers, such as:
    • Timestamps (e.g., milliseconds since the epoch).
    • File sizes.
    • Unique identifiers (e.g., database IDs).
    • Financial calculations involving very large sums.

Example of long:

public class LongExample {
    public static void main(String[] args) {
        // Declare and initialize a long variable
        // IMPORTANT: Use the 'L' or 'l' suffix for long literals. 'L' is preferred.
        long bigNumber = 1234567890123L;
        System.out.println("bigNumber: " + bigNumber);
        System.out.println("Size in bits: " + Long.SIZE); // Prints 64
        System.out.println("Min value: " + Long.MIN_VALUE);
        System.out.println("Max value: " + Long.MAX_VALUE);
    }
}

Important Casting Note for long:

You cannot assign a long value to an int variable without an explicit cast, because the long value might be too large to fit into an int.

long myLong = 100L;
// int myInt = myLong; // COMPILE-TIME ERROR: Incompatible types
// The correct way is to cast
int myInt = (int) myLong;
System.out.println(myInt); // Output: 100
// Example of overflow
long bigLong = Long.MAX_VALUE;
int smallInt = (int) bigLong;
System.out.println(smallInt); // Output will be a negative number (-1) due to truncation

Comparison: short vs. long

Feature short long
Size 16 bits (2 bytes) 64 bits (8 bytes)
Purpose To save memory for small integer values. To hold very large integer values.
Range -32,768 to 32,767 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Default Value 0 0L
Literal Suffix No suffix needed (e.g., 10) L or l suffix is required (e.g., 10L)
Common Use Rarely used. Niche applications like arrays of small numbers. Very common. For timestamps, IDs, large counters, etc.
Performance Operations can be slower than int. Operations are generally fast on modern 64-bit systems.

Summary and Best Practices

  • Use int by default. For most integer needs in Java, int is the right choice. It offers a good balance of range and performance.
  • Use long when you need a bigger range. If you know your number will exceed the int limit (approx. 2.1 billion), use long. Always remember the L suffix for literals.
  • Avoid short unless you have a specific reason. The memory savings are often negligible, and it can lead to more complex code due to frequent casting. It's mostly a legacy type from when memory was extremely constrained.

When to Use Which?

  • Use int for:

    • Loop counters (for (int i = 0; ...)).
    • Array indices.
    • General-purpose integer calculations.
  • Use long for:

    • Any number that might exceed Integer.MAX_VALUE.
    • System.currentTimeMillis() returns a long.
    • Representing IDs in a database that are likely to grow large.
  • Use short for:

    Java中short与long类型有何区别?-图3
    (图片来源网络,侵删)
    • Storing a large number of small values in an array to save memory (e.g., short[] pixelData = new short[width * height];).
分享:
扫描分享到社交APP
上一篇
下一篇