Chapter 10. Numbers Matter: Numbers and Statics
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.