Common API s in Java
1. Use of Scanner
Function of Scanner class: can implement keyboard input data, into the program.
/* Gets an int number entered by the keyboard: int num = sc.nextInt(); Gets a string entered by the keyboard: String str = sc.next(); */ import java.util.Scanner; public class DemoScanner { public static void main(String[] args) { // 2. Create // Note: System.in represents input from the keyboard Scanner sc = new Scanner(System.in); // 3. Get the int number entered by the keyboard int num = sc.nextInt(); System.out.println("Input int The numbers are:" + num); // 4. Get the string of keyboard input String str = sc.next(); System.out.println("The string entered is:" + str); } }
2 Use of Random
The Random class is used to generate random numbers.
/* Gets a random int number (range is all range of int, plus or minus two): int num = r.nextInt() Gets a random int number (the parameter represents the range, left closed right open interval): int num = r.nextInt(3) What it actually means is: [0,3], that is, 0~2 */ import java.util.Random; public class DemoRandom { public static void main(String[] args) { Random r = new Random(); int num = r.nextInt(); System.out.println("Random numbers are:" + num); } }
3 Use of the ArrayList class
/* ArrayList Common methods are: public boolean add(E e): Add an element to the collection with the same type and generic type of parameter. The return value indicates whether the addition was successful or not. Note: For an ArrayList collection, the add add add action must be successful, so the return value is available or not needed. But for other collections (future studies), the add add action may not succeed. public E get(int index): Gets the element from the collection, the parameter is the index number, and the return value is the element at the corresponding location. public E remove(int index): Deletes an element from a collection, the parameter is the index number, and the return value is the deleted element. public int size(): Gets the dimension length of the collection, and the return value is the number of elements contained in the collection. */ public class DemoArrayListMethod { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); System.out.println(list); // [] // Add elements to the collection:add boolean success = list.add("Zhang San"); System.out.println(list); // [Zhang San] System.out.println("Is the action added successful:" + success); // true list.add("Li Si"); list.add("WangTwo"); list.add("Zhao Six"); list.add("Pseudo-ginseng"); System.out.println(list); // [Zhang San, Li Si, Wang II, Zhao VI, Tian Qi] // Get elements from a collection: get. Index values start at 0 String name = list.get(2); System.out.println("Index position 2:" + name); // WangTwo // Delete element from collection: remove. Index value starts at 0. String whoRemoved = list.remove(3); System.out.println("The people deleted are:" + whoRemoved); // Zhao Six System.out.println(list); // [Zhang San, Li Si, Wang Er, Tian Qi] // Gets the length dimension of the collection, that is, the number of elements in it int size = list.size(); System.out.println("The length of the collection is:" + size); // Traverse Set for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } }
/* If you want to store the base type data in the collection ArrayList, you must use the wrapper class corresponding to the base type. Basic type wrapper classes (reference types, wrapper classes all under the java.lang package) byte Byte short Short int Integer [Special] long Long float Float double Double char Character [Special] boolean Boolean Starting with JDK 1.5+, automatic packing and unloading are supported. Automatic packing: Basic type-->Packaging type Automatic unpacking: Packaging type-->Basic type */ import java.util.ArrayList; public class DemoArrayListBasic { public static void main(String[] args) { ArrayList<String> listA = new ArrayList<>(); // Wrong Writing! Generics can only be reference types, not base types // ArrayList<int> listB = new ArrayList<>(); ArrayList<Integer> listC = new ArrayList<>(); listC.add(100); listC.add(200); System.out.println(listC); // [100, 200] int num = listC.get(1); System.out.println("Element 1 is:" + num); } }
4 Use of String
Construction method of string
/* java.lang.String Class represents string. API It says that all string literal values (such as "abc") in a Java program are implemented as instances of this class. In fact, that is, all double quote strings in the program are objects of the String class. (Even if there's no new, it's the same.) The characteristics of strings: 1. The content of a string is never changed. [Key] 2. Strings are shared because they cannot be changed. 3. String effects are equivalent to char[] character arrays, but the underlying principle is byte[] byte arrays. Common 3+1 ways to create strings. Three construction methods: public String(): Create a blank string with nothing in it. public String(char[] array): Creates the corresponding string based on the contents of the character array. public String(byte[] array): Creates the corresponding string based on the contents of the byte array. A direct creation: String str = "Hello"; // Use double quotation marks directly to the right Note: Write double quotation marks directly, that is, the string object. */ public class DemoString { public static void main(String[] args) { // Construct with empty parameters String str1 = new String(); // Leave parentheses blank to indicate that the string has nothing. System.out.println("The first string:" + str1); // Create a string from an array of characters char[] charArray = { 'A', 'B', 'C' }; String str2 = new String(charArray); System.out.println("The second string:" + str2); // Create string from byte array byte[] byteArray = { 97, 98, 99 }; String str3 = new String(byteArray); System.out.println("The third string:" + str3); // Create directly String str4 = "Hello"; System.out.println("The fourth string:" + str4); } }
String equals uses
/* ==Is to compare the address values of the objects, and if you really need to compare the contents of the strings, you can use two methods: public boolean equals(Object obj): A parameter can be any object, and only if the parameter is a string and the content is the same will it be given true; Otherwise, it returns false. Matters needing attention: 1. Any object can be received with Object. 2. equals The method is symmetric, that is, a.equals(b) has the same effect as b.equals(a). 3. If you compare a constant with a variable on both sides, it is recommended that you write the constant string first. Recommended:'abc'. equals (str) not recommended: str.equals ('abc') public boolean equalsIgnoreCase(String str): Ignore case and compare content. */ public class DemoStringEquals { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; char[] charArray = {'H', 'e', 'l', 'l', 'o'}; String str3 = new String(charArray); System.out.println(str1.equals(str2)); // true System.out.println(str2.equals(str3)); // true System.out.println(str3.equals("Hello")); // true System.out.println("Hello".equals(str1)); // true String str4 = "hello"; System.out.println(str1.equals(str4)); // false System.out.println("================="); String str5 = null; System.out.println("abc".equals(str5)); // Recommendation: false // System.out.println(str5.equals("abc"); // Not recommended: Error, null pointer exception NullPointerException System.out.println("================="); String strA = "Java"; String strB = "java"; System.out.println(strA.equals(strB)); // false, case sensitive System.out.println(strA.equalsIgnoreCase(strB)); // true, ignoring case // Note that only the English letters are case sensitive, and the others are not. System.out.println("abc One 123".equalsIgnoreCase("abc One 123")); // false } }
Common methods of String
/* String The common methods related to acquisition are: public int length(): Get the number of characters in the string, get the length of the string. public String concat(String str): Split the current string and the parameter string into a new string for the return value. public char charAt(int index): Gets a single character at the specified index position. (The index starts at 0.) public int indexOf(String str): Finds the index position of the first occurrence of a parameter string in this string, if no -1 value is returned. */ public class DemoStringGet { public static void main(String[] args) { // Get the length of the string int length = "asdasfeutrvauevbueyvb".length(); System.out.println("The length of the string is:" + length); // Split String String str1 = "Hello"; String str2 = "World"; String str3 = str1.concat(str2); System.out.println(str1); // Hello, unchanged System.out.println(str2); // World, unchanged System.out.println(str3); // HelloWorld, new string System.out.println("=============="); // Gets a single character at the specified index position char ch = "Hello".charAt(1); System.out.println("The characters at index 1 are:" + ch); System.out.println("=============="); // Finds the first index position of a parameter string that occurs within the native string // Return a -1 value if it doesn't exist at all String original = "HelloWorldHelloWorld"; int index = original.indexOf("llo"); System.out.println("The first index value is:" + index); // 2 System.out.println("HelloWorld".indexOf("abc")); // -1 } }
String Interception Method
/* String interception method: public String substring(int index): Intercepts from the parameter position to the end of the string and returns the new string. public String substring(int begin, int end): Interception starts with begin and end s with a string in the middle. Remarks: [begin, end], including left, not right. */ public class Demo03Substring { public static void main(String[] args) { String str1 = "HelloWorld"; String str2 = str1.substring(5); System.out.println(str1); // HelloWorld, unchanged System.out.println(str2); // World, new string System.out.println("================"); String str3 = str1.substring(4, 7); System.out.println(str3); // oWo System.out.println("================"); // In the following way, the content of the string remains unchanged // There are two strings below: "Hello", "Java" // Address values are stored in strA. // The original address value was Hello's 0x666, // Later the address value became Java's 0x999 String strA = "Hello"; System.out.println(strA); // Hello strA = "Java"; System.out.println(strA); // Java } }
Common methods associated with String transformations are
/* String The common methods associated with conversion are: public char[] toCharArray(): Split the current string into an array of characters as a return value. public byte[] getBytes(): Gets the byte array at the bottom of the current string. public String replace(CharSequence oldString, CharSequence newString): Replace all the old strings that appear with new strings and return the new string as a result of the replacement. Note: CharSequence means that string types are acceptable. */ public class DemoStringConvert { public static void main(String[] args) { // Convert to character array char[] chars = "Hello".toCharArray(); System.out.println(chars[0]); // H System.out.println(chars.length); // 5 System.out.println("=============="); // Convert to Byte Array byte[] bytes = "abc".getBytes(); for (int i = 0; i < bytes.length; i++) { System.out.println(bytes[i]); } System.out.println("=============="); // Content substitution of strings String str1 = "How do you do?"; String str2 = str1.replace("o", "*"); System.out.println(str1); // How do you do? System.out.println(str2); // H*w d* y*u d*? System.out.println("=============="); String lang1 = "Will you play? Your grandfather! Your grandfather! Your grandfather!!!"; String lang2 = lang1.replace("Damn you", "****"); System.out.println(lang2); // Will it be fun!****!**!**!****!!!! } }
String Segmentation Method
/* How to split a string: public String[] split(String regex): The string is divided into parts according to the rules of the parameters. Matters needing attention: split The parameter of the method is actually a "regular expression", which you will learn later. Note today: If you are slicing by the English period'.', you must write'\.'(two backslashes) */ public class DemoStringSplit { public static void main(String[] args) { String str1 = "aaa,bbb,ccc"; String[] array1 = str1.split(","); for (int i = 0; i < array1.length; i++) { System.out.println(array1[i]); } System.out.println("==============="); String str2 = "aaa bbb ccc"; String[] array2 = str2.split(" "); for (int i = 0; i < array2.length; i++) { System.out.println(array2[i]); } System.out.println("==============="); String str3 = "XXX.YYY.ZZZ"; String[] array3 = str3.split("\\."); System.out.println(array3.length); // 0 for (int i = 0; i < array3.length; i++) { System.out.println(array3[i]); } } }
A small case of String
/* Title: Defines a method to concatenate the array {1,2,3} into a string in the specified format. The format is as follows: [word1#word2#word3]. Return value type: String Stitching format: [word1#word2#word3] Used: for loops, string splicing, a word before each array element, separating with #, distinguishing if it's the last */ public class Demo06StringPractise { public static void main(String[] args) { int[] array = {1, 2, 3, 4}; String result = fromArrayToString(array); System.out.println(result); } public static String fromArrayToString(int[] array) { String str = "["; for (int i = 0; i < array.length; i++) { if (i == array.length - 1) { str += "word" + array[i] + "]"; } else { str += "word" + array[i] + "#"; } } return str; } }
5 Static method
Once the member method is modified with static, it becomes static. Static methods do not belong to objects, but to classes.
If you do not have a static keyword, you must first create an object, then use it through the object.
If you have a static keyword, you can use it directly through the class name without creating an object.
Whether it is a member variable or a member method. If static exists, the class name is recommended for invocation.
Static variables: class names. Static variables
Static methods: class names. Static methods ()
Matters needing attention:
1 Static cannot access non-static directly.
Reason: Because there is static content in memory and non-static content in memory.
2. this cannot be used in static methods.
Reason: this represents the current object, through whom method is invoked, who is the current object.
public class MyClass { int num; // Member variables static int numStatic; // Static variable // Member Method public void method() { System.out.println("This is a member method."); // Member methods can access member variables System.out.println(num); // Member methods can access static variables System.out.println(numStatic); } // Static method public static void methodStatic() { System.out.println("This is a static method."); // Static methods can access static variables System.out.println(numStatic); // Static cannot access non-static directly // System.out.println(num); // Wrong Writing! // The this keyword cannot be used in static methods. // System.out.println(this); // Wrong Writing! } } public class DemoStaticMethod { public static void main(String[] args) { MyClass obj = new MyClass(); // Create object first // Then you can use content without the static keyword obj.method(); // For static methods, they can be called either by object name or directly by class name. obj.methodStatic(); // Correct, not recommended, this writing will also be translated by javac to "class name. static method name" after compilation MyClass.methodStatic(); // Correct, recommended // Class names can be omitted for static methods that would otherwise be myMethod(); Demo02StaticMethod.myMethod(); // Completely Equivalent } public static void myMethod() { System.out.println("Your own way!"); } }
/* The format of the static code block is: public class Class name { static { // Contents of static code blocks } } Features: When this class is first used, static code blocks execute only once. Static content always takes precedence over non-static content, so static code blocks execute first than construction methods. Typical uses of static code blocks: Used to assign static member variables at once. */ public class DemoStatic { public static void main(String[] args) { Person one = new Person(); Person two = new Person(); } } public class Person { static {System.out.println("Static code block execution!");} public Person() {System.out.println("Construction method execution!");} }
6 Use of Arrays class
/* java.util.Arrays Is an array-related tool class that provides a large number of static methods for common operations on arrays. public static String toString(Array: Turn the parameter array into a string (in the default format: [Element 1, Element 2, Element 3...]) public static void sort(Array: Sorts the elements of the array in the default ascending order (from smallest to largest). Remarks: 1. If numeric, sort defaults to ascending order from smallest to largest 2. If it is a string, sort defaults to ascending alphabetically 3. If it is a custom type, then this custom class needs to be supported by a Comparable or Comparator interface. (Learn later) */ public class DemoArrays { public static void main(String[] args) { int[] intArray = {10, 20, 30}; // Convert an int[] array to a string in the default format String intStr = Arrays.toString(intArray); System.out.println(intStr); // [10, 20, 30] int[] array1 = {2, 1, 3, 10, 6}; Arrays.sort(array1); System.out.println(Arrays.toString(array1)); // [1, 2, 3, 6, 10] String[] array2 = {"bbb", "aaa", "ccc"}; Arrays.sort(array2); System.out.println(Arrays.toString(array2)); // [aaa, bbb, ccc] } } /* Use the Arrays related API to sort all the characters in a random string in ascending order and print them in reverse order. */ public class Demo02ArraysPractise { public static void main(String[] args) { String str = "asv76agfqwdfvasdfvjh"; // How to sort in ascending order: // Must be an array to use the Arrays.sort method // String --> Array, using toCharArray char[] chars = str.toCharArray(); Arrays.sort(chars); // Array of characters in ascending order // Need to traverse in reverse order for (int i = chars.length - 1; i >= 0; i--) { System.out.println(chars[i]); } }
/* java.util.Math Class is a mathematical-related tool class, which provides a large number of static methods to complete operations related to mathematical operations. public static double abs(double num): Gets the absolute value. There are multiple overloads. public static double ceil(double num): Round up. public static double floor(double num): Round down. public static long round(double num): Rounding. Math.PI Represents an approximate circumference constant (double). */ public class DemoMath { public static void main(String[] args) { // Get absolute value System.out.println(Math.abs(3.14)); // 3.14 System.out.println(Math.abs(0)); // 0 System.out.println(Math.abs(-2.5)); // 2.5 System.out.println("================"); // ceil System.out.println(Math.ceil(3.9)); // 4.0 System.out.println(Math.ceil(3.1)); // 4.0 System.out.println(Math.ceil(3.0)); // 3.0 System.out.println("================"); // Round down, wipe out System.out.println(Math.floor(30.1)); // 30.0 System.out.println(Math.floor(30.9)); // 30.0 System.out.println(Math.floor(31.0)); // 31.0 System.out.println("================"); System.out.println(Math.round(20.4)); // 20 System.out.println(Math.round(10.5)); // 11 } } /* How many integers with absolute values greater than 6 or less than 2.1 are calculated between -10.8 and 5.9? */ public class Demo04MathPractise { public static void main(String[] args) { int count = 0; // Quantity that meets the requirements double min = -10.8; double max = 5.9; // In this way, variable i is all the integers in the interval for (int i = (int) min; i < max; i++) { int abs = Math.abs(i); // absolute value if (abs > 6 || abs < 2.1) { System.out.println(i); count++; } } System.out.println("Total:" + count); // 9 } }
7 Use of Object classes
The java.lang.Object class is the root class in the Java language, the parent class of all classes. All method subclasses described in it can be used. When an object is instantiated, the parent that is ultimately found is Object.
public String toString(): Returns the string representation of the object.
The toString method returns a string representation of the object whose content is the object's type +@+ memory address value.
Because the result returned by the toString method is a memory address, it is often necessary to get the corresponding string representation according to the object's properties in development, so it needs to be overridden as well.
public class DemoToString{ public static void main(String[] args) { /* Person Classes inherit Object classes by default, so you can use the toString method in the Object class String toString() Returns the string representation of the object. */ Person p = new Person("Zhang San",18); String s = p.toString(); System.out.println(s);//com.demo.Object.Person@75412c2f | abc | Person{name=Zhang San, age=18} //Printing the name of an object directly means calling the object toString p=p.toString(); System.out.println(p);//com.demo.Object.Person@5f150435 | abc | Person{name=Zhang San, age=18} Random r = new Random(); //To see if a class overrides a toString, print the object of the class directly, or print the address value of the object if the toString method is not overridden System.out.println(r);//java.util.Random@3f3afe78 No override of toString method Scanner sc = new Scanner(System.in); System.out.println(sc);//java.util.Scanner[delimiters=\p{javaWhitespace}+..Overrides the toString method ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); System.out.println(list);//[1, 2, 3] Override toString method } } public class Person { private String name; private int age; public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } /* Printing the address value of an object directly is meaningless and the toString method in the Object class needs to be overridden Print object properties (name,age) */ /*@Override public String toString() { //return "abc"; return "Person{name="+name+" ,age="+age+"}"; }*/ /*@Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; }*/ @Override public int hashCode() {return Objects.hash(name, age);} 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 boolean equals(Object obj): Indicates whether another object is "equal" to this object.
If you call the member method equals and specify the parameter as another object, you can tell if the two objects are the same. There are two ways to "same" here, default and custom.
public class DemoEquals { public static void main(String[] args) { /* Person Classes inherit Object classes by default, so you can use the equals method of the Object class boolean equals(Object obj) Indicates whether another object is "equal" to this object. equals Method Source: public boolean equals(Object obj) { return (this == obj); } Parameters: Object obj:Any object can be passed == Comparison operator, returns a Boolean value of true false Basic data type: Values are compared Reference data type: The ratio is the address value of two objects this Who is it? That object calls the method in which this is the object; equals method called by p1 so this is p1 obj Who is it? Parameter p2 passed in this==obj -->p1==p2 */ Person p1 = new Person("Dili Reba",18); //Person P2 = new Person (Gulinaza, 19); Person p2 = new Person("Dili Reba",18); System.out.println("p1:"+p1);//p1:com.itheima.demo01.Object.Person@58ceff1 System.out.println("p2:"+p2);//p2:com.itheima.demo01.Object.Person@7c30a502 //p1=p2; // Assign the address value of P2 to p1 ArrayList<String> list = new ArrayList<>(); boolean b = p1.equals(p1); System.out.println(b); } } public class Person { private String name; private int age; public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } /*@Override public boolean equals(Object obj) { //Increase a judgment, pass parameter obj if this is itself, return true directly, improve the efficiency of the program if(obj==this){ return true; } //Increase a judgment, pass parameter obj if null, return false directly, improve the efficiency of the program if(obj==null){ return false; } //Add a judgment to prevent type conversion from happening once if(obj instanceof Person){ //Convert obj to Person type using downward transition Person p = (Person)obj; //Compare the properties of two objects, one is this(p1) and the other is p (obj->p2) boolean b = this.name.equals(p.name) && this.age==p.age; return b; } //Not Person type returns false directly return false; }*/ @Override public int hashCode() {return Objects.hash(name, age);} 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;} }
An Objects tool class was added to JDK7, which provides methods for manipulating objects. It consists of static, practical methods, such as null-save (null pointer safe) or null-tolerant (null pointer tolerant), which computes the hashcode of an object, returns a string representation of an object, and compares two objects.
When comparing two objects, the Object's equals method tends to throw null pointer exceptions, which are optimized by the equals method in the Objects class. The method is as follows: public static boolean equals(Object a, Object b): Determine if two objects are equal.
public class DemoObjects { public static void main(String[] args) { String s1 = "abc"; //String s1 = null; String s2 = "abc"; //boolean b = s1.equals(s2); // NullPointerException null is a method that cannot be called and will throw a null pointer exception //System.out.println(b); /* Objects Class equals method: Compare two objects to prevent null pointer exceptions public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); } */ boolean b2 = Objects.equals(s1, s2); System.out.println(b2); } }
8 Date usage
Construction method of Date class
import java.util.Date; public class DemoDate { public static void main(String[] args) { demo03(); } /* long getTime() Convert the date to a millisecond value (equivalent to the System.currentTimeMillis() method) Returns the number of milliseconds represented by this Date object since 100:00:00 GMT on January 1, 1970. */ private static void demo03() { Date date = new Date(); long time = date.getTime(); System.out.println(time);//3742777636267 } /* Date Class construction with parameters Date(long date) :Pass in milliseconds to convert milliseconds to Date date */ private static void demo02() { Date date = new Date(0L); System.out.println(date);// Thu Jan 01 08:00:00 CST 1970 date = new Date(3742767540068L); System.out.println(date);// Sun Aug 08 09:39:00 CST 2088 } /* Date Empty parameter construction methods for classes Date() Get the date and time of the current system */ private static void demo01() { Date date = new Date(); System.out.println(date);//Sun Aug 08 12:23:03 CST 2088 } }
Methods in the DateFormat class
public class DemoDateFormat { public static void main(String[] args) throws ParseException { demo02(); } /* Parse the text to a date using the method parse in the DateFormat class Steps to use: 1.Creates a SimpleDateFormat object, passing the specified pattern in the construction method 2.Call the method parse in the SimpleDateFormat object to parse the string that matches the pattern in the construction method to the Date date Be careful: public Date parse(String source) throws ParseException parse Method declares an exception called ParseException If the pattern of the string and the constructor is different, the program will throw this exception Calling a method that throws an exception requires that the exception be handled, either throws continue to throw the exception, or try catch handles it itself */ private static void demo02() throws ParseException { //1. Create a SimpleDateFormat object and pass the specified pattern in the construction method SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH time mm branch ss second"); //2. Call the method parse in the SimpleDateFormat object to parse the string that matches the pattern in the construction method into a Date date //Date parse(String source) parses a pattern-compliant string into a Date date Date date = sdf.parse("2088 08/08/15:51 min 54 seconds"); System.out.println(date); } /* Format the date as text using the method format in the DateFormat class Steps to use: 1.Creates a SimpleDateFormat object, passing the specified pattern in the construction method 2.Call the method format in the SimpleDateFormat object to format the Date date as a pattern-compliant string (text) according to the pattern specified in the construction method */ private static void demo01() { //1. Create a SimpleDateFormat object and pass the specified pattern in the construction method SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH time mm branch ss second"); //2. Call the method format in the SimpleDateFormat object to format the Date date as a pattern-compliant string (text) according to the pattern specified in the construction method //String format(Date date) Formats the Date date as a pattern-compliant string in the specified pattern Date date = new Date(); String d = sdf.format(date); System.out.println(date);//Sun Aug 08 15:51:54 CST 2088 System.out.println(d);//08, 2088 15:51 min 54 seconds } }
Common member methods of the Calendar class
import java.util.Calendar; import java.util.Date; /* Calendar Common member methods for classes: public int get(int field): Returns the value of a given calendar field. public void set(int field, int value): Set the given calendar field to the given value. public abstract void add(int field, int amount): Adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar. public Date getTime(): Returns a Date object representing this Calendar time value from the epoch to the current millisecond offset. Parameters for member methods: int field:Calendar class field, which can be obtained using the static member variable of the Calendar class public static final int YEAR = 1; year public static final int MONTH = 2; month public static final int DATE = 5; One day of the month public static final int DAY_OF_MONTH = 5;One day of the month public static final int HOUR = 10; time public static final int MINUTE = 12; branch public static final int SECOND = 13; second */ public class DemoCalendar { public static void main(String[] args) { demo04(); } /* public Date getTime(): Returns a Date object representing this Calendar time value from the epoch to the current millisecond offset. Convert Calendar Object to Date Object */ private static void demo04() { //Getting a Calendar object using the getInstance method Calendar c = Calendar.getInstance(); Date date = c.getTime(); System.out.println(date); } /* public abstract void add(int field, int amount): Adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar. Increases/decreases the specified value for the specified field Parameters: int field:Pass the specified calendar field (YEAR,MONTH...) int amount:Increase/decrease specified value Positive number: increase Negative number: decrease */ private static void demo03() { //Getting a Calendar object using the getInstance method Calendar c = Calendar.getInstance(); //Add 2 years to the year c.add(Calendar.YEAR,2); //Reduce months by 3 months c.add(Calendar.MONTH,-3); int year = c.get(Calendar.YEAR); System.out.println(year); int month = c.get(Calendar.MONTH); System.out.println(month);//West Month 0-11 East: 1-12 //int date = c.get(Calendar.DAY_OF_MONTH); int date = c.get(Calendar.DATE); System.out.println(date); } /* public void set(int field, int value): Set the given calendar field to the given value. Parameters: int field:Pass the specified calendar field (YEAR,MONTH...) int value:The value set to the specified field */ private static void demo02() { //Getting a Calendar object using the getInstance method Calendar c = Calendar.getInstance(); //Set year to 9999 c.set(Calendar.YEAR,9999); //Set month to September c.set(Calendar.MONTH,9); //Setup Day 9 c.set(Calendar.DATE,9); //Also set the year, month and day, you can use set's overload method c.set(8888,8,8); int year = c.get(Calendar.YEAR); System.out.println(year); int month = c.get(Calendar.MONTH); System.out.println(month);//West Month 0-11 East: 1-12 int date = c.get(Calendar.DATE); System.out.println(date); } /* public int get(int field): Returns the value of a given calendar field. Parameter: Pass the specified calendar field (YEAR,MONTH...) Return value: The specific value represented by the calendar field */ private static void demo01() { //Getting a Calendar object using the getInstance method Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); System.out.println(year); int month = c.get(Calendar.MONTH); System.out.println(month);//West Month 0-11 East: 1-12 //int date = c.get(Calendar.DAY_OF_MONTH); int date = c.get(Calendar.DATE); System.out.println(date); }
9 Use of StringBuilder
Construction method of StringBuilder
/* java.lang.StringBuilder Class: String buffer, which improves string efficiency Construction method: StringBuilder() Constructs a string generator without any characters, which has an initial capacity of 16 characters. StringBuilder(String str) Constructs a string generator and initializes it to the specified string content. */ public class DemoStringBuilder { public static void main(String[] args) { //Empty parameter construction method StringBuilder bu1 = new StringBuilder(); System.out.println("bu1:"+bu1);//bu1:"" //Constructing methods with strings StringBuilder bu2 = new StringBuilder("abc"); System.out.println("bu2:"+bu2);//bu2:abc } }
Common methods of StringBuilder
/* StringBuilder Common methods: public StringBuilder append(...): Add a string of any type of data and return the current object itself. */ public class DemoStringBuilder { public static void main(String[] args) { //Create StringBuilder Object StringBuilder bu = new StringBuilder(); //Add data to StringBuilder using the append method //The append method returns this, the object Bu calling the method, this==bu //StringBuilder bu2 = bu.append("abc"); // Assign bu's address to bu2 //System.out.println(bu);//"abc" //System.out.println(bu2);//"abc" //System.out.println(bu==bu2);// Address true is compared //There is no need to receive a return value using the append method // bu.append("abc"); // bu.append(1); // bu.append(true); // bu.append(8.8); // bu.append('medium'); // System.out.println(bu);// In abc1true8.8 /* Chain programming: Method return value is an object and method calls can continue */ System.out.println("abc".toUpperCase().toLowerCase().toUpperCase().toLowerCase()); bu.append("abc").append(1).append(true).append(8.8).append('in'); System.out.println(bu);//In abc1true8.8 } }
Conversion of StringBuilder and String
/* StringBuilder And String can convert to each other: String->StringBuilder:You can use the StringBuilder construction method StringBuilder(String str) Constructs a string generator and initializes it to the specified string content. StringBuilder->String:You can use the toString method in StringBuilder public String toString(): Converts the current StringBuilder object to a String object. */ public class DemoStringBuilder { public static void main(String[] args) { //String->StringBuilder String str = "hello"; System.out.println("str:"+str); StringBuilder bu = new StringBuilder(str); //Add data to StringBuilder bu.append("world"); System.out.println("bu:"+bu); //StringBuilder->String String s = bu.toString(); System.out.println("s:"+s); } }
10 Basic types of data and packaging classes
Construction Method of Packaging Class
/* Boxing: Package basic types of data into packaging classes (basic types of data - > packaging classes) Construction method: Integer(int value) Constructs a newly assigned Integer object that represents the specified int value. Integer(String s) Constructs a newly assigned Integer object that represents the int value indicated by the String parameter. The string passed must be of the basic type, otherwise the exception "100" is thrown correctly "a" is thrown Static method: static Integer valueOf(int i) Returns an Integer instance that represents the specified int value. static Integer valueOf(String s) Returns an Integer object that holds the value of the specified String. Unpacking: Take out the basic type of data in the packaging class (packaging class - > basic type of data) Membership method: int intValue() Returns the value of the Integer in type int. */ public class DemoInteger { public static void main(String[] args) { //Boxing: Package basic types of data into packaging classes (basic types of data - > packaging classes) //Construction method Integer in1 = new Integer(1);//There is a horizontal line on the method indicating that it is out of date System.out.println(in1);//1 Overrides the toString method Integer in2 = new Integer("1"); System.out.println(in2);//1 //Static method Integer in3 = Integer.valueOf(1); System.out.println(in3); //Integer in4 = Integer.valueOf("a");//NumberFormatException number formatting exception Integer in4 = Integer.valueOf("1"); System.out.println(in4); //Unpacking: Take out the basic type of data in the packaging class (packaging class - > basic type of data) int i = in1.intValue(); System.out.println(i); } }
Conversion between automatic packing and automatic unpacking
import java.util.ArrayList; /* Auto-boxing and auto-unboxing: automatic conversion between basic types of data and packaging classes JDK1.5 New features that follow */ public class DemoIneger { public static void main(String[] args) { /* Auto-boxing: Packaging classes that assign integers of type int directly Integer in = 1; Is equivalent to Integer in = new Integer(1); */ Integer in = 1; /* Auto-unboxing: in is a wrapper class and cannot directly participate in operations. It can be automatically converted to basic data types for calculation in+2;Is equivalent to in.intVale() + 2 = 3 in = in.intVale() + 2 = 3 Another automatic packing */ in = in+2; ArrayList<Integer> list = new ArrayList<>(); /* ArrayList Collections cannot store integers directly, they can store Integer wrapper classes */ list.add(1); //-->Auto-packing list.add(new Integer(1)); int a = list.get(0); //-->Auto-unboxing list.get(0).intValue(); } }
Conversion between base type and string type
/* Conversion between base types and string types Basic Type - > String 1.Value of the basic type + "" The easiest way to do this (commonly used in work) 2.The static method toString (parameter) of the wrapper class is not a toString() overload of the Object class static String toString(int i) Returns a String object that represents a specified integer. 3.String Class static method valueOf (parameter) static String valueOf(int i) Returns the string representation of the int parameter. String - > Basic Type Use the static method parseXXX("string") of the wrapper class; Integer Class: static int parseInt(String s) Double Class: static double parseDouble(String s) */ public class DemoInteger { public static void main(String[] args) { //Basic Type - > String int i1 = 100; String s1 = i1+""; System.out.println(s1+200);//100200 String s2 = Integer.toString(100); System.out.println(s2+200);//100200 String s3 = String.valueOf(100); System.out.println(s3+200);//100200 //String - > Basic Type int i = Integer.parseInt(s1); System.out.println(i-10); int a = Integer.parseInt("a");//NumberFormatException System.out.println(a); } }