Introduction to the Java Number & Math Classes

Introduction to the Java Number & Math Classes

In Java programming, Number and Math are two very commonly used classes. The Number class is an abstract class, which is the parent class of all digital classes, including integers, floating point numbers, and large numbers. The Math class provides many static methods for mathematical calculations. In this article, we will introduce Java Number & Math classes in detail, including their common methods, subclasses and constants.

Number class

The Number class is an abstract class that is the parent class of all number classes. It provides methods for converting numeric objects to various primitive data types.

All wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.

Packaging basic data type
Boolean boolean
Byte byte
Short short
Integer int
Long long
Character char
Float float
Double double

The following are commonly used methods in the Number class:

common method

  • intValue(): Convert Number object to int type.
  • longValue(): Convert Number object to long type.
  • floatValue(): Convert Number object to float type.
  • doubleValue(): Convert Number object to double type.

sample code

Double myDouble = new Double(5.5);
int myInt = myDouble.intValue();
System.out.println(myInt);

In the above sample code, we created a Double object myDouble, then used intValue()method to convert it to int type, and assigned it to the variable myInt. Finally, we use System.out.println()the method to myIntprint the value of the variable.

Subclass

Each numeric type in Java has a corresponding subclass, for example: Integer, Double, Float, Long, etc. These subclasses inherit the methods of the Number class and also provide some new methods.

sample code

Double myDouble = new Double(5.5);
System.out.println(myDouble.isNaN());

In the sample code above, we created a Double object myDoubleand then used isNaN()the method to check whether the number is NaN (Not a Number). Finally, we use System.out.println()the method to print out the judgment result.

Precautions

There are some issues to be aware of when using the Number class. For example, if a Double object is assigned to a variable of type int, precision loss and data truncation will result. Therefore, care must be taken when performing type conversions.

optimization suggestion

According to recent user feedback, the above content is relatively simple, and it is recommended to add more code examples and actual application scenarios.

sample code

Double myDouble = new Double(5.5);
long myLong = myDouble.longValue();
System.out.println(myLong);

In the above sample code, we created a Double object myDouble, then used longValue()method to convert it to long type, and assigned it to a variable myLong. Finally, we use System.out.println()the method to myLongprint the value of the variable.

Application Scenario

In actual programming, the application scenarios of Number and Math classes are very extensive. For example, we can use them to perform operations such as mathematical calculations, data format conversion, and data validation.

mathematical calculation

The Math class provides many static methods for mathematical calculations, such as calculating powers, taking absolute values, and performing rounding operations. These methods can help us perform various mathematical calculations to complete programming tasks more efficiently.

Data format conversion

The Number class provides methods for converting numeric objects to various primitive data types. These methods can help us convert different types of data to meet different business needs.

Data validation

The Number class provides a method to determine whether a number is NaN, which can be used for data verification. At the same time, we can also use the max and min methods in the Math class to perform range verification to ensure the validity of the data.

sample code

The following is a sample code that uses the Number class and the Math class to demonstrate how to perform mathematical calculations, data format conversion, and data validation.

import java.math.BigDecimal;

public class NumberAndMathExample {
    public static void main(String[] args) {
        // 数学计算
        double x = 4.0;
        double y = 2.0;
        double result = Math.pow(x, y);
        System.out.println(result);

        // 数据格式转换
        Double myDouble = new Double(5.5);
        long myLong = myDouble.longValue();
        System.out.println(myLong);

        // 数据校验
        Double myNaN = new Double(Double.NaN);
        System.out.println(myNaN.isNaN());

        BigDecimal myDecimal = new BigDecimal("1234.5678");
        System.out.println(myDecimal.setScale(2, BigDecimal.ROUND_HALF_UP));
    }
}

In the above sample code, we have demonstrated how to use the Math class to calculate a power and use the Number class to convert a Double object to a long type. At the same time, we also demonstrated how to use the isNaN() method to determine whether a number is NaN, and use the BigDecimal class to perform data format conversion and rounding operations.

Math class

The Math class provides many static methods for mathematical calculations. The following are commonly used methods in the Math class:

common method

  • abs(): Returns the absolute value of the given number.
  • ceil(): Returns the smallest integer greater than or equal to the given number.
  • floor(): Returns the largest integer less than or equal to the given number.
  • max(): Returns the greater of two numbers.
  • min(): Returns the smaller of two numbers.
  • pow(): Returns the value of the first number raised to the second power.
  • round(): Returns the rounded value of the given number.
  • sqrt(): Returns the square root of the given number.

sample code

double x = 4.0;
double y = 2.0;
double result = Math.pow(x, y);
System.out.println(result);

In the above sample code, we define two variables of type double xand yuse Math.pow()the method to calculate the power of , and assign the result to the xvariable . Finally, we use the method to print the value of the variable.yresultSystem.out.println()result

constant

The Math class also defines some constants, including:

  • PI: pi constant.
  • E: Natural logarithm constant.

sample code

System.out.println(Math.PI);

In the above sample code, we use System.out.println()the method to print out the value of the pi constant PI in the Math class.

Precautions

When using the Math class, you need to pay attention to some issues. For example, round()when using the method rounding, you need to pay attention to the direction of the rounding. In addition, due to the precision limit of the computer, pow()when using the method to calculate the power, there may be a problem of loss of precision.

Summarize

Number and Math classes are very commonly used classes in Java programming, they provide many useful methods and constants. Proficiency in the use of these classes can help us perform mathematical calculations and digital processing more efficiently. In actual programming, we can choose appropriate subclasses and methods according to specific needs to achieve the best results. At the same time, it is necessary to pay attention to data precision and type conversion to ensure the correctness and reliability of programming.

Guess you like

Origin blog.csdn.net/NBITer/article/details/130165723