AP Computer Science A

Should I Use "int" or "double"?

2 min readjuly 11, 2024

Milo Chang

Milo Chang

Milo Chang

Milo Chang

🌄 Check out these other AP Computer Science A Resources: 

What's the Difference Between "int" and "double"? 🤷‍♂️

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. 

Why Does This Matter?

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. 

Summary: 🎉 ✨ 😎

  • Once you know what type of numbers you will get from your code (integers or decimals), you will know what type of variable to use.
  • Comparing doubles is tricky, so be careful! 🔎
  • Want to learn more about APCSA, check out this blog on the myths of AP Computer Science
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.