YouTip LogoYouTip

Java Number

# Java Number & Math Classes\n\n## Java Number\n\nGenerally, when we need to use numbers, we typically use built-in data types such as **byte, int, long, double**, etc.\n\n## Example\n\n```java\nint a = 5000;\nfloat b = 13.65f;\nbyte c = 0x4a;\n\nHowever, in actual development, we often encounter situations where we need to use objects instead of built-in data types. To solve this problem, the Java language provides a corresponding wrapper class for each built-in data type.\n\nAll wrapper classes **(Integer, Long, Byte, Double, Float, Short)** are subclasses of the abstract class Number.\n\n| Class Name | Corresponding Primitive Type | Description |\n| --- | --- | --- |\n| Byte | byte | Byte wrapper class |\n| Short | short | Short integer wrapper class |\n| Integer | int | Integer wrapper class |\n| Long | long | Long integer wrapper class |\n| Float | float | Single-precision floating-point wrapper class |\n| Double | double | Double-precision floating-point wrapper class |\n| BigInteger | - | Immutable arbitrary-precision integer |\n| BigDecimal | - | Immutable arbitrary-precision signed decimal number |\n\n![Image 1: Java Number Class](#)\n\nThis special support by the compiler is called boxing. So when a built-in data type is used as an object, the compiler boxes the built-in type into a wrapper class. Similarly, the compiler can also unbox an object into a built-in type.\n\nThe Number class belongs to the `java.lang` package.\n\nNumber is an abstract class, primarily providing unified conversion methods for various numeric types:\n\n## Example\n\n```java\npublic abstract class Number implements Serializable {\n\n // Abstract methods\n public abstract int intValue();\n public abstract long longValue();\n public abstract float floatValue();\n public abstract double doubleValue();\n\n // Added in Java 8\n public byte byteValue() {\n return (byte) intValue();\n }\n\n public short shortValue() {\n return (short) intValue();\n }\n}\n\nHere is an example using an Integer object:\n\n## Test.java File Code:\n\n```java\npublic class Test {\n public static void main(String[] args) {\n Integer x = 5;\n x = x + 10;\n System.out.println(x);\n }\n}\n\nThe compilation and execution result of the above example is as follows:\n\n15\n\nWhen `x` is assigned an integer value, since `x` is an object, the compiler needs to box `x`. Then, to allow `x` to perform addition, it needs to be unboxed.\n\n### Common Method Examples\n\n#### Primitive Type Conversion\n\n## Example\n\n```java\nNumber num = 1234.56; // Actually a Double type\n\nSystem.out.println(num.intValue()); // 1234 (truncates decimals)\nSystem.out.println(num.longValue()); // 1234\nSystem.out.println(num.floatValue()); // 1234.56\nSystem.out.println(num.doubleValue()); // 1234.56\n\n#### Numerical Comparison\n\n## Example\n\n```java\nInteger x = 10;\nDouble y = 10.0;\n\n// Correct comparison method: convert to the same type before comparing\nSystem.out.println(x.doubleValue() == y.doubleValue()); // true\n\n### Special Numerical Handling\n\n#### Handling Large Numbers\n\n## Example\n\n```java\nBigInteger bigInt = new BigInteger("12345678901234567890");\nBigDecimal bigDec = new BigDecimal("1234567890.1234567890");\n\n// Large number operations\nBigInteger sum = bigInt.add(new BigInteger("1"));\nBigDecimal product = bigDec.multiply(new BigDecimal("2"));\n\n#### Numerical Formatting\n\n## Example\n\n```java\nNumberFormat nf = NumberFormat.getInstance();\nnf.setMaximumFractionDigits(2);\nSystem.out.println(nf.format(1234.5678)); // "1,234.57"\n\n### Autoboxing and Unboxing\n\nJava 5+ supports automatic conversion:\n\n## Example\n\n```java\n// Autoboxing\nInteger autoBoxed = 42; // Compiler converts to Integer.valueOf(42)\n\n// Unboxing\nint autoUnboxed = autoBoxed; // Compiler converts to autoBoxed.intValue()\n\n---\n\n## Java Math Class\n\nThe Math class is a mathematical utility class provided by Java, located in the `java.lang` package, containing static methods for performing basic numerical operations.\n\nJava's Math includes properties and methods for performing basic mathematical operations, such as elementary exponentials, logarithms, square roots, and trigonometric functions.\n\nMath methods are all defined as static. You can call them directly in the main function through the Math class.\n\n## Test.java File Code:\n\n```java\npublic class Test {\n public static void main(String[] args) {\n System.out.println("90 Sine value of degrees:" + Math.sin(Math.PI / 2));\n System.out.println("0Cosine value of degrees:" + Math.cos(0));\n System.out.println("60Tangent value of degrees:" + Math.tan(Math.PI / 3));\n System.out.println("1Arctangent value: " + Math.atan(1));\n System.out.println("Ο€/2Angle value:" + Math.toDegrees(Math.PI / 2));\n System.out.println(Math.PI);\n }\n}\n\nThe compilation and execution result of the above example is as follows:\n\n90 Sine value of degrees: 1.0\n0Cosine value of degrees: 1.0\n60Tangent value of degrees: 1.7320508075688767\n1Arctangent value: 0.7853981633974483\nΟ€/2Angle value: 90.0\n3.141592653589793\n\n### Advanced Mathematical Operations\n\n#### 1. Exponential and Logarithmic Operations\n\n## Example\n\n```java\nMath.exp(1); // e^1 β‰ˆ 2.718\nMath.log(Math.E); // ln(e) = 1\nMath.log10(100); // log10(100) = 2\n\n#### 2. Random Number Generation\n\n## Example\n\n```java\n// Generate a random number in the range [0.0, 1.0)\ndouble random = Math.random();\n\n// Generate a random integer in the range [1, 100]\nint randomInt = (int) (Math.random() * 100) + 1;\n\n#### 3. Other Operations\n\n## Example\n\n```java\nMath.hypot(3, 4); // Calculate sqrt(xΒ²+yΒ²) β†’ 5.0\nMath.IEEEremainder(10, 3); // IEEE remainder β†’ 1.0\n\n#### 4. Constant Fields\n\n## Example\n\n```java\nMath.PI; // Ο€ β‰ˆ 3.141592653589793\nMath.E; // Natural logarithm base e β‰ˆ 2.718281828459045\n\n---\n\n## Number & Math Class Methods\n\nThe table below lists some common methods of the Number & Math classes:\n\n| No. | Method and Description |\n| --- | --- |\n| 1 | [xxxValue()](#) Converts the Number object to a value of the xxx data type and returns it. |\n| 2 | [compareTo()](#) Compares the number object with the parameter. |\n| 3 | [equals()](#) Determines whether the number object is equal to the parameter. |\n| 4 | [valueOf()](#) Returns a Number object of the specified built-in data type. |\n| 5 | [toString()](#) Returns the value as a string. |\n| 6 | [parseInt()](#) Parses a string into an int type. |\n| 7 | [abs()](#) Returns the absolute value of the parameter. |\n| 8 | [ceil()](#) Returns the smallest integer greater than or equal to (>=) the given parameter, as a double. |\n| 9 | [floor()](#) Returns the largest integer less than or equal to (<=) the given parameter. |\n| 10 | [rint()](#) Returns the integer closest to the parameter. The return type is double. |\n| 11 | [round()](#) It represents **rounding**, with the algorithm Math.floor(x+0.5), which adds 0.5 to the original number and then rounds down. Therefore, Math.round(11.5) results in 12, and Math.round(-11.5) results in -11. |\n| 12 | [min()](#) Returns the smaller of the two parameters. |\n| 13 | [max()](#) Returns the larger of the two parameters. |\n| 14 | [exp()](#) Returns e raised to the power of the parameter. |\n| 15 | [log()](#) Returns the natural logarithm of the parameter. |\n| 16 | [pow()](#) Returns the first parameter raised to the power of the second parameter. |\n| 17 | [sqrt()](#) Returns the square root of the parameter. |\n| 18 | [sin()](#) Returns the sine of the specified double parameter. |\n| 19 | [cos()](#) Returns the cosine of the specified double parameter. |\n| 20 | [tan()](#) Returns the tangent of the specified double parameter. |\n| 21 | [asin()](#) Returns the arc sine of the specified double parameter. |\n| 22 | [acos()](#) Returns the arc cosine of the specified double parameter. |\n| 23 | [atan()](#) Returns the arc tangent of the specified double parameter. |\n| 24 | [atan2()](#) Converts Cartesian coordinates to polar coordinates and returns the angle of the polar coordinates. |\n| 25 | [toDegrees()](#) Converts the parameter to degrees. |\n| 26 | [toRadians()](#) Converts degrees to radians. |\n| 27 | [random()](#) Returns a random number. |\n\n---\n\n## Comparison of Math's floor, round, and ceil Methods\n\n| Parameter | Math.floor | Math.round | Math.ceil |\n| --- | --- | --- | --- |\n| 1.4 | 1 | 1 | 2 |\n| 1.5 | 1 | 2 | 2 |\n| 1.6 | 1 | 2 | 2 |\n| -1.4 | -2 | -1 | -1 |\n| -1.5 | -2 | -1 | -1 |\n| -1.6 | -2 | -2 | -1 |\n\n## floor, round, and ceil Example:\n\n```java\npublic class Main {\n public static void main(String[] args) {\n double[] nums = {1.4, 1.5, 1.6, -1.4, -1.5, -1.6};\n for (double num : nums) {\n test(num);\n }\n }\n\n private static void test(double num) {\n System.out.println("Math.floor(" + num + ")=" + Math.floor(num));\n System.out.println("Math.round(" + num + ")=" + Math.round(num));\n System.out.println("Math.ceil(" + num + ")=" + Math.ceil(num));\n }\n}\n\nThe output of the above example is:\n\nMath.floor(1.4)=1.0\nMath.round(1.4)=1\nMath.ceil(1.4)=2.0\nMath.floor(1.5)=1.0\nMath.round(1.5)=2\nMath.ceil(1.5)=2.0\nMath.floor(1.6)=1.0\nMath.round(1.6)=2\nMath.ceil(1.6)=2.0\nMath.floor(-1.4)=-2.0\nMath.round(-1.4)=-1\nMath.ceil(-1.4)=-1.0\nMath.floor(-1.5)=-2.0\nMath.round(-1.5)=-1\nMath.ceil(-1.5)=-1.0\nMath.floor(-1.6)=-2.0\nMath.round(-1.6)=-2\nMath.ceil(-1.6)=-1.0
← Java CharacterJava If Else Switch β†’