Java learning log - day 14

Posted by g.grillo on Mon, 17 Jan 2022 02:16:42 +0100

Common API

 String

summary

 * java.lang.String : Is a string class, and the bottom is a string class final Embellished char array,therefore String Many properties are array properties,
 * 
 * For example, once determined,The length cannot be changed
 * 
 * 1 Once the string is created,This string object can no longer be changed
 * 
 * 2 In order to improve the efficiency of string access and storage,java The virtual machine adopts a caching mechanism,All strings are saved in the string constant pool
 * 
 * 3 During program execution,If you want to use a string a   String s1 = "a";First, retrieve from the string constant pool,Yes no a, If not, create one
 * 			If so String s2 = "a"; No longer create,Put the existing one a return
 * 
 * 		So lead String s1 = "a"  String s2 = "a" Use at this time s1 == s2  So is he true,Because they point to the same string object a

Basic use

	// The first part creates an object because they all point to the constant pool
		String s1 = "a";
		String s2 = "a";
		// Compare value true
		System.out.println(s1.equals(s2));
		// Compare address true
		System.out.println(s1 == s2);
		// Once a String is created, it does not mean that this s1 variable cannot be changed, but that the data in the object pointed to by the variable cannot be changed
		s1 = "b";
		
		// In the second part, if the new method is used, a heap memory object will be created, and the string object will be saved in heap memory
		String s3 = new String("a");
		String s4 = new String("a");
		// Because s3 and s4 do not point to the constant pool, but point to the heap memory respectively, the addresses are different and are false
		System.out.println(s3 == s4);
		// However, the equals method is overridden in the String to compare values, so it is true
		System.out.println(s3.equals(s4));

Do not splice frequently

Because the string cannot be changed after creation, if it is spliced frequently, the efficiency is very low, and garbage collection may also have problems

		String[] arr = { "a", "b", "c" };
		String s1 = "";
		for (int i = 0; i < arr.length; i++) {
			s1 += arr[i];
		}
		System.out.println(s1);

Construction method

 

// 1 literal
		String s1 = "asad";
		// 2
		String s2 = new String("xxx");

		// 3-byte array
		byte[] bytes = { 97, 98, 99, 100, 101, 102 };
		String s3 = new String(bytes);
		// abcdef
		System.out.println(s3);

		// 4-byte array, only part is intercepted, 4 represents the starting subscript (including), and 2 represents the number
		String s4 = new String(bytes, 4, 2);
		// ef
		System.out.println(s4);

		// 5-character array
		char[] chars = { 'a', 'b', 'c', 'd' };
		String s5 = new String(chars);
		System.out.println(s5);
		
		// 6-character array, only part of which is intercepted. 1 represents the starting subscript (inclusive) and 2 represents the number
		String s6 = new String(chars,1,2);
		System.out.println(s6);

common method

Learning API: 1. What are the functions? 2. What are the input and output parameters? 3. How to use them

		// 1 char charAt (int index): returns the character at the specified position in the string
		String s1 = "qwehihasd";
		char c1 = s1.charAt(2);
		// e
		System.out.println(c1);

		// 2 boolean endsWith(String suffix): judge whether the string ends with the specified string
		// boolean startsWith(String prefix): the same as above. Judge the start
		System.out.println("Hello.java".endsWith(".java"));
		// Pay attention to the space. If there is a space, it won't match
		System.out.println("Hello.java".endsWith(".java "));

		// 3 boolean equalsIgnoreCase(String str): case insensitive. Compare whether two strings are equal
		System.out.println("abc".equalsIgnoreCase("aBc"));

		// 4 byte[] getBytes(): converts a string into a byte array and returns
		byte[] bytes = "abc".getBytes();
		for (int i = 0; i < bytes.length; i++) {
			System.out.println(bytes[i]);
		}

		// 5 char[] toCharArray(): convert a string into a character array and return it
		char[] chars = "abc".toCharArray();
		for (int i = 0; i < chars.length; i++) {
			System.out.println(chars[i]);
		}

		// 6 int indexOf(String str): get the starting index of the specified string in the string. If not found, return - 1
		System.out.println("askdhqwbe".indexOf("kd")); // 2
		System.out.println("askdhqwbe".indexOf("kda")); // -1
		// 7 int indexOf(String str,int index) :
		// Search (including) from the specified position to obtain the starting index of the specified string in the string. If it is not found, it returns - 1
		System.out.println("askdhaqwbe".indexOf("a", 5)); // -1

		// 8 index lastIndexOf(String str): the same as above. If the last index cannot be found, return - 1
		System.out.println("askdhaqwbe".lastIndexOf("a")); // 5

		// 9 int length(): returns the length of the string
		System.out.println("abc".length());

		// 10 String replaceAll(String regex . String replacement);
		// Replace the specified character and support regular expressions
		// String replace (String str . String replacement);  Regular expressions are not supported
		// Replace a with 1 and return a new string
		// Regular expressions are supported, but there is no difference in not writing regular expressions
		System.out.println("hucgasdqweasd".replaceAll("a", "1"));
		System.out.println("hucgasdqweasd".replace("a", "1"));
		// Because In a regular expression, represents any character
		System.out.println("qwe.rty.yui.uio".replaceAll(".", ","));
		// You can use \ escape
		System.out.println("qwe.rty.yui.uio".replaceAll("\\.", ","));
		System.out.println("qwe.rty.yui.uio".replace(".", ","));

		// 11 String[] split(String regex): splits a string and returns a string array. Regular expressions are supported. Note
		// Point, need escape
		String s2 = "2022.1.14";
		String[] arr = s2.split("\\.");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}

		// 12 String substring(int begin); Gets the substring (including) in the string starting with a subscript
		System.out.println("abcdef".substring(2));// cdef

		// 13 String substring(int begin, int end) :
		// Gets the substring (excluding) in the string starting with (including) a subscript and ending with a subscript
		System.out.println("abcdef".substring(2, 4));// cd

		// 14 String trim(): remove the spaces on both sides of the string
		System.out
				.println("            a                    d                  sadasd                      ");
		System.out
				.println("            a                    d                  sadasd                      "
						.trim());

		// 15 String toUpperCase(): convert to uppercase
		// String toLowerCase(): convert to lowercase
		System.out.println("asd".toUpperCase());

		// 16 static String valueOf(Object obj) :
		// Call the toString method of the object. If it is null, toString will no longer be called, but the string null will be returned
		String_05 s = null;
		// When printing a reference type, the valueOf of String will be called automatically, so the toString method will be called automatically
		System.out.println(s);
	

be careful

		// 1
		String a = "a";
		String b = "b";
		String str = "ab";
		// The literal addition removes + at the compilation stage
		String d = "a" + "b";
		// true
		System.out.println(d == str);
		// true
		System.out.println(d.equals(str));
		// Variable addition, because the value of the variable is variable, there is no way to determine the value of the variable before operation,
		// Therefore, there is no way to optimize. We can only convert it to new and recreate and splice the string
		String c = a + b;
		String e = a + "b";
		// false
		System.out.println(c == str);
		// true
		System.out.println(c.equals(str));
		
		//  The above addition is because the value of the variable cannot be determined. If it is declared as a constant, it can be optimized
		String str1 = "ab";
		final String a1 = "a";
		final String b1 = "b";
		String c1 = a1+b1;
		System.out.println(c1==str1);
		
		// How many objects are created? 1 
		String xx = "a"+"b" +"c"+"d";
	

StringBuffer and StringBuilder

StringBuffer and StringBuilder: both are string buffers that can be spliced\
The difference between StringBuffer and StringBuilder and String
String: the bottom layer is a char array with a fixed length. Once created, it cannot be changed. It is not suitable for string splicing
StringBuffer and StringBuilder: the bottom layer is the char array, which becomes longer. A space is applied in memory in advance to store many characters
If the reserved space is insufficient, it will be automatically expanded
The default capacity is 16, and the expanded capacity (current capacity + 1) * 2 16 - > 34 - > 70
The difference between StringBuffer and StringBuilder
StringBuffer is thread safe and will not cause problems in a multithreaded environment
StringBuilder is not thread safe. In a multithreaded environment, problems may occur

	public static void main(String[] args) {
		// Create an object
		StringBuilder sb = new  StringBuilder();
		String[] arr = {"a","b","c"};
		for (int i = 0; i < arr.length; i++) {
			// append is to add data and splice
			// Can be called chained
			sb.append(arr[i]).append(",");
		}
		// reversal
		sb.reverse();
		// Get the number of existing elements
		System.out.println(sb.length());
		// Current capacity (array length)
		System.out.println(sb.capacity());
		// toString can convert StringBuilder to String type
		String str = sb.toString();
		
		System.out.println(str);
	}

Packaging

[question] what should I do if I want to perform more operations on basic type data?  

[answer] the most convenient way is to encapsulate it into objects. Because more attributes and behaviors can be defined in the object description to operate on the basic data type. We don't need to encapsulate basic types by ourselves. JDK has already encapsulated them for us.

[concept]

1. Boxing is to automatically convert the basic data type to the wrapper type

2. Unpacking is to automatically convert the wrapper type to the basic data type

use

	public static void main(String[] args) {
		// Basic type
		byte b1 = 12;
		// Package as wrapper class
		Byte b2 = new Byte(b1);
		m1(b2);
		long l1 = 123L;
		Long l2 = new Long(l1);
	}
	public static void m1(Object o){
		
	}

 

		// Maximum
		System.out.println(Integer.MAX_VALUE);
		System.out.println(Integer.MIN_VALUE);
		System.out.println(Long.MAX_VALUE);
		System.out.println(Double.MAX_VALUE);
		
		// create object
		Integer i1 = new Integer(123);
		// Passing a string is OK, but it must be a pure number
		Integer i2 = new Integer("1231");
		// Error Java lang.NumberFormatException: For input string: "1231a"
		Integer i3 = new Integer("1231a");
	
		// int ---> Integer
		Integer i1 = new Integer(123);
		i1 = Integer.valueOf(123);
		
		// Integer --> int
		int i2 = i1.intValue();
		
		// String --> integer
		Integer i3 = new Integer("123");
		i3 = Integer.valueOf("123");
		
		// Integer --> String 
		String string = i3.toString();
		
		// int --> String
		String string1 = 123+"";
		
		// String --> int 
		// Important static int parseInt(String str): converts a pure numeric string to an int type
		int i4 = Integer.parseInt("123");
		double d1 = Double.parseDouble("2.4");
		
		// Returns a number as a binary string
		String s1 = Integer.toBinaryString(10);
		// Ditto, octal
		s1 = Integer.toOctalString(10);
		// Ditto, hex
		s1 = Integer.toHexString(10);
		System.out.println(s1);
		
	

 java1.5 new features: automatic packing and unpacking
Packing: basic type to packing class type
Unpacking: from package type to basic type
All eight wrapper classes override the toString and equals() methods

		// It was written before 1.5
		Integer i1 = Integer.valueOf(123);
		int i2 = i1.intValue();
		
		// 1.5 start
		Integer i3 = 123; // After compilation, it is equal to integer I3 = integer valueOf(123);
		int i4 = i3; // After compilation, it is equal to int I4 = I3 intValue(); 
		m1(i3);
		// 1234 is an int type. It will be automatically boxed to Integer type first, and then polymorphic transformation to Object type occurs
		m1(1234);
	

Constant pool

In short, the constant pool is to prepare some objects in advance. When we want to save data, we find that they have been created, so we can take them away directly without re creating them
Summary:
When we create an object through new Integer(xx), no matter what the value is== Always false
When we use Integer i1 = xxx; In this way, it will be converted to integer after compilation valueOf() ; This method passes through the integer constant pool
If the value of xxx is between - 128 and 127, the new object is not required, but the created object in the constant pool is used
Otherwise, if it is no longer in the range, it is still equal to new Integer(xxx)
So
              Integer i1 = xxx;
              Integer i2 = xxx; If XXX is between - 128 and 127, i1 == i2 is true
However, note that it is better to compare Integer types with equals

		int i = -128;
		System.out.println(-i);
		Integer i1 = new Integer(10);
		Integer i2 = new Integer(10);
		// false
		System.out.println(i1 == i2);
		// true
		System.out.println(i1.equals(i2));
		Integer i3 = Integer.valueOf(-126);
		Integer i4 = Integer.valueOf(-126);
		// true
		System.out.println(i3 == i4);

		Integer i5 = 12; // After compilation, integer valueOf(12);
		Integer i6 = 12;
		// true
		System.out.println(i5 == i6);

		Integer i7 = 222; // Is equal to new Integer(222)
		Integer i8 = 222;
		// false, because the range of integer constant pool is - 128 ~ 127
		System.out.println(i7 == i8);
	

system

Gets the current number of milliseconds, computer time system In user input stream

		//Indicates that the error is displayed to the console in red font
		System.err.println(123);
		//Standard output -- > print to console
		System.out.println(123);
		//in indicates the standard input receiving console input information
		new Scanner(System.in);
		
		// Gets the number of milliseconds from the time origin to the current time (1970.1.1 8:0:0)
		long startTime = System.currentTimeMillis();
		System.out.println("Executing");
		@SuppressWarnings("unused")
		long endTime = System.currentTimeMillis();
		System.out.println(startTime);
		
		//Exiting the JVM virtual machine 0 means normal shutdown and 1 means abnormal shutdown. It is generally used to close the window of the graphical interface
		System.exit(0);
		//Cannot execute
		System.out.println("+=====");
	

Date

		// Get current system time
		Date d1 = new Date();
		// Pass in the number of milliseconds and get the world from the time origin to the specified number of milliseconds
		Date d2 = new Date(1000);
		// Fri Jan 14 16:15:57 CST 2022
		System.out.println(d1);
		// Thu Jan 01 08:00:01 CST 1970
		System.out.println(d2);
		
		// 1642148327849 gets the number of milliseconds for the specified time
		System.out.println(d1.getTime());
		// Convert time to string type
		System.out.println(d1.toString());
		
		/**
		 * Year y
		 * Month M
		 * Day d
		 * Hour H
		 * Minute m
		 * Second s
		 * MS S 
		 */
		// Create time format object
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss SSS");
		// Format, return string
		String string = sdf.format(d1);
		System.out.println(string);
		
		// Convert a string in time format to a Date object
		String strDate = "2022/01/14 16:21:36";
		// The time format of the formatted object should be consistent with the format of the string
		sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		// The conversion returns a Date object
		Date date = sdf.parse(strDate);
		System.out.println(date);
	
		//Get current calendar
		Calendar c1 = Calendar.getInstance();
		//Gets the day of the week, starting on Sunday
		System.out.println(c1.get(Calendar.DAY_OF_WEEK));
		//year
		System.out.println(c1.get(Calendar.YEAR));
		//month
		System.out.println(c1.get(Calendar.MONTH)+1);
		//day
		System.out.println(c1.get(Calendar.DAY_OF_MONTH));
		//Time 12 hours
		System.out.println(c1.get(Calendar.HOUR));
		//24 hours
		System.out.println(c1.get(Calendar.HOUR_OF_DAY));
		System.out.println(c1.get(Calendar.MINUTE));
		System.out.println(c1.get(Calendar.MARCH));
		
	

Random

		//Create random number generator 
		Random r =new Random(); 
		//Randomly generate a number in the range of int
		int i =r.nextInt();
		System.out.println(i);
		
		//Passing in 10 indicates that it should be generated between 0 and 9
		i=r.nextInt(10);
		System.out.println(i);
		
		//Generate 10 ~ 20
		//Nextint (max min + 1) + min
		int result = r.nextInt(100 - 20 +1)+20;
				System.out.println(result);

	

Topics: Java Back-end