Summary - Data types
- Java course
- Beginner
- Lesson 18/116
- 5 min
Combine primitives, Math and BigDecimal to write an interest calculator.
Summary - Data types
In this group you learned Java's data types:
- Primitive types: byte, short, int, long, float, double, char, boolean
- Type casting: widening (automatic), narrowing (cast)
- String concatenation:
+operator - Math class: abs, max, min, pow, PI
- BigDecimal: for precise money calculations
Now combine them and write an interest calculator.
Practice Compute with Math
Write a Main class with a main method. Assign 15 to int a and 8 to int b. Print Math.max(a, b) with println.
Sample solution
public class Main {
public static void main(String[] args) {
int a = 15;
int b = 8;
System.out.println(Math.max(a, b));
}
}Expected output
15
Tips
A few tips from this group:
- Always use
BigDecimalfor money;doublecauses rounding loss. - Remember the
Lsuffix onlong:10000000000L. charuses single quotes,Stringuses double quotes.- The
+operator works left to right; precedence matters. - Think about data loss before casting.
These basics are needed for conditionals and loops in the next groups.
Practice Compute interest with BigDecimal
Write a Main class with a main method. Add import java.math.BigDecimal; at the top. Assign BigDecimal.valueOf(1000) to BigDecimal principal and BigDecimal.valueOf(0.05) to BigDecimal rate. Print principal.multiply(rate) with println.
Starter code
import java.math.BigDecimal;
public class Main {
}Sample solution
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal principal = BigDecimal.valueOf(1000);
BigDecimal rate = BigDecimal.valueOf(0.05);
System.out.println(principal.multiply(rate));
}
}Expected output
50.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the types
| Term | Meaning |
|---|---|
int |
Integer |
double |
Decimal |
char |
Character |
BigDecimal |
Precise |
2 Cast to convert
int whole = ____ 9.99;
int whole = (int) 9.99;
Explanation: (int) cast does narrowing conversion.