Chapter 10. Numbers and Statics: Numbers Matter
Do the Math. But there’s more to working with numbers than just doing primitive arithmetic. You might want to get the absolute value of a number, or round a number, or find the larger of two numbers. You might want your numbers to print with exactly two decimal places, or you might want to put commas into your large numbers to make them easier to read. And what about working with dates? You might want to print dates in a variety of ways, or even manipulate dates to say things like, “add three weeks to today’s date”. And what about parsing a String into a number? Or turning a number into a String? You’re in luck. The Java API is full of handy number-tweaking methods ready and easy to use. But most of them are static, so we’ll start by learning what it means for a variable or method to be static, including constants in Java—static final variables.
MATH methods: as close as you’ll ever get to a global method
Except there’s no global anything in Java. But think about this: what if you have a method whose behavior doesn’t depend on an instance variable value. Take the round() method in the Math class, for example. It does the same thing every time—rounds a floating point number(the argument to the method) to the nearest integer. Every time. If you had 10,000 instances of class Math, and ran the round(42.2) method, you’d get an integer value ...
Get Head First Java, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.