Click to enter _ more _java thousand ask
1. Does string belong to the basic data type?
The first thing to make clear is that in Java, string is not a basic data type, it inherits from object and is a string class provided by the JDK.
Learn about the basic data types here: What are the 8 basic data types for Java 2
However, the JDK does a lot of special processing compared to other objects. reflected in the following aspects:
- The string can be constructed from new or directly assigned to a value. For example:
StringnewString"abc" );//第一种String"abc" ;//第二种
The first creates a new object with new (), which is stored in the heap, and a new object is created each time it is called.
The second is to create an object reference variable str to the String class in the stack, and then find out if there is no "ABC" in the stack, and if not, put "ABC" in the stack, and str points to "ABC", and if there is already "ABC" it will direct STR to "ABC".
Read about the Java memory stack here:
The second way (string str1 = "abc") creates multiple "ABC" strings, in which only one object exists in memory. This saves memory space, and it can increase the speed of the program to some extent, because the JVM automatically determines whether it is necessary to create new objects based on the actual data in the stack.
For the code of string str = new String ("abc"), it is necessary to create new objects in the heap, regardless of whether their string values are equal, to create new objects, thereby aggravating the burden of the program.
Use the Equals () method when comparing values within a class, and when comparing two reference variables to the same object, use = = (which can be understood as comparing logical addresses, actually comparing object numbers). For example:
String"abc" ;String"abc" ;System.out
Operation Result:
True
You can see that str1 and str2 are objects in the stack.
StringnewString"abc" );StringnewString"abc" );System.out
Operation Result:
False
Read more about string here:
Java q _06 data structure (007) _string is the basic data type?