Post

Created by @nathanedwards
 at November 1st 2023, 10:07:12 am.

AP Computer Science Exam Question

Explain the difference between primitive data types in Java: int and double. Then, write a Java program that demonstrates their usage by performing arithmetic operations on both types.

Answer

In Java, int and double are two different primitive data types used to store numerical values. The main difference between int and double is their precision and range.

int Data Type

The int data type is used to store whole numbers (integers) without any decimal places. It has a fixed size of 32 bits and can store values ranging from -2,147,483,648 to 2,147,483,647. This data type is commonly used for indexing arrays, counting, and storing integers in general.

double Data Type

The double data type is used to store decimal numbers (floating-point values) with a higher level of precision. It has a size of 64 bits and can store a wider range of values compared to int. It is commonly used when dealing with calculations involving fractions, percentages, or any other real numbers.

Java Program

Here is a Java program that demonstrates the usage of int and double data types by performing arithmetic operations:

public class PrimitiveTypesDemo {
    public static void main(String[] args) {
        int x = 10;
        double y = 3.5;
        
        // Addition
        double sum = x + y;
        System.out.println("Sum: " + sum);
        
        // Subtraction
        double difference = x - y;
        System.out.println("Difference: " + difference);
        
        // Multiplication
        double product = x * y;
        System.out.println("Product: " + product);
        
        // Division
        double quotient = x / y;
        System.out.println("Quotient: " + quotient);
    }
}

Explanation

  • First, we declare two variables x of type int and y of type double and assign them the initial values 10 and 3.5, respectively.
  • Using these variables, we perform the following arithmetic operations:
    • Addition: x + y. The result is stored in the variable sum of type double.
    • Subtraction: x - y. The result is stored in the variable difference of type double.
    • Multiplication: x * y. The result is stored in the variable product of type double.
    • Division: x / y. The result is stored in the variable quotient of type double.
  • Finally, we display the results using the System.out.println() method.

When we run this program, the output will be:

Sum: 13.5
Difference: 6.5
Product: 35.0
Quotient: 2.857142857142857

Note that the result of the division operation returns a decimal value due to the involvement of the double data type.