Home >Java >javaTutorial >Review of Java basics: basic data types and String type

Review of Java basics: basic data types and String type

php是最好的语言
php是最好的语言Original
2018-08-02 14:53:272185browse

1. Basic data types

There are 8 basic data types in Java, four integer types (byte, short, int, long), Two decimal types (float, double), one character type (char), and one Boolean type (boolean)

Type byte Value range
byte 1 -2^7 ~ 2^7 - 1
short 2 -2^15 ~ 2^15 - 1
int 4 -2^31 ~ 2^31 - 1
long 8 -2^63 ~ 2^63 - 1

(One byte represents an 8-bit binary) float occupies 32 bits, double occupies 64 bits, char occupies 16 bits, and boolean occupies 1 bit

Because Java is object-oriented It is a language, so these eight basic data types have corresponding packaging classes: Byte, Short, Integer, Long, Float, Double, Character, and Boolean. The assignment between these eight basic types and their corresponding packaging types is completed using automatic boxing and unboxing.

Integer a = 1; // 基本数据类型int自动装箱为Integer包装类(实际上在编译时会调用Integer .valueOf方法来装箱)int b = a;  // 自动拆箱(实际上会在编译调用intValue)

So what is the difference between new Integer(123) and Integer.valueOf(123)?

new Integer(123) An object will be created every time, and Integer.valueOf(123) uses the cache object, so Integer is used multiple times .valueOf(123), only a reference to the same object will be obtained.

Integer a = new Integer(123);Integer b = new Integer(123);
System.out.println(x == y);    // falseInteger c = Integer.valueOf(123);Integer d = Integer.valueOf(123);
System.out.println(z == k);   // true

The compiler will call the valueOf() method during the autoboxing process. Therefore, if multiple Integer instances are created using autoboxing and have the same value, they will reference the same object.

Integer m = 123;Integer n = 123;
System.out.println(m == n); // true

According to looking at the source code of the Integer class, we found that when using valueOf(), first determine whether the value is in the cache pool, and if so, directly return the contents of the cache pool.

public static Integer valueOf(int i) {    if (i >= IntegerCache.low && i <= IntegerCache.high)        return IntegerCache.cache[i + (-IntegerCache.low)];    return new Integer(i);
}

But looking at the code below

    Integer i1 = 128;    Integer i2 = 128;
    System.out.println(i1 == i2); //false

, we find that false is returned. This is because in Integer, the cache pool range is: -128 ~ 127

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() {}
    }

2 .String type

In addition to the eight basic data types above, the String class is also the most commonly used type in writing programs.

The String class is declared final, so it cannot be inherited. It uses a char array internally to store data, and the array is declared as final, which means that after the value array is initialized, it cannot reference other arrays, and there is no method inside String to change the value array, so String can be guaranteed to be immutable.

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

String.intern()

Using String.intern() can ensure that string variables with the same content refer to the same memory object.

In the following example, s1 and s2 use new String() to create two new objects, and s3 obtains an object reference through the s1.intern() method. This method first removes the object referenced by s1. Put it into the String Pool (string constant pool), and then return this object reference. Therefore, s3 and s1 refer to the same string constant pool object.

String s1 = new String("aaa");String s2 = new String("aaa");
System.out.println(s1 == s2);           // falseString s3 = s1.intern();
System.out.println(s1.intern() == s3);  // true

If you create a string instance in the form of "bbb" using double quotes, the newly created object will be automatically put into the String Pool.

String s4 = "bbb";String s5 = "bbb";
System.out.println(s4 == s5);  // true

Before Java 7, the string constant pool was placed in the runtime constant pool, which belonged to the permanent generation. In Java 7, the string constant pool is placed on the heap. This is because the permanent generation has limited space, which can cause OutOfMemoryError errors in scenarios where strings are used extensively.

So knowing that String is immutable, what are the benefits of this design?

1. The need for string pool

The string constant pool (String intern pool) is a special storage area in the Java heap memory. When creating a String object hour. If this string value already exists in the constant pool, a new object will not be created, but the existing object will be referenced.
Review of Java basics: basic data types and String type

2. Allow String objects to cache HashCode

The hash code of String objects in Java is frequently used, such as in containers such as hashMap .

String immutability ensures the uniqueness of the hash code, so it can be cached with confidence. This is also a performance optimization method, which means that you don’t have to calculate a new hash code every time

3. Security

String is used by many Java classes ( library) are used as parameters, such as network connection address URL, file path, and String parameters required by the reflection mechanism, etc. If the String is not fixed, it will cause various security risks.

boolean connect(string s){  
    if (!isSecure(s)) {   
throw new SecurityException();   
}  
    // 如果在其他地方可以修改String,那么此处就会引起各种预料不到的问题/错误   
    causeProblem(s);  
}

4. Thread safety

String Immutability is inherently thread-safe and can be used safely in multiple threads.

This article has a detailed introduction.

String is immutable, so is there a mutable string?

StringBuffer and StringBuilder are provided in Java, which are variable. In String, a final character array is defined, so it is immutable. However, because StringBuffer and StringBuilder inherit AbstractStringBuilder, it can be seen from the source code that they are variable character arrays.

public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence{
     AbstractStringBuilder(int capacity) {
            value = new char[capacity];
        }    /**
     * The value is used for character storage.
     */
    char[] value;

According to the source code, we can also know that StringBuffer is thread-safe, and its methods are all modified by synchronized.

Related articles:

Data types of basic knowledge of JavaScript_Basic knowledge

## Basic data types and streams in Java

Related videos:


Overview and classification of data types-JAVA beginner video tutorial

The above is the detailed content of Review of Java basics: basic data types and String type. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn