For various languages, we want to do the calculation of data, so we need to define different data types, and then let the program to do the calculation, so Java is no exception, the following list of Java basic data types, and the corresponding wrapper class. Today we’re going to look at the specifics.

Java’s eight basic data types:

  • Boolean: Boolean
  • Integer type: byte1 short 2.int 4.long8
  • Character type: char
  • Float type: float double
type A wrapper class Byte digits
byte Byte 8-128-127
boolean Boolean The default false
short Short 16-32768-32767
char Character 16 bits, storing Unicode codes
int Integer 32 –
long Long A 64 – bit
float Float 32 –
double Double A 64 – bit

A wrapper class

Since Java is an object-oriented language, the use of primitive data types is not sufficient for our daily operations, which are often performed with objects. All other wrapper types of Object that inherit directly from Character and Boolean inherit from Number.

There are two common methods we use for wrapping classes and primitive data types

/ / packing

xxx.ValueOf(); Parameter is the basic data type and returns the wrapper object. A string can return a wrapper object, but the string must match the returned object

/ / split open a case

ParseXXX ():Charcater does not have this method. This is to convert the wrapper class to a primitive data type

Automatic type conversion

Integer, real (constant), and character data can be mixed. In an operation, different types of data are first converted to the same type and then the operation is performed.

Convert from low-level to high-level.

Low -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > highbyte.short.char-- - >int-- - >long-- - >float-- - >double 
Copy the code

Data type conversions must meet the following rules:

  1. Boolean types cannot be cast.

  2. An object type cannot be converted to an object of an unrelated class.

  3. Casts must be used when converting a large type to a small type.

  4. Overflow or loss of precision may occur during conversion, for example:

int i =128; byte b = (byte)i; Because byte is 8 bits and has a maximum of 127, an overflow occurs when an int is cast to byte at 128.Copy the code
  1. Floating-point to integer conversions are obtained by abandoning decimals rather than rounding them, for example:
23.7 = = 23 (int); (int) to 45.89 f = = - 45Copy the code

Automatic type conversion must be such that the number of bits of the data type before the conversion is lower than the number of bits of the data type after the conversion. For example, a 16-bit short data type can be converted to a 32-bit int, and a 32-bit float data type to a 64-bit double.

Public class ZiDongLeiZhuan{public static void main(String[] args){char c1='a'; // define a char int i1 = c1; Println ("char char = "+i1); // int system.out. println("char char = "+i1); char c2 = 'A'; Int i2 = c2+1; Println ("char and int equals "+i2); }} The result is: Char = 97 char =66 c1 =66 C1 = 97 char =66 C1 =66 C1 = 97 CHAR =66 C1 =66Copy the code

Cast casting

  1. The condition is that the converted data types must be compatible.

  2. Format: (type)value type is an instance of the data type to be cast:

Example public class QiangZhiZhuanHuan{public static void main(String[] args){int i1 = 123; byte b = (byte)i1; // Cast to byte system.out. println("int cast to byte equals "+b); }} Result: The value of the int cast to byte is 123Copy the code

Implicit cast

  1. The default type of an integer is int.

  2. Floating-point types do not do this, because you must follow F or F after a number when defining a float type.

Constant pool

The constant pool is the data that is identified at compile time and stored in a compiled.class file. It includes constants in classes, methods, and interfaces, as well as strings.

Constant pool can be divided into static constant pool and runtime constant pool.

Static constant pools exist in class files, such as the commonly used javap-verbose.

The runtime constant pool is stored in the method area after the class file has been loaded into memory. So, it’s all about run-time constant pools

Constant pools now know of a string constant pool

String s1 = "abc"; Look in the string constant pool to see if there are any"abc"Object, if not"abc"And I'm going to point s1"abc"; If you do, you just point to s1"abc";
   String s2 = new String("efg"); Created directly in the heap"efg"Object, and then point to s2 in the stack"efg"example1:
String s1 = "abc";
String s2 = "abc";// assign s1's address to s2, s2 also refers to "ABC"
System.out.println(s1 == s2);//true
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println(s3 == s4);//falsePrinciple: Similar to the basic data type, but the location of data storage is different, the basic data type stored in the stack; String variables are stored on the stack and objects are stored in the heap.Copy the code

Buffer pool

The cache pool is the value cached by the virtual machine in advance, which is easy to operate. It can be understood as a computer buffer technology similar to, (in fact, there is also constant pool flush)

Most of basic types in the Java wrapper class implements the constant pool technology, these classes are Byte, Short, Integer, Long, Character, Boolean, the other two floating-point types of wrapper classes are not implemented. Additional Byte, Short, Integer, Long, Character the 5 kinds of wrapper classes is the corresponding value of the Integer less than or equal to 127 can only be used when constant pool, that object is not responsible for the creation and management of greater than 127 corresponds to the basic types of the objects of the buffer pool is as follows:

  • boolean values true and false
  • all byte values
  • short values between -128 and 127
  • int values between -128 and 127
  • char in the range \u0000 to \u007F

When using the wrapper type corresponding to these base types, if the value range is within the buffer pool scope, you can use objects from the buffer pool directly.

In JDK 1.8, the Integer buffer pool IntegerCache is special. The lower bound of Integer buffer pool IntegerCache is -128. The upper bound is 127 by default, but this upper bound is tunable. Through – XX: AutoBoxCacheMax = to specify the size of the buffer pool, this option will set the JVM is initialized, a Java lang. IntegerCache. High system properties, The system property is then read when IntegerCache is initialized to determine the upper bound.

Integer i = 1; If the number to the right of the equals sign is [-128,127], it is boxed into a wrapper class and stored in an Integer buffer pool. Check to see if the Integer object exists in the buffer pool, and if so, point the variable I to it. If not, create an Integer object in the buffer pool and point variable I to it.

Integer j = 200; Since the number on the right is not [-128,127], create an Integer object directly in the heap memory and point the variable j to it. Take a look at the source:

/** * Caches to support auto-boxed object identity semantics for values between -128 and 127 inclusive as required by JLS. The cache is initialized when first used. * The cache size can be controlled by the -xx :AutoBoxCacheMax=
      
        option. * during the VM initialization, can be in the sun. The misc. VM class in the system of private property Settings and save the Java. Lang. Integer. IntegerCache. * / high attribute
      
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 =
               sun.misc.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(a) {}}Copy the code

I don’t know much about constant pools and buffer pools, but I’ll come back to them when I look at the JVM.

Basic Types Common interview questions:

Q&A: What is automatic packing and unpacking?

Automatic boxing is when the Java compiler does a conversion between the primitive data type and the corresponding object wrapper type, such as int to Integer and double to double. Otherwise, it is automatic unpacking.

Q&A: Is String a basic data type?

String is not an abridged data type and is a final, unmodifiable class. For efficiency, use the StringBuffer class.

Q&A: What’s the difference between int and integer?

Int is the basic type and INTEGER is the wrapper type.

Integer must be instantiated before it can be used, whereas int variables do not.

Integer defaults to null, and int defaults to 0.

An integer is actually a reference to an object, and when new produces an integer it actually generates a pointer to that object, whereas int stores the data value directly.

Q&A: What are the results?
Integer a= new Integer(3);
Integer b= 3; // Automatically box 3 into type Integer
int c=3;
a==b  // false The two references do not refer to the unified object.
a==c // true a automatically unpack int and compare with c.Two nonnewThe generated integer object is compared if the values of the two variables range between -128~127Is compared withtrue, if it is not in this rangefalse;
Integer a=100;  => Integer a = Integer.valueOf(100);
Integer b=100;
a==b // true;
Integer a=128;
Integer b=128;
a== b // false;For valueOf methods there is a cache judgment in the Integer class:Copy the code
Q&A short s1 = 1; s1 = s1 + 1; What’s wrong with that? short s1 = 1; s1 +=1; What’s wrong with that?
  1. For shorts1 = 1; S1 =s1+1; s1+1 =s1+1; s1+1 =s1+1; s1+1 =s1+1; s1+1 =s1+1; s1+1 =s1+1; s1+1 =s1+1; s1+1 =s1+1; s1+1 =s1+1

  2. For short s1 = 1; S1 += for s1+=1 is a Java language-specific operator that the Java compiler treats specially so that it compiles correctly.

OK, that’s all for today. Please follow me if you like.