AP Computer Science AÜnite 1 · Using Objects and Methods
The Math Class and Wrapper Classes
Use static Math methods including random number generation, and the Integer and Double wrapper classes with autoboxing and unboxing.
Math class methods (static)
| Method | Returns |
|---|---|
Math.abs(x) | absolute value (int or double) |
Math.pow(a, b) | a to the power b, as a double |
Math.sqrt(x) | square root, as a double |
Math.random() | a double in [0.0, 1.0) |
Random integers
To get a random int from min to max inclusive:
int r = (int) (Math.random() * (max - min + 1)) + min;
A die roll: (int) (Math.random() * 6) + 1 gives 1 to 6.
Math.random() * 10 gives values from 0.0 up to but not including 10.0, so (int) of it is 0 to 9.
Wrapper classes
Integer and Double wrap primitive values so they can be stored in collections such as ArrayList.
- Autoboxing:
Integer n = 5;converts int to Integer automatically. - Unboxing:
int m = n;converts back. Integer.MAX_VALUEandInteger.MIN_VALUEgive the int limits.Integer.parseInt("42")converts a String to an int;Double.parseDouble("3.5")to a double.
Common pitfalls
Math.powandMath.sqrtreturn double; assigning to an int needs a cast.- Comparing two Integer objects with
==compares references; useequalsor unbox.
Quick summary
- Math methods are static and called with the class name.
- Random int in [min, max]: (int)(Math.random() * (max − min + 1)) + min.
- Autoboxing and unboxing move between int and Integer.
Konu quizi
5 soru. Geçmek için en az %80 doğru gerekiyor; geçince sonraki konu açılır.
Quizi çözüp ilerlemeni kaydetmek için giriş yap. Hesap açmak ücretsiz.
Giriş yap ve quizi çöz