48_ Packaging (familiar)

Packaging (familiar)

Concept of packaging class

Generally, the variables of basic data type are not objects. In order to meet the concept that everything is an object, it is necessary to package and encapsulate the variables of basic data type into objects, and the related classes responsible for declaring these variables as member variables for object-oriented processing are called packaging classes.

For example:

Person p = new Person(); // Is the object
int num = 10; // From the grammatical level, it is not an object, which violates our concept that everything is an object. Therefore, we need to find ways to turn it into an object. To create an object, we must first have a class. Therefore, we need to associate the num variable with a class.

public class MyInt {
 	private int num = 10;  // In this way, we invisibly package num into this class, and then turn it into an object through new
}

Classification of packaging

The main value of the wrapper class: package the variables of 8 basic types of data officially in Java into objects through the wrapper class

Benefits: it meets the concept that everything is an object

Packaging (8)  											Corresponding basic types (8)
java.lang.Byte													byte  1 byte
java.lang.Short 												short 2 byte
java.lang.Integer 												int   4 Bytes (special)
java.lang.Long 													long  8 byte
java.lang.Float 												float
java.lang.Double 												double
java.lang.Boolean												boolean
java.lang.Character												char ((special)

Overview and construction of Integer class

  1. Concept:

    • java.lang.Integer class internally wraps an int type variable as a member variable, which is mainly used to wrap int type and provide methods such as conversion from int type to String class.
  2. Common constants

    Constant type and name 								Function introduction
    public static final int MAX_VALUE 		express int The maximum value that the type can describe, i.e. 2^31-1(1 One sign bit, the rest are all 1, so-1)
    public static final int MIN_VALUE 		express int The minimum value that the type can describe, i.e-2^31
    public static final int SIZE 			express int The number of bits (4 bytes) of the type in the form of binary complement*8=32 Bit)
    public static final int BYTES 			express int Number of bytes occupied by type (4 bytes)
    public static final Class<Integer> TYPE  express int Type Class example(For the time being, it can be understood as the name of a type)
    
  3. Common methods

    Method declaration 										Function introduction
    Integer(int value)			 			Constructs the object based on the integer specified by the parameter (obsolete)
    Integer(String s) 			 			Constructs an object based on the string specified by the parameter (obsolete)
        
    int intValue() 				 			Gets the integer value in the calling object and returns
    static Integer valueOf(int i) 			 It is obtained by specifying an integer value according to the parameter Integer Type object
    boolean equals(Object obj) 	  			 Compare whether the calling object is equal to the object specified by the parameter
    String toString() 			 			Returns a string describing the value of the calling object
    static int parseInt(String s) 			 Convert string type to int Type and return
    static String toString(int i) 			 Gets the decimal string form of the integer specified by the parameter
    static String toBinaryString(int i) 	  Gets the binary string form of the integer specified by the parameter
    static String toHexString(int i) 		 Gets the hexadecimal string form of the integer specified by the parameter
    static String toOctalString(int i) 		 Gets the octal string form of the integer specified by the parameter
    
  4. Simple application of constants, construction methods and common basic methods

    package com.huang.task01;
    
    /**
     * @author hhc19
     * @date 2022/1/3 15:46
     * @description
     */
    public class IntegerTest {
    
        public static void main(String[] args) {
    
            // 1. Print Integer; Constant values commonly used in classes
            System.out.println("The maximum value is:" + Integer.MAX_VALUE); // 2147483647 2^31-1
            System.out.println("The minimum value is:" + Integer.MIN_VALUE); // -2147483648 -2^31
            System.out.println("The number of bits represented by binary is:" + Integer.SIZE); // 32
            System.out.println("The number of bytes occupied is" + Integer.BYTES); // 4
            System.out.println("corresponding int Type Class The instance (type name) is:" + Integer.TYPE); // int
    
            System.out.println("--------------------------------------------------");
            // 2. Use the constructor to construct an object of type Integer and print it
            Integer it1 = new Integer(123); // Replaced by valueOf(int i) from Java 9 (static factory method)
            // When string and reference variable are spliced: toString method is called automatically
            System.out.println("it1 = " + it1); // 123
            Integer it2 = new Integer("456"); // Since Java 9, it has been replaced by parseInt(String) + valueOf(int) or value(String) (both static factory methods)
            System.out.println("it2 = " + it2); // 456
            // The appeal method is outdated. It is recommended to use the static factory method in the Integer class to replace it: valueOf(int i). We no longer need to go to the new object. We can directly use the class name call
            // It is equivalent to the conversion from int type to Integer type, which is called packing, that is, the packaging process, which is equivalent to sending express
            Integer it3 = Integer.valueOf(123);
            System.out.println("it3 = " + 123); // 123
            // Equivalent to conversion from String type to Integer type
            Integer it4 = Integer.valueOf("456");
            System.out.println("it4 = " + it4); // 456
            Integer it5 = Integer.valueOf(Integer.parseInt("789"));
            System.out.println("it5 = " + it5); // 789 automatically calls the toString method to get the String type
            // This is the iteration of technology
            // Int variables packaged in Integer: Private Final int value; The member variable in the Integer class, which is the proof of final and cannot be changed once initialized
    
            // Get the Integer value in the calling object, which is equivalent to the conversion from Integer type to int type. It is called unpacking, which is equivalent to unpacking
            int ia = it5.intValue(); // Non static method
            System.out.println("The integer data obtained is:" + ia); // 789 gets int type, but after splicing, it will actually become String type
        }
    }
    
    
  5. The concepts of Boxing (conversion from basic data type to packaging class type) and unpacking (conversion from packaging class type to basic data type)

    • Before the release of Java 5, when using packaging class objects for operations, more cumbersome "unpacking" and "boxing" operations are required; That is, the wrapper object is split into basic type data before operation, and then the result is encapsulated into wrapper object after operation.
    • Since Java 5, the functions of automatic unpacking and automatic packing have been added.
  6. Auto boxing pool:

    • The automatic boxing pool technology is provided inside the Integer class. The integers between - 128 and 127 have been boxed. When the integers in this range are used in the program, the objects in the automatic boxing pool can be used directly without boxing, so as to improve the efficiency.

      Integer Source code of auto boxing pool in class:---------------------------------------
      
      /**
        * Cache to support the object identity semantics of autoboxing for values between
        * -128 and 127 (inclusive) as required by JLS.
        *
        * The cache is initialized on first usage.  The size of the cache
        * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
        * During VM initialization, java.lang.Integer.IntegerCache.high property
        * may be set and saved in the private system properties in the
        * jdk.internal.misc.VM class.
        *
        *
        * The size of the cache
        * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
        * This shows that we can adjust the size of the boxing pool through - XX: autoboxcachemax = < size >, and through the JVM
        * This section involves JVM tuning, which we will learn later.
        * The scope can be appropriately adjusted according to our business needs, so as to improve the efficiency of the program.
        */
      
      // Why not provide a boxing pool for the entire int range? Because it is unnecessary, the range is too large, which consumes memory. We don't necessarily need it, otherwise it will cause waste
      private static class IntegerCache {
           static final int low = -128;
           static final int high;
          static final Integer cache[];
      
          static {
              // high value may be configured by property
              int h = 127;
              String integerCacheHighPropValue =
                  VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
              if (integerCacheHighPropValue != null) {
                  try {
                      int i = parseInt(integerCacheHighPropValue);
                      i = Math.max(i, 127);
                      // Maximum array size is Integer.MAX_VALUE
                      h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                  } catch( NumberFormatException nfe) {
                      // If the property cannot be parsed into an int, ignore it.
                  }
              }
              high = h;
      
              cache = new Integer[(high - low) + 1];
              int j = low;
              for(int k = 0; k < cache.length; k++)
                  cache[k] = new Integer(j++);
      
              // range [-128, 127] must be interned (JLS7 5.1.7)
              assert IntegerCache.high >= 127;
          }
      
          private IntegerCache() {}
      }
      
      Code practice and written examination point of automatic packing mechanism (about automatic packing pool)-----------------------------------------
      
      System.out.println("--------------------------------------------------");
      // 3. Since Java 5, the mechanism of automatic packing and automatic unpacking has been added
      Integer it6 = Integer.valueOf(100); // Before Java 5, you wanted to use boxing
      Integer it7 = 100; // After Java 5, automatic boxing is realized directly through the assignment operator
      int ib = it7; // After Java 5, the automatic unpacking is realized directly through the assignment operator. Before Java 5, Integer object needs to be used intValue(); method
      // Pack and unpack at will. You no longer need to call the method above.
      // In fact, the underlying mechanism of automatic packing and automatic unpacking is still the adjustment method, but I don't need to adjust it myself.
      
      System.out.println("--------------------------------------------------");
      // 4. Written examination site for packing and unpacking
      // The original question of the written examination was 127
      // Automatic packing
      Integer it8 = 127; // 128;
      Integer it9 = 127; // 128;
      // Manual boxing: by calling the constructor new object
      Integer it10 = new Integer(127); // new Integer(128);
      Integer it11 = new Integer(127); // new Integer(128);
      
      // 128 operation results:
      /*System.out.println(it8 == it9);         // The comparison address false has been boxed into a reference type object
      System.out.println(it8.equals(it9));    // The comparison content is true. If the equals method is rewritten, it is the comparison content
      System.out.println(it10 == it11);       // Compare address false
      System.out.println(it10.equals(it11));  // Compare content true*/
      
      // Operation results of 127
      System.out.println(it8 == it9);         // If the comparison address true 127 becomes true, it means that the addresses are the same (that is, the concept of auto boxing pool)
      System.out.println(it8.equals(it9));    // Compare content true
      System.out.println(it10 == it11);       // Compare address false
      System.out.println(it10.equals(it11));  // Compare content true
      
  7. Other common methods of Integer class (static method: raise class name. Call)

    // Static method of converting string to integer
    static int parseInt(String s) 			 Convert string type to int Type and return
        
    // Static method of converting integer to binary: convert according to different hexadecimal
    static String toString(int i) 			 Gets the decimal string form of the integer specified by the parameter
    static String toBinaryString(int i) 	  Gets the binary string form of the integer specified by the parameter
    static String toHexString(int i) 		 Gets the hexadecimal string form of the integer specified by the parameter
    static String toOctalString(int i) 		 Gets the octal string form of the integer specified by the parameter
    
        
    Practice code-------------------------------------------
    // 5. Implement the call of static methods
    int ic = Integer.parseInt("200"); //Although 200 can convert a string to a number, it must be a pure digital string
    // int ic = Integer.parseInt("200a"); //  Compile ok and run Java Lang. numberformatexception (number format exception), because there are letters
    System.out.println("The result of converting a string to an integer is:" + ic); // 200
    System.out.println("The decimal string obtained according to the integer specified by the parameter is:" + Integer.toString(ic)); // 200
    System.out.println("The binary string obtained according to the integer specified by the parameter is:" + Integer.toBinaryString(ic)); // 11001000
    System.out.println("The hexadecimal string obtained according to the integer specified by the parameter is:" + Integer.toHexString(ic)); // c8
    System.out.println("The octal string obtained according to the integer specified by the parameter is:" + Integer.toOctalString(ic));// 310
    

Concept and use of Double class

  1. Basic concepts:

    java.lang.Double type internally wraps a variable of double type as a member variable, which is mainly used to wrap double type and provide methods such as conversion from double type to String class.

  2. Common constants

    Constant type and name 								Function introduction
    public static final int SIZE 			express double Binary digits of type
    public static final int BYTES 			express double Number of bytes of type
    public static final Class TYPE 			express double Type Class example
    
  3. Common methods

    Method declaration 												Function introduction
    Double(double value) 						Constructs an object based on the floating-point data specified by the parameter (obsolete)
    Double(String s) 							Constructs an object based on the string specified by the parameter (obsolete)
    double doubleValue() 						Gets the floating point data in the calling object and returns
    static Double valueOf(double d) 	 		 Obtained by specifying floating point data according to parameters Double Type object
    boolean equals(Object obj) 			 		 Compare whether the calling object is equal to the object specified by the parameter
    String toString() 							Returns a string describing the value of the calling object
    static double parseDouble(String s)   		  Convert string type to double Type and return
    boolean isNaN() 							Judge whether the value of the calling object is non numeric
    
  4. code

    package com.huang.task01;
    
    /**
     * @author hhc19
     * @date 2022/1/3 18:09
     * @description
     */
    public class DoubleTest {
    
        public static void main(String[] args) {
    
            // 1. Print constant values commonly used in the Double class
            System.out.println("double The binary digits of type are:" + Double.SIZE); // 64
            System.out.println("double The number of bytes of type is:" + Double.BYTES);  // 8
            System.out.println("double Type Class Examples are:" + Double.TYPE);  // double
    
            System.out.println("-------------------------------------");
            // 2. The use of common methods, as well as the implementation of boxing and unpacking methods before Java 5
            Float fl1 = new Float(22.22); // The maximum length of float type data is 8 digits, that is, only 8 digits can be displayed at most
            System.out.println("fl1 = " + fl1); // 22.22
            // Double to double conversion
            Double db1 = new Double(22.22); // The maximum data length of double type is 16 bits, and only 16 digits can be displayed at most
            System.out.println("db1 = " + db1); // 22.22
            // Conversion from String type to Double type
            Double db2 = new Double("22.22");
            System.out.println("db2 = " + db2); // 22.22
            // Conversion from double type to double type unpacking
            double d1 = db2.doubleValue();
            System.out.println("d1 = " + d1); // 22.22
    
            System.out.println("-------------------------------------");
            // 3. Use of static factory methods: that is, the methods used to create boxed class objects instead of using construction methods
            Double db3 = Double.valueOf(22.22);
            System.out.println("db3 = " + db3); // 22.22
            Double db4 = Double.valueOf("22.22");
            System.out.println("db4 = " + db4); // 22.22
            Double db5 = Double.valueOf(Double.parseDouble("22.22")); // First, use the parseDouble method to convert the string to double
            System.out.println("db5 = " + db5); // 22.22
    
            System.out.println("-------------------------------------");
            // 4. Start from Java 5 to realize automatic packing and unpacking
            // A double data type variable is wrapped in the double class as a member variable: private final double value;
            // Double type does not hold auto boxing pool
            Double db6 = 22.22;
            double d2 = db6;
            System.out.println("db6 = " + db6); // 22.22
            System.out.println("d2 = " + d2); // 22.22
            // The equals method and toString method are still overridden in the Double class, that is, whether they are equal is compared according to the content
            System.out.println(db6.equals(d2)); // true
            System.out.println(db2.toString());
    
            System.out.println("-------------------------------------");
            // 5. Implement calls to static methods and member methods
            double d3 = Double.parseDouble("3.14");
            System.out.println(d3); // 3,14
            // Judge whether the value of the calling object is non numeric: If yes, return true; Not a non number, that is, a number returns false
            System.out.println("db2 The judgment result of the object is:" + db2.isNaN()); // false is not a non number (it is a number)
            Double db7 = Double.valueOf(0 / 0.0);
            System.out.println("db7 = " + db7); // NaN
            System.out.println("db7 The judgment result of the object is:" + db7.isNaN()); // true is not a number
        }
    }
    
    
  5. extend

    java.lang.Number class is an abstract class and the parent class of the above class. It describes the members common to all classes

    There are abstract intValue(), doubleValue(), longValue(), floatValue() methods in the Number abstract class. Subclasses of the abstract class of these methods need to be rewritten, and the principle of underlying rewriting is the forced type conversion of basic data types.

  6. Shortcut keys for formatting codes in Idea: ctr + A select all codes, and then ctr + alt + L format codes

    Shortcut keys to remove all spaces and white space in Idea: ctr + A selects all codes, then ctr + shift + J removes blank lines and blank values, and shrinks all codes into one line.

Concept and use of Boolean class

  1. Basic concepts

    java.lang.Boolean type internally wraps a boolean type variable as a member variable, which is mainly used to wrap the boolean type and provide methods such as conversion from boolean type to String class.

  2. Common constants

    Constant type and name 										Function introduction
    public static final Boolean FALSE 					The corresponding base value is false Object of
    public static final Boolean TRUE 					The corresponding base value is true Object of
    public static final Class TYPE 						express boolean Type Class example
    
  3. Common methods

    Method declaration 											Function introduction
    Boolean(boolean value) 					Constructs the object based on the Boolean value specified by the parameter (obsolete)
    Boolean(String s) 					    Constructs an object based on the string specified by the parameter (obsolete)
    boolean booleanValue() 					Gets the Boolean value in the calling object and returns
    static Boolean valueOf(boolean b) 		 Obtained by specifying Boolean values according to parameters Boolean Type object
    boolean equals(Object obj) 				 Compare whether the calling object is equal to the object specified by the parameter
    String toString() 					    Returns a string describing the value of the calling object
    static boolean parseBoolean(String s) 	  Convert string type to boolean Type and return
    
  4. Practice code

    package com.huang.task01;
    
    /**
     * @author hhc19
     * @date 2022/1/3 20:33
     * @description
     */
    public class BooleanTest {
    
        public static void main(String[] args) {
    
            // 1. Print constant values commonly used in Boolean classes
            System.out.println("Boolean The corresponding base value is false Object:" + Boolean.FALSE); // false
            System.out.println("Boolean The corresponding base value is true Object:" + Boolean.TRUE);  // true
            System.out.println("Boolean Type Class Examples are:" + Boolean.TYPE);  // boolean
    
            // 2. Before Java 5, the method of packing and unpacking was adopted
            // Equivalent to the conversion from boolean type to boolean type, boxing
            Boolean bo1 = Boolean.valueOf(true);
            System.out.println("bo1 = " + bo1); // true
            boolean b1 = bo1.booleanValue();
            System.out.println("b1 = " + b1); // true
            Boolean bo3 = new Boolean(true);
            System.out.println("bo3 = " + bo3);
            Boolean bo4 = new Boolean("true");
            System.out.println("bo4 = " + bo4);
            Boolean bo5 = new Boolean("TRUEa"); // It is not case sensitive, but the value passed in must also be true after ignoring case, otherwise it is false
            System.out.println("b05 = " + bo5);
    
            // The equals method and toString method are also overridden in the Boolean class
            // The Boolean class encapsulates a member variable of boolean type: private final boolean value;
            System.out.println("----------------------------------------------");
            // 3. Support automatic packing and unpacking from Java 5
            Boolean bo2 = false;
            boolean b2 = bo2;
            System.out.println("b2 = " + b2); // false
    
            System.out.println("----------------------------------------------");
            // 4. Realize the conversion from String type to boolean type
            //boolean b3 = Boolean.parseBoolean("112");
            // The implementation principle of this method is: as long as the parameter value is not true or true, the result is false. Check the manual and source code
            /**
             * public static boolean parseBoolean(String s) {
             *     return "true".equalsIgnoreCase(s);
             * }
             *
             * According to the source code, it can be analyzed that as long as the string passed ignores case, it will return true if it is equal to true, otherwise it will return false.
             */
            boolean b3 = Boolean.parseBoolean("TRUE");
            System.out.println("b3 = " + b3); // true
        }
    }
    
    

Concept and use of Character class

  1. Basic concepts

    java.lang.Character type internally wraps a variable of character type as a member variable (private final char value;), It is mainly used to realize the packaging of char type and provide methods such as character category judgment and conversion.

  2. Common constants

    Constant type and name 							Function introduction
    public static final int SIZE 		express char Binary digits of type
    public static final int BYTES 		express char Number of bytes of type
    public static final Class TYPE 		express char Type Class example
    
  3. Common methods

    Method declaration 											Function introduction
    Character(char value) 					Construct the object based on the character data specified by the parameter (obsolete)
    char charValue() 						Gets the character data in the calling object and returns
    static Character valueOf(char c) 		 Obtained according to the character data specified by the parameter Character Type object
    boolean equals(Object obj) 				Compare whether the calling object is equal to the object specified by the parameter
    String toString() 						Returns a string describing the value of the calling object
        
    static boolean isUpperCase(char ch) 	 Judge whether the character specified by the parameter is uppercase
    static boolean isLowerCase(char ch) 	 Judge whether the character specified by the parameter is lowercase
    static boolean isDigit(char ch) 		 Judge whether the character specified by the parameter is a numeric character
        
    static char toUpperCase(char ch) 		 Converts the characters specified by the parameter to uppercase characters
    static char toLowerCase(char ch) 		 Converts the character specified by the parameter to lowercase
    
  4. Practice code

    package com.huang.task01;
    
    /**
     * @author hhc19
     * @date 2022/1/3 20:33
     * @description
     */
    public class CharacterTest {
    
        public static void main(String[] args) {
    
            // 1. Prints constant values commonly used in the Character class
            System.out.println("Character The binary digits of type are:" + Character.SIZE); // 16
            System.out.println("Character The number of bytes of type is:" + Character.BYTES);  // 2
            System.out.println("Character Type Class Examples are:" + Character.TYPE);  // char
            // Character also overrides the equals method and the toString method
    
            // 2. before Java5, invoke method to implement boxing and unboxing mechanism.
            // It is equivalent to the conversion from Character type to Character type, boxing
            Character ca1 = Character.valueOf('a');
            System.out.println("ca1 = " + ca1); // a
            Character ca3 = new Character('b'); // b
            // Character ca3 = new Character('box'); // Error: Too many characters in character literal
            // Character ca4 = new Character("box"); //  type mismatch
            System.out.println("ca3 = " + ca3);
            // Conversion from Character type to Character type, unpacking
            char c1 = ca1.charValue();
            System.out.println("c1 = " + c1); // a
    
            System.out.println("----------------------------------------");
            // 3. Support automatic packing and unpacking from Java 5
            Character ca2 = 'b';
            char c2 = ca2;
            System.out.println("c2 = " + c2); // b
    
            System.out.println("----------------------------------------");
            // 4. Realize the judgment and conversion of character types
            System.out.println(Character.isUpperCase(c2)); // Determine whether it is a capital letter false
            System.out.println(Character.isLowerCase(c2)); // Determine whether it is lowercase true
            System.out.println(Character.isDigit(c2));     // Judge whether it is numeric character false
            System.out.println("The characters converted to uppercase are:" + Character.toUpperCase(c2)); // B
            System.out.println("The conversion to lowercase characters is:" + Character.toLowerCase(c2)); // b
        }
    }
    

Usage Summary of Wrapper

  • How to convert the basic data type to the corresponding packaging class:
    • Call the constructor or static method (valueOf) = = of the wrapper class
  • How to get the value of the basic data type variable in the wrapper class object:
    • Just call the = = xxxValue (non static) = = method in the wrapper class
  • How string is converted to basic data type:
    • Just call the parseXxx method in the wrapper class (there is no char type, because the strings are composed of char)

Keywords: Java Back-end JavaSE

Added by Qazsad on Thu, 06 Jan 2022 16:01:59 +0200