Analysis of principle examples of Java number class

This article mainly introduces the principle analysis of Java number class. It is introduced in great detail through the example code, which has a certain reference value for everyone's study or work. Friends in need can refer to it

Number class

Built in data types: byte, int, long, double, etc

Packaging classes: integer, long, byte, double, float, short

This wrapper specifically supported by the compiler is called boxing, so when the built-in data type is used as an object, the compiler will box the built-in type as a wrapper class. Similarly, the compiler can unpack an object into a built-in type. The number class belongs to Java Lang package.

public class Test{

  public static void main(String args[]){
   Integer x = 5;
   x = x + 10;
   System.out.println(x);
  }
}

When x is assigned an integer value, the compiler will box x because x is an object. Then, in order to add x, we unpack X

Number class method:

Xxxvalue method: converts the number object to a value of XXX data type and returns

public class Test{

  public static void main(String args[]){
   Integer x = 5;
   // 返回 byte 原生数据类型
   System.out.println( x.byteValue() );//5

   // 返回 double 原生数据类型
   System.out.println(x.doubleValue());//5.0

   // 返回 long 原生数据类型
   System.out.println( x.longValue() ); //5
  }

CompareTo () method: compare the number object with the parameter, and compare two data of the same type

public class Test{
  public static void main(String args[]){
   Integer x = 5;
   System.out.println(x.compareTo(3));//1
   System.out.println(x.compareTo(5));//0
   System.out.println(x.compareTo(8));//-1
   }
}

Equals() method: judge whether the number object is equal to the parameter

    Integer x = 5;
    Integer y = 10;
    Integer z =5;
    Short a = 5;

    System.out.println(x.equals(y)); //false
    System.out.println(x.equals(z)); //true
    System.out.println(x.equals(a));//false

Valueof () method: returns the native number object value of the given parameter. This method is a static method

    Integer x =Integer.valueOf(9);//9
    Double c = Double.valueOf(5);//5.0
    Float a = Float.valueOf("80");//80.0        

    Integer b = Integer.valueOf("444",16);  // 使用 16 进制//1092

Tostring() method: returns a value as a string

    System.out.println(x.toString());
    System.out.println(Integer.toString(12)); 

Parselnt(): resolves a string to type int

    int x =Integer.parseInt("9");
    double c = Double.parseDouble("5");
    int b = Integer.parseInt("444",16);

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>