AP Computer Science A
2 min read•Last Updated on July 11, 2024
Milo Chang
Milo Chang
🌄 Check out these other AP Computer Science A Resources:
An int is an integer, which you might remember from math is a whole number. A double is a number with a decimal. The number 1 is an integer while the number 1.0 is a double.
Sometimes, you're trying to write code where you need to use a double instead of an int for the correct output, or vice versa. Whether you use integers or doubles depends on the problem. For example, if you are calculating something with GPA or money, you probably need to use a double because of the decimals involved in these calculations.
You might get the wrong answer if you don't use the correct type: 😱
int a = 2/3; System.out.println(a); // This prints 0
Check out this resource covering how to read Java Code!
The code above would print 0 because a is an integer value, meaning the computer cuts off every number after the decimal(truncates), so a is 0 instead of 0.666667.
Comparing doubles is a lot trickier than comparing integers, so if you're going to be comparing a lot of numbers, you might need to use integers.
double a = 2/3; double b = 0.6667; System.out.println(a==b); // This prints "false"
In the example above, the computer would print "false" because the value of a would be 0.66666666666666...7 while the value of b is simply 0.6667. This is the problem with comparing doubles, since if there is even one decimal difference between two doubles, they will not be equal.