杰瑞科技汇

Java与Integer、Double有哪些区别?

Of course! This is a fundamental concept in Java. Let's break down int and double in detail, covering their definitions, differences, and how to work with them.

Java与Integer、Double有哪些区别?-图1
(图片来源网络,侵删)

int - Integer

int is a data type in Java used to store whole numbers (numbers without a decimal point).

Key Characteristics of int:

  • Purpose: For counting, indexing, and any operation where you don't need fractional values.
  • Size: 32 bits (4 bytes).
  • Range: Can store values from -2,147,483,648 to 2,147,483,647 (inclusive). This is from -2³¹ to 2³¹-1.
  • Default Value: If you declare an int as an instance variable without initializing it, its default value is 0.

Example of int:

public class IntExample {
    public static void main(String[] args) {
        // Declaration and initialization
        int age = 30;
        int population = 7_900_000_000; // Using underscores for readability (Java 7+)
        int negativeNumber = -50;
        // You can perform mathematical operations
        int sum = 10 + 5;      // sum will be 15
        int difference = 10 - 5; // difference will be 5
        int product = 10 * 5;  // product will be 50
        int quotient = 10 / 3; // quotient will be 3 (decimal part is truncated!)
        System.out.println("Age: " + age);
        System.out.println("Quotient of 10 / 3: " + quotient); // Important: result is 3, not 3.33
    }
}

Important Note: When you divide two ints, Java performs integer division, which means the result is also an int and any fractional part is simply discarded (truncated).


double - Floating-Point Number

double is a data type used to store numbers with decimal points. It's called "double-precision" because it can store a much wider range of values and more decimal places than the float type.

Key Characteristics of double:

  • Purpose: For scientific calculations, financial calculations, measurements, and any operation requiring precision.
  • Size: 64 bits (8 bytes).
  • Range: Can store a very wide range of values, both positive and negative. It's approximately ±1.8 x 10³⁰⁸ with about 15-17 significant decimal digits of precision.
  • Default Value: If you declare a double as an instance variable without initializing it, its default value is 0.

Example of double:

public class DoubleExample {
    public static void main(String[] args) {
        // Declaration and initialization
        double price = 19.99;
        double pi = 3.14159;
        double scientificNotation = 6.022e23; // Represents 6.022 x 10^23 (Avogadro's number)
        double negativeDecimal = -12.5;
        // You can perform mathematical operations
        double sum = 10.5 + 5.2;      // sum will be 15.7
        double difference = 10.5 - 5.2; // difference will be 5.3
        double product = 10.5 * 2;     // product will be 21.0
        double quotient = 10.0 / 3.0;  // quotient will be approximately 3.333...
        System.out.println("Price: " + price);
        System.out.println("Quotient of 10.0 / 3.0: " + quotient);
    }
}

Key Differences at a Glance

Feature int double
Type Integer (Whole Number) Floating-Point (Number with a decimal)
Size 32 bits (4 bytes) 64 bits (8 bytes)
Range -2,147,483,648 to 2,147,483,647 ~±1.8 x 10³⁰⁸
Precision Exact whole numbers Approximate, about 15-17 significant decimal digits
Default 0 0
Example 100, -50, 0 9, -3.14, 022e23
Division 10 / 3 results in 3 (truncates) 0 / 3.0 results in 333... (keeps decimal)

Conversion and Casting (A Crucial Topic)

You often need to convert between int and double. This is where the concepts of widening and narrowing conversions come in.

Java与Integer、Double有哪些区别?-图2
(图片来源网络,侵删)

Widening Primitive Conversion (Implicit, Safe)

Converting from a smaller type (int) to a larger type (double) is automatic. The int value is simply placed inside the double container, and .0 is added if necessary. No data is lost.

int myInt = 100;
double myDouble = myInt; // This is perfectly fine and automatic
System.out.println(myDouble); // Output: 100.0

Narrowing Primitive Conversion (Explicit, Risky)

Converting from a larger type (double) to a smaller type (int) is not automatic. You must explicitly tell the compiler you want to do it using casting (int). This is risky because you will lose the decimal part of the number.

double myDouble = 9.87;
// int myInt = myDouble; // COMPILE ERROR! Incompatible types.
                        // Java protects you from potential data loss.
// You must cast it explicitly
int myInt = (int) myDouble; // The decimal part (.87) is truncated
System.out.println(myInt); // Output: 9

Rounding vs. Truncating: Casting (int) truncates (chops off) the decimal part. If you want to round to the nearest integer, you should use the Math.round() method first.

double price = 99.99;
// Truncating (casting)
int truncatedPrice = (int) price; // Becomes 99
// Rounding
long roundedPrice = Math.round(price); // Becomes 100. Note: Math.round() returns a long.
System.out.println("Truncated: " + truncatedPrice);
System.out.println("Rounded: " + roundedPrice);

The Integer and Double Wrapper Classes

For every primitive type in Java, there is a corresponding wrapper class. int has Integer, and double has Double.

Java与Integer、Double有哪些区别?-图3
(图片来源网络,侵删)

Why do we need them?

  1. Object-Oriented Programming: You can't use primitive types in collections like ArrayList or as generic types. You need their object counterparts.

    // Correct way to store numbers in an ArrayList
    ArrayList<Integer> numbers = new ArrayList<>();
    numbers.add(10); // Java automatically "autoboxes" the int 10 into an Integer object
  2. Utility Methods: The wrapper classes provide useful static methods for parsing, converting, and performing other operations.

    String strNumber = "123";
    int num = Integer.parseInt(strNumber); // Converts String to int
    String strDouble = "45.67";
    double d = Double.parseDouble(strDouble); // Converts String to double
  3. Null Values: Wrapper classes can be null, which is useful for representing the absence of a value (e.g., in databases or APIs), whereas primitives cannot.

Summary

  • Use int for counting, loop counters, and any situation where you are certain you only need whole numbers. It's memory-efficient and fast.
  • Use double for any calculation that might involve a fraction, money, scientific data, or any value that requires precision.
  • Remember that converting int to double is easy, but converting double to int requires casting and will result in the loss of the decimal part. Be careful!
分享:
扫描分享到社交APP
上一篇
下一篇