Java Foundation: Day_12 String Class, Date Class

Keywords: Java JDK network

I. String class

1. Classification of strings:
Immutable String: When an object is created, its content cannot be changed. Once the content changes, it is a new object.
Variable String Builder/String Buffer: When the object is created, the content of the object can be changed, and when the content changes, the object remains unchanged.
The bottom of the string is the char [] array, such as:

String str = "ABCD";//Equivalent to
char[] str = {'A','B','C','D'}; 

2. String creation

Null values of String objects:

String str1 = null;//No initialization, no allocation of memory space
String str2 = "";//Initialization completed, memory allocation, no content

So when we judge whether the string is empty, we should pay attention to the above questions: whether memory is empty or content is not empty. In addition, when using string comparison. Therefore, when comparing content alone, we often use equals method.

In addition, there are two conventional methods for string creation, such as:

//What are the differences between the following two methods?
String str1 = "ABC";				//Law 1
String str2 = new String("ABC"); //Law two

From the point of view of memory usage, for the "ABCD" created by Fa I, a String object is created at most, and a String object is not created at least. Because if "ABCD" already exists in the constant pool, str1 can refer to it directly, and String objects are not created at this time, otherwise "ABCD" memory space is created in the constant pool and then referenced.

For Fa 2, create at most two String objects and at least one String object. If "ABCD" does not exist in the constant pool, create one in it and then create a reference to the constant pool in heap space. If it exists, it is referenced directly after opening up memory.

Then there will be the following phenomena:

System.out.println(str1 == str2);		//false
System.out.println(str1.equals(str2));  //true

Of course, after extending this question one step:

public class Demo_02 {
	public static void main(String[] args) {
		//Notes are pre-compiled
		String str1 = "ABCD";				//String str1 = "ABCD";
		String str2 = "A"+"B"+"C"+"D";		//String str2 = "ABCD";
		String str3 = "AB"+"CD";			//String str3 = "ABCD";
		String str4 = new String("ABCD");	//String str4 = new String("ABCD");
		String str5 = "AB";					//String str5 = "AB";
		String str6 = str5+"CD";			//(new StringBuilder(String.valueOf(str5))).append("CD").toString();
		String str7 = getAB()+"CD";			//(new StringBuilder(String.valueOf(getAB()))).append("CD").toString();
		
		//Output result
		System.out.println(str1 == str2);//true
		System.out.println(str1 == str3);//true
		System.out.println(str1 == str4);//false
		System.out.println(str1 == str6);//false
		System.out.println(str1 == str7);//false
	}
	
	private static String getAB()
	{
		return "AB";
	}
}

Why does this happen? For STR1 to str3, compilation optimization is involved. When compiling, it is optimized to be a string constant. For the relationship between str5 and str1, we can't determine the value of str5 at compile time. We only check that there are no errors in the grammar. Therefore, the compiler cannot optimize it. Similarly, str7 only knows its value at runtime, and the compiler cannot optimize it.

Conclusion:
The strings created by quotation marks alone are all direct quantities, and they are stored in the constant pool at compile time.
(2) Objects created using the new method will be stored in heap memory, which is created at runtime.
(3) Use string connectors that contain only direct quantities, such as "+", and create direct compile times that can be determined and stored in constant pools (such as str2 and str3 above).
(4) Characters that contain String's direct quantities are used to determine the value of variables and the return value of methods only at runtime, and there is no compilation optimization operation.

3.StringBuilder/StringBuffer

According to JDK API 1.6, we can find that:
StringBuffer:

StingBuilder:

//String splicing
public class Demo_01 {
	public static void main(String[] args) {
		StringTest();			//205
		StringBufferTest();		//3
		StringBuilderTest();	//1
		
	}
	
	public static void StringTest()
	{
		long begin = System.currentTimeMillis();
		String str = "";
		for(int i = 0 ; i < 5000 ; i++)
		{
			str += i;
		}
		long end = System.currentTimeMillis();
		System.out.println(end - begin);
		
	}
	
	public static void StringBuilderTest()
	{
		long begin = System.currentTimeMillis();
		StringBuilder sb = new StringBuilder("");
		
		for(int i = 0 ; i < 5000 ; i++)
		{
			sb.append(i);
		}
		long end = System.currentTimeMillis();
		System.out.println(end - begin);
		
	}
	
	public static void StringBufferTest()
	{
		long begin = System.currentTimeMillis();
		StringBuffer sb = new StringBuffer("");
		
		for(int i = 0 ; i < 5000 ; i++)
		{
			sb.append(i);
		}
		long end = System.currentTimeMillis();
		System.out.println(end - begin);	
	}
}

StringBuffer and StringBuilder are functionally identical, representing variable strings.
The only difference is that the methods in StringBuffer all use synchronized modifiers to represent synchronization, which guarantees thread safety when multithreaded concurrency occurs, and performance will be degraded. But StringBuilder does not use synchronized modifiers, which is unsafe, but has relatively high performance. Therefore, we usually use String Builder.

When using StringBuilder, if you need to create an array of char [] with initial capacity, we need to pay attention to the following issues.

For example: char[] value = new char[30]; at this point, the array can only store 16 characters, once more, it needs to be automatically expanded (at this point performance will be reduced). Generally, we know in advance how much content we need to store.

II. Random Number Class

Class 1.Random
A very common but also very simple class for generating a random number (pseudo-random).

int num = new Random().nextInt(150) + 50;//Generate an int, [50,150] random number.

2.TheadRandom class
Java 7 is a new class, which is a subclass of Random. In the case of multi-threaded concurrency, it can reduce the competition of thread resources compared with Random, and ensure the security of threads. Overall, it's more powerful than Random.

In addition, because the constructor is the default access permission to create objects only in java.util, a static method ThreadLocalRandom.current() is provided to return objects of the current class.

ThreadLocalRandom random=THreadLocalRandom.current();//Returns a ThreadLocalRandom object
int num = random.nextInt(50,105)//Returns a random number of int s [50,105].

Class 3.UUID

UUID generates a number on a machine that guarantees that it is unique to machines in the same time and space. It is a 128-bit long number, usually expressed in hexadecimal system. The core idea of the algorithm is to generate UUID by combining machine network card, local time and a pseudo-random number. We usually use it to represent random strings.

String uuid = UUID.randomUUID().toString();
System.out.println(uuid);

III. Date Category

Class 1.Date
Located in the java.util.Date package, it represents a specific instant accurate to milliseconds. But many of these methods are outdated (not necessarily unavailable, just not recommended).

2.DateFormat class
DateFormat can complete date formatting. Includes formatting (Date type - > String type) and parsing (String type - > Date type).
For the use of DateFormat,

		Date date = new Date();
		DateFormat df = DateFormat.getDateInstance();//Decorated by static, the return type is DateFormat
		String time =df.format(date);
		System.out.println(time);

It should be noted that DateFormat is abstract ly modified and cannot be instantiated.

3.SimpleDateFormat class
Custom date class, you can customize any format of time format according to your needs. Specific uses are as follows:

		String pattern = "yyyy-mm-dd hh:mm:ss a";
		SimpleDateFormat mode_01 = new SimpleDateFormat();
		mode_01.applyPattern(pattern);
		String time = mode_01.format(new Date());
		System.out.println(time);

Its mode is composed of strings, which are as follows:

4.Calendar class
Is an abstract class, methods are mostly static methods. In most cases, when we use the calendar class, we use the getInstance() method to create objects.

Calendar date = Calendar.getInstance();

Of course, the date created at this time is not intuitive and concise. So we usually need to use date.get(Calendar.YEAR) to extract the information we need (the year is extracted here).
In most cases, we use Calendar to represent time.

Posted by kusal on Fri, 26 Apr 2019 21:30:50 -0700