JAVA / CHAPTER 03
Data types
BeginnerChoose primitive types and predict arithmetic and conversion results.
By the end of this chapter
- Distinguish integer and floating-point division
- Use boolean expressions
- Control numeric conversion
The idea
A variable has a declared type that limits which values and operations are valid. int represents bounded whole numbers, double represents floating-point approximations, boolean holds true or false, and char stores one UTF-16 code unit. String is a reference type rather than a primitive. Choose a type from the meaning of the data: a task count is usually integral, while an average can contain a fractional part.
Arithmetic uses operand types before an assignment occurs. Dividing two integers discards the fractional part toward zero even when the destination is double. Convert an operand before division when a fractional result is required. Parentheses make the intended grouping explicit and help reveal conversions during tracing.
public class Main {
public static void main(String[] args) {
int completed = 7;
int days = 2;
System.out.println(completed / days);
System.out.println((double) completed / days);
}
}3 3.5
The first expression uses integer division. Casting completed changes the second expression to floating-point division before it is evaluated.
Try it yourself
Compute an average from two integer counts and explain where a conversion must occur.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING