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.
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 TypeThe 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 TypeThe 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.
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);
}
}
x
of type int
and y
of type double
and assign them the initial values 10 and 3.5, respectively.x + y
. The result is stored in the variable sum
of type double
.x - y
. The result is stored in the variable difference
of type double
.x * y
. The result is stored in the variable product
of type double
.x / y
. The result is stored in the variable quotient
of type double
.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.