Math Class
1. What Is Math? (beginner)
Math = static toolbox (no new! all methods static). Constants PI, E + functions: power, root, round, random, max/min. java.lang (no import!).
System.out.println(Math.PI); // 3.141592653589793
System.out.println(Math.pow(2, 10)); // 1024.0 (double! cast to int!)
System.out.println(Math.sqrt(16)); // 4.0
System.out.println(Math.abs(-5)); // 5
System.out.println(Math.max(10, 20)); // 20
System.out.println(Math.min(10, 20)); // 10
System.out.println(Math.round(3.6)); // 4 (long!)
System.out.println(Math.ceil(3.1)); // 4.0 (up!)
System.out.println(Math.floor(3.9)); // 3.0 (down!)
System.out.println((int)(Math.random() * 100)); // 0-99 random! (classic!)
4. Traps
Mathconstructor private:new Math()ERROR (useMath.sqrt, not object!).powreturns double:int p = Math.pow(2,10);ERROR — need(int).round(3.6)returns long (not int!).random()gives0.0to0.999...(never 1.0!) — scale + cast pattern above.
5. Exam Points
- Method table + dice/circle program — 5-7 marks, very frequent.
- Static (no
new) + cast traps — 3 marks, frequent.