Table of Contents
1. Basic data types
2 .String type
Home Java javaTutorial Review of Java basics: basic data types and String type

Review of Java basics: basic data types and String type

Aug 02, 2018 pm 02:53 PM
java string

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)
Copy after login

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
Copy after login

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
Copy after login

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);
}
Copy after login

But looking at the code below

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

, 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() {}
    }
Copy after login

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[];
Copy after login

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
Copy after login

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
Copy after login

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);  
}
Copy after login

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{
Copy after login
     AbstractStringBuilder(int capacity) {
            value = new char[capacity];
        }    /**
     * The value is used for character storage.
     */
    char[] value;
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles