Chapter 10. Numbers Matter: Numbers and Statics

image

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 parsing a String into a number? Or turning a number into a String? Someday you’re gonna want to put a bunch of numbers into a collection like ArrayList that takes only objects. You’re in luck. Java and the Java API are full of handy number-tweaking capabilities and 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, also known as 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 ...

Get Head First Java, 3rd 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.