One week's quick self-study of java programming Advanced Language Dry Goods Notes - Practical Classes

Keywords: Java network

1. Master the use of enumerations

Enumeration:
Reference data types: array, class (String), interface, enumeration
switch supports int String enumeration (enum)

public class Student{
    private String name;
    private int age;
    private String gender;
    
    public void setAge(int age){
        if(age < 0 || age > 100){
            syso("Illegal age!.....");
            this.age = 60;
        }else{
         	this.age = age;   
        }
    }
    
    public void setGender(String gender){
        if(gender.equals("male") || gender.equals("female")){
            this.gender = gender;
        }else{
            syso(xxxx);
        }
    }
}

public class Test{
    main(){
        Student stu = new Student();
        // stu.age = -1000; (using encapsulation) to solve unreasonable assignments
        stu.gender = "Ha-ha"; // Men and women XX String type - > Gender type?
         
    }
}

Use of enumeration:

/**
 * Gender Type
 * @author Charles7c
 * 2019 April 21, 2000 9:59:03 a.m.
 */
public enum Gender {
	// Constant static final
	// Male, female
	// 0 1
	MALE,FEMALE
}



package cn.kgc.demo1;
/**
 * Student Class
 */
public class Student {
	
	private String name;
	private int age;
	// private String gender; 0 1
	private Gender gender;
	
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", gender=" + gender + "]";
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	/*public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}*/
	public Gender getGender() {
		return gender;
	}
	public void setGender(Gender gender) {
		this.gender = gender;
	}
	
}


package cn.kgc.demo1;

public class Test {

	public static void main(String[] args) {
		
		Student student = new Student();
		student.setName("Bean culm");
		student.setAge(10);
		// student.setGender("oh");
		// In many scenarios we need other developers to pass only a few fixed values when calling some of our methods
		// Enumeration is then required
		student.setGender(Gender.MALE);
		System.out.println(student);
		
	}

}

2. Master the use of packaging classes

  1. There are no functions for the basic data types, so when you need to operate on the basic data types, you can use the corresponding packaging type.
  2. Collection generics require that the data type must be a wrapper type.

Common API s for Packaging Types

  1. String->Basic Data Type/Packaging Type (In network data transfers, your data table layer is converted to a string, and the server accepts some strings, but you also know that strings are not very convenient for manipulating some data, so they need to be converted)
String value = "10";
// Strings can be converted to their corresponding base types
int parsrInt = Integer.parsrInt(value);
// Strings can be converted to their corresponding wrapper type
Integer valueof = Integer.valueof(value);
  1. Basic/Packaging Type->String
int a = 10;
// Anything spliced with a + sign becomes a string
String b = a+"";
// Convert basic data types to strings
String string = Integer.toString(a);
// Convert package type to string
Integer c = Integer.valueof(a);
String string2 = c.toString();

Unpacking and packing

**Unpacking: ** Converting packaging type to basic data type
** Boxing: ** Basic data type converted to packaging type

Notes on the use of packaging classes and basic data types

  1. The wrapper class is a reference data type, so it can accept null values, while the basic data type cannot.
public class Student{
	// private Integer id;
	private Long id;
	}
  1. Wrapper types are not used to replace basic data types, but to compensate for the inability of basic data types to use functions.
    Base data types can be compared with ==worthwhile content wrapper types by default of null, basic data types by default of 0 false, etc.
  2. However, when data is transmitted, it is mostly the basic situation and packaging that can be confused.

3.Math and Random classes

Math Teaching Class

// Base of natural number of circumference
// Find the minimum of both
int mins = Math.min(10,9);
System.out.println(min); // 9
// Find the maximum of both
int maxs = Math.max(10,9);
System.out.println(maxs); // 10
// Evaluate Absolute Value
int abss = Math.abs(-10);
System.out.println(abss); // 10
// Power operation 2 to the third power
double pow = Math.pow(2, 3);
System.out.println(pow); // 8

// Rounding
long round = Math.round(10.5);
System.out.println(round); // 11

// ceil
double ceil = Math.ceil(10.2);
System.out.println(ceil); // 11
// Rounding Down
double floor = Math.floor(10.8);
System.out.println(floor); // 10

// Square
double sqrt = Math.sqrt(4);
System.out.println(sqrt); // 2

// Find random numbers [0.0,1.0]
double random = Math.random();
// Find Random Integers in Range [min,max)
// (int)(Math.random() * (max - min)) + min

4. Master String's common API s

  1. Gets the string length: int length ();
  2. Determine whether the contents of strings are the same: boolean equals(Object obj)
  3. Case-insensitive string comparison: Boolean equalslgnoreCase (String str);
  4. Convert all letters to upper/lower case: String toUpperCase();/ String toLowerCase();
  5. String concat(String anotherString);
		String str1 = "hello";
		String str2 = "world";
		String str3 = str1.concat(str2);
		System.out.println(str3);
  1. Finds the first occurrence of a specified string: int indexOf(String subtr);
String str1 = "helloworld";
		
		int index = str1.indexOf("o");
		System.out.println(index);// 4 Output is the first index from left
		
		int lastIndexOf = str1.lastIndexOf("o");
		System.out.println(lastIndexOf);// 6 Start first from right
  1. Starting at the specified location (inclusive), find the location where the specified string appears: int indexOf(String subtr,int fromIndex);
  2. Finds the last occurrence of the specified string: String substring(int starlndex);
  3. Intercept the substring from the specified location: String substring(int startIndex);
String str1 = "helloworld";
String substring2 = str1.substring(3);
		System.out.println(substring2);
		// loworld gets all characters after index 3
  1. String substring (String subtr, int fromIndex); [substring, fromIndex]
String str1 = "helloworld";
String substring = str1.substring(3, 6);
		System.out.println(substring);// low
  1. Gets the character of the specified index: char charAt(int index);
String str1 = "helloworld";
char charAt = str1.charAt(5);
		System.out.println(charAt);// w
  1. String trim();
  2. Replace string: String replace(String oldStr,String newStr);
String replace = userInput.replace("garbage", "**");
(userInput Just a variable name entered by a keyboard)
  1. Split string: String[] split(String regular expression);
String str = "Outside the Long Pavilion~Edge of Old Road~Evergreen";
		// Regular expression regex
		// A Rule Simple Mode Composite Mode\d{9}
		// Can match rules
		String[] split = str.split("~");
		for (String stri : split) {
			System.out.println(stri);
		}
  1. Converts a string to an array of characters: char[] toCharArray();

2. Master the basic use of StringBuffer

String String Buffer Buffer
String refers to data types, so every time you use a string, you need to create an object (there is a pool of string constants in the method area, so sometimes it won't create objects); every time you stitch a string, you create a new string object, which is particularly inefficient!
Do not use the + sign in a loop to use a stitched string, as the bottom layer is implemented using StringBuffer/StringBuilder.

Construction method:
StringBuffer();
StringBuffer(String str);
Common methods:
Append (any data type); append string
insert(int index, any type of data); insert any data at a specified location and move back the original data
reverse(); string inversion
toString(); converted to string

Master the difference between StringBuffer and String

String creates a new space for each string that is stitched together, only two stitches at a time. Str stitches four times, as shown below
StringBuffer is a one-time stitching process without creating space again

// create object
		// StringBuffer sb = new StringBuffer();
		StringBuffer sb = new StringBuffer("begin:");
		// Split String
		sb.append(10);
		sb.append(11);
		sb.append("abc");
		String string = sb.toString();
		System.out.println(string);// begin:1011abc
		
		// Insert data at specified location
		sb.insert(3, "hehe");
		System.out.println(sb);// beghehein:1011abc
		
		sb.reverse();
		System.out.println(sb);// cba1101:niehehgeb
	
	
		// 12345678
		String numStr = "12345678";
		// Use string buffer object for content insertion - > disguised stitching
		StringBuffer sb = new StringBuffer(numStr);
		for (int i = numStr.length() - 3; i > 0 ; i -= 3) {
			sb.insert(i, ",");
		}
		System.out.println(sb);// 12,345,678

3. Master the time type Date

java.util.Date

Master Time Format Conversion SimpleDateFormat

Date date = new Date(); Will get the current system time for assignment
//Output: Fri Apr 2618:17:48 CST 2019 (US view)
SimpleDateFormat simpleDateFormat = 
				new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
		String f = simpleDateFormat.format(date);
		System.out.println(f);
		// This translates to the current time value
package cn.kgc.demo3;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Demo1 {

	private Date birthday;
	
	public static void main(String[] args) {
		Date date = new Date();
		System.out.println(date);
		// Out of date
		int month = date.getMonth();
		// sCalendar.get(Calendar.MONTH)
		// Format Conversion Object SimpleDateFormat
		// Converted format string
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
		String format = sdf.format(date);
		System.out.println(format);
		
		try {
			Date parse = sdf.parse("2019 11 April 2004:31:42");
			System.out.println(parse);
		} catch (ParseException e) {
			e.printStackTrace();// Return to Fri Apr 2618:17:48 CST 2019
		}
		
	}

}

Use Calendar to master date types

	public static void main(String[] args) {
		
		// Eliminate time sensitivity
		Calendar calendar = Calendar.getInstance();
		// Get time information
		// int dayOfMonth = calendar.get(5);
		// Do not use magic values to use constants
		int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		System.out.println(dayOfMonth);
		int month = calendar.get(Calendar.MONTH);
		System.out.println(month);
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
		System.out.println(dayOfWeek);
	}

Posted by derwert on Sat, 27 Apr 2019 06:42:36 -0700