Java
Basics
input data
public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Please enter:") int number = sc.nextInt(); }
private keyword
- Avoid modifying member variables by other classes
- Is a permission modifier
- You can modify members (member variables and member methods)
- The function is to protect members from being used and modified by other classes. Members modified by private can only be accessed in this class
- Used by other classes to provide corresponding operations
- The "get variable name ()" method is provided to obtain the value of the member variable. The method is decorated with public
- The set variable name (parameter) method is provided to set the value of the member variable. The method is decorated with public
public class Student{ String name; // Can be used in other classes private int age; // It cannot be used unless the set\get() method is used; it is as follows: public void setAge(int a){ if(a < 0 || a > 120){ System.out.println("The age to be modified is incorrect") }else{ age = a; } } public void getAge(){ return a; } // When the method in the object is, static is not added public void show(){ System.out.println(name+","+age) } } public class StudentDome{ public static void main(String[] args){ Student s = new Student(); s.name = "Jarry"; // It can be modified directly without modification s.setAge(-30); // The value can be modified s.show(); } }
Traversal string
- Public char charat (int index);: returns the char value at the specified index, and the index of the string starts from 0
- public int length(): returns the length of the secondary string
public class Hello{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Please enter a string") String line = sc.nextLine() for(int i = 0;i < line.length();i ++){ System.out.println(line.charAt(i)); } } }
ArrayList collection
-
ArrayList collection method
Extensions
// Demo file public class Demo{ public static void main(String[] args){ int age = 35; Fu f = new Fu(); f.speak(); // 40 Zi z = new Zi(); z.show(); // 30 z.speak(); // The subclass calls the method 40 of the parent class } } // Zi.java file public class Zi extends Fu{ public int age = 25; public Zi(){ super(); // It's added by default. You don't have to write it manually System.out.println("Zi Nonparametric construction method in"); } public Zi(int age){ super(14); // It is added by default. You don't need to write it manually unless you pass a parameter System.out.println("Zi Constructor with parameters in") } public void show(){ int age = 30; // Access the member variable age in the method System.out.println(age); // 30 // Access the member variable age in this class System.out.println(this.age); // 25 // Access the member variable age of the parent class Systme.out.println(super.age); // 40 } } // Fu.java file public class Fu{ public int age = 40; public Fu(){} // Nonparametric construction method public Fu(int age){ // Structural method with parameters System.out.println("fu The constructor with parameters in is called"); } public void speak(){ System.out.println(age) // 40 } }
Access characteristics of construction methods in inheritance
- Before subclass initialization, complete the initialization of parent class data
- The first statement of each subclass constructor is super() by default
- If there are no parameterless constructors in the parent class, but only parameterless constructors, an error will occur
- ① Use the super keyword to get the parameter constructor of the calling parent class displayed
- ② Provide a parameterless constructor in the parent class
package
New package
Modifier
Permission modifier
public class Person{ private void show1(){} protected void show2(){} void show3(){} public void show4(){} }
Modifier | In the same class | Subclass independent class in the same package | Subclasses of different packages | Unrelated classes of different packages |
---|---|---|---|---|
private | √ | |||
default | √ | √ | ||
protected | √ | √ | √ | |
public | √ | √ | √ | √ |
protected
-
Definition: protected is protected by the package in which the class is located.
-
Scope: members modified by protected can be accessed by all classes in the same package. Meanwhile, members modified by protected can also be inherited by all subclasses of this class. (Note: this means that subclasses in the same package or different packages can be accessed)
- Subclasses and base classes are in the same package: variables, methods and constructors declared as protected can be accessed by any other class in the same package;
- The subclass is not in the same package as the base class: in the subclass, the subclass instance can access the protected method inherited from the base class, but not the protected method of the base class instance.
final
- Final keyword is the final meaning. It can modify member methods, member variables and classes
- characteristic
- Decoration method: table name. This method is the final method and cannot be overridden
- Decorated variable: the table name variable is a constant and cannot be assigned again
static
- Static means static. It can modify member methods and member variables
package com.item; public class Student{ public static String name; public int age; public void show(){ System.out.println(name+","+age) } } package com.item; public class Demo{ public static void main(String[] args){ Student.name = "Jarry"; // Default shared member variable Student s = new Student(); s.age = 12; s.show(); // Jarry,12 Student s2 = "John"; s2.age = 15; s2.show(); // Jarry,15 } }
polymorphic
- Object polymorphism: the reference of the parent class points to the object of the child class
// public class Man extends Person{} Person p1 = new Man();
-
Use of polymorphism: virtual method calls
-
With the polymorphism of the object, only the declared methods in the parent class can be called at compile time. At run time, the actual execution is the method of the child class overriding the parent class.
// Demo public class Demo{ public static void main(String[] args){ Person m1 = new Man(); // polymorphic m1.eat(); // The man is eating! m1.walk(); // It is not declared (defined) in the parent class and cannot be called } } // Parent class public class Person{ private String name; private int age; public Person(){}; public Person(String name,int age){ this.name = name; this.age = age; } public void eat(){ System.out.println("The person is eating!"); } public void setName(String name){ this.name = name; } public void setAge(int age){ this.age = age; } public String getName(){ return name; } public int getAge(){ return age; } } // Subclass public class Man extends Person{ // Nonparametric structure public Man(){}; // Parametric structure public Man(String name,int age){ super(name,age); } // Subclass private method (cannot be called when polymorphic) public void walk(){ System.out.println("The man is walking!") } // Superclass method override @Override public void eat(){ System.out.println("The man is eating!") } }
-
-
Use premise of polymorphism
- ① Class inheritance
- ② Method override
- ③ Applies only to methods, not attributes
abstract class
public class Demo{ public static void main(){ Animal n1 = new Animal(); n1.eat(); // Error reporting, no Animal n2 = new Cat(); n2.eat(); // If it is an abstract method, it can only be defined with polymorphism, and then it can be called after subclass rewriting } } // Abstract class [abstract classes can have concrete methods or no abstract methods; however, abstract methods can only be defined in abstract classes] public abstract class Animal{ // Abstract method public abstract void eat(); // Note: method content cannot be written public void sleep(){ System.out.println("The animal is sleeping!"); } } // Subclass // Subclasses of abstract classes need to override methods in abstract classes // Or subclasses are abstract classes public class Cat extends Animal{ @Override public void eat(){ System.out.println("Subclasses override the of the parent class eat method") } }
Interface
Characteristics of interface
-
The interface is decorated with the keyword interface
public interface Interface name {}
-
When subclasses inherit interfaces, they are represented by implements (not extensions)
public class Class name implements Interface name {}
-
The variables in the interface are constants (final) of the default static modifier and cannot be modified
-
Multiple interfaces can also be implemented in a class
- Syntax: publi class name implements interface 1, interface 2 {}
-
Default modifier: public static final
public interface Inter{ public int num = 10; public static final int num3 = 30; // The variable in the interface defaults to this type and can be replaced by the following code int num3 = 30; // It can be replaced by code and is a static constant that cannot be modified public abstract void eat(); // Abstract method void play(); // This can also be written in the interface. The default is public abstract void play(); public void play(){System.out.println("jjjjj"); } // Error, no concrete method can be written in the interface (only abstract methods can exist) } // Subclass public abstract class ZiInterface extends Object implements Inter{ // Extensions object is the default. If there is no parent class, it can be omitted. Don't forget abstract @Override // Must override public void eat(){ System.out.println("The things is eating!") } } // Demo public class Demo{ public static void main(String[] args){ Inter interDemo = new ZiInterface(); interDemo.eat(); // The things is eating! } }
-
Inner class
- First kind
// Outer class public class Outer{ private int num = 239; public void method(){ class Inter{ public void show(){ System.out.pritln(num); } } Inter i = new Inter(); i.show(); } } // Demo public class Demo{ public static void main(String[] args){ Outer o = new Outer(); o.method(); // 239 } }
-
Second
public class Outer{ private int num = 34; public class Inter{ public void show(){ System.out.println(num); } } public void method(){ Inter i = new Inter(); i.show(); } } // Demo public class Demo{ public static void main(String[] args){ Outer o = new Outer(); o.method(); } }
-
Anonymous Inner Class
// Interface Inter public interface Inter{ int age = 53; void show(); } // Outer public class Outer{ public void method(){ new Inter(){ @Override public void show(){ System.out.println(age); // 53 System.out.println("The niming is running!") } }.show(); // There is a second way to write when multiple overridden methods in an anonymous class are called // Inter i = new Inter(){ // @Override // public void show(){ // System.out.println(age); // } // }; // i.show(); // 53 // i.show(); // 53 } } // Demo public class Demo{ public static void main(String[] args){ Outer o = new Outer(); o.method(); // 53 // The niming is running! } }
Bubble sorting
public class Demo{ public static void main(String[] args) { int[] arr = {55,36,93,59,29}; // System.out.println(Arrays.toString(arr)); / / the first (using the toString method in the Array class) System.out.println("Before sorting"+arrayTostring(arr)); // The second (traversal and conversion to string) zhuan(arr); // The array transferred to the past is still the arr in the previous {} System.out.println("After sorting"+arrayTostring(arr)); } // Arrays cannot be printed directly // If you want to print, you need to traverse to the string type; otherwise, it is the first address of the array public static String arrayTostring(int[] arr){ StringBuilder bu = new StringBuilder(); bu.append("["); for(int i = 0;i < arr.length;i ++){ if(i == arr.length - 1){ bu.append(arr[i]); }else{ bu.append(arr[i]).append(", "); } } bu.append("]"); String s = bu.toString(); return s; } public static void zhuan(int[] arr){ for(int i = 0;i < arr.length-1;i ++) { for (int j = 0; j < arr.length - 1 - 0; j++) { int temp; if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } }
Arrays class
Method name | explain |
---|---|
public static String toString(int[] a) | Returns a string representation of the contents of the specified array |
public static void sort(int[] a) | Arranges the specified array in numerical order (sort) |
public static void main(String[] args){ int[] arr = {43,543,23,56,6}; System.out.println("Before sorting:"+ Arrays.toString(arr)); // [43, 543, 23, 56, 6] Arrays.sort(arr); System.out.println("After sorting:"+ Arrays.toString(arr)); // [6, 23, 43, 56, 543] }
Basic type wrapper class (int and String are interchangeable)
Date tool class
Case (how many days are there in February of any year)
public class Demo{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter the year:"); int year = sc.nextInt(); Calendar d = Calendar.getInstance(); // Set year, month and day of calendar object d.set(year,2,1); // March 1 is the last day of February d.add(Calendar.DATE,-1); // Just get this day int date = d.get(Calendar.DATE); System.out.println(year+"In February"+date+"day"); } }
abnormal
Custom exception handling (case)
// ScoreException.java file public class ScoreException extends Exception{ public ScoreException(){} public ScoreException(String message){ super(message); } } // Teacher.java file public class Teacher { public void checkScore(int score) throws ScoreException { if(score < 0 || score > 100){ throw new ScoreException("Please enter 0-100 Number between"); }else { System.out.println("The score is normal"); } } } // Demo.java file public class Demo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter your grade:"); int score = sc.nextInt(); Teacher t = new Teacher(); try { t.checkScore(score); } catch (ScoreException e) { e.printStackTrace(); } } }
Collection collection
Collection collection common methods
Method name | explain |
---|---|
boolean | Add element |
boolean remove(Object o) | Removes the specified element from the collection |
void clear() | Empty elements in collection |
boolean contains(Object o) | Determines whether the specified element exists in the collection |
boolean isEmpty() | Determine whether the collection is empty |
int size() | The length of the set, that is, the number of elements in the set |
-
case
package Collection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class StudentDemo { public static void main(String[] args) { Student s1 = new Student("Jarry",23); Student s2 = new Student("John",12); Student s3 = new Student("Zip",13); Collection<Student> c =new ArrayList<Student>(); c.add(s1); c.add(s2); c.add(s3); // iterator Iterator<Student> it = c.iterator(); while(it.hasNext()){ Student s = it.next(); System.out.println("Age:"+s.getAge()+", full name:"+s.getName()); } } }
List collection
List collection specific methods
-
case
- Traverse the List collection. If there is a "world" element, add a "test" element
public class Demo{ public static void main(String[] args){ List<String> li = new ArrayList<String>(); li.add("Hello"); li.add("world"); li.add("Java"); /* // iterator Iterator<String> it = li.iterator(); while(it.hasNext()){ String s = it.next(); This step will increase the actual number of times by 1 if(s.equals("world")){ li.add("test"); } } */ // Error message: /* Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997) at Collection.StudentDemo.main(StudentDemo.java:35) */ // Error (check the source code, in which the expected modification times are inconsistent with the actual modification times, so an error is reported) // improvement: for(int i = 0;i < li.size();i ++){ String s = li.get(i); if(s.equals("world")){ li.add("test"); } } // Enhanced for /* for(String s : li){ if(s.equals("world")){ li.add("test"); } } */ } System.out.println(li); // [Hello, world, Java, test] }
Set set
-
characteristic:
- A collection that does not contain duplicate elements
- There is no indexed method, so you can't use a normal for loop to traverse
public static void main(String[] args){ Set<String> set = new HashSet<String>(); set.add("Jarry"); set.add("John"); for(String s :set){ Systme.out.println(s); /* Output: (different order) John Jarry */ } }
-
Hash value
-
It is a numeric value of type int calculated by JDK according to the address or string or number of the object
-
There is a method in the Object class to get the hash value of the Object
-
public int hashCode(): returns the hash value of an object (the hash value of the same object is the same, and different hash values are different)
Student s = new Student("jarry",12); System.out.println(s.hashCode); // 1060830840 (hash value)
-
LinkedHashSet collection overview and features
-
The Set interface implemented by hash table and linked list has predictable iteration order
-
The order of elements is guaranteed by the linked list, that is, the storage and extraction order of elements are consistent
-
The hash table ensures that the elements are unique, that is, there are no duplicate elements
public static void main(String[] args){ LinkedHashSet<String> link = new LinkedHashSet<String>(); link.add("hello"); link.add("world"); for(String s : link){ System.out.println(s); } /* Output: (same order) hello world */ }
-
TreeSet set (Comparator)
-
Elements are ordered and sorted according to certain rules. The specific sorting method depends on the construction method
- TreeSet(): sort according to the natural order of its elements
- TreeSet (comparator): sort according to the specified comparator
-
There is no indexed method, so you can't use a normal for loop to traverse
-
A collection that does not contain duplicate elements because it is a Set collection
-
Use case of natural sorting Comparable
-
Store and traverse the student object, create a TreeSet collection, and use the parameterless construction method
-
Requirements: sort by age from small to large. If the age is the same, sort by i name alphabetically
- To call a Comparable interface and override a sort method
// Student package TreeSet; public class Student implements Comparable<Student> { private int age; private String name; public Student(){} public Student(String name,int age){ this.name = name; this.age = age; } public void setAge(int age){ this.age = age; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public String getName(){ return name; } @Override public int compareTo(Student s) { // return 0; // Only the first one can be returned // return 1; // Ascending arrangement // return -1; // Descending order // Sorted by age int num = this.age - s.age; return num; } } // Demo package TreeSet; import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { Student s3 = new Student("Jarry",34); Student s1 = new Student("John",15); Student s2 = new Student("Zip",18); TreeSet<Student> t = new TreeSet<Student>(); t.add(s3); t.add(s1); t.add(s2); System.out.println("Sorted by age:"); for(Student s : t){ System.out.println("Age:"+s.getAge()+", full name:"+s.getName()); } } }
-
-
Use of Comparator comparator
-
The user-defined objects are stored in the treeSet collection. The construction method with parameters uses comparator sorting to sort the elements
-
Comparator sorting is to make the collection construction method accept the implementation class object of comparator and override the compare (To1,To2) method
public static void main(String[] args){ TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){ @Override public int compare(Student s1,Student s2){ int num = s1.getAge() - s2.getAge(); // If the age is the same, sort by name int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num; return num2; } }); Student s3 = new Student("Jarry",34); Student s1 = new Student("John",15); Student s2 = new Student("Zip",18); TreeSet<Student> t = new TreeSet<Student>(); t.add(s3); t.add(s1); t.add(s2); System.out.println("Sorted by age:"); for(Student s : t){ System.out.println("Age:"+s.getAge()+", full name:"+s.getName()); } /* Output results: Sorted by age: Age: 15, name: John Age: 18, name: Zip Age: 34, name: Jarry */ }
-
-
case
-
Generate 10 random numbers between 1-20 and add them to the set
public static void main(String[] args){ Set<Integer> set = new HashSet<Integer>(); // The generated random numbers are out of order Set<Integer> set = new TreeSet<Integer>(); // The resulting random numbers are sorted // Create random number object Random r = new Random(); // Judge whether the length of the set is less than 10 while(set.size()<10){ // Generates a random number and adds it to the collection int number = r.nextInt(20) + 1; // Numbers in brackets represent numbers between 1 and 20 set.add(number); } for(Integer I : set){ System.out.println(i); } }
-
generic paradigm
// Generic.java /* The first representation: public class Generic <T>{ public T getT(){ return t; } public void setT(T t){ this.t = t; } } */ // Second: public class Generic { public <T> void show(T t){ System.out.println(t); } } // Demo public class Demo{ public static void main(String[] args){ Generic g = new Generic(); g.show("Hello"); g.show(23); g.show(true); g.show(12.34); } }
Type wildcard
Variable parameters
Math set
public class Demo{ public static void main(String[] args){ // Data is unique Map<String,String> map = new HashMap<String,String>(); map.put("hello","world"); System.out.println(map); // {Hello=world} } }
-
Basic functions of Map collection
Method name explain V put(K key,V value) Add element V remove(Object key) Delete value pair elements according to key void clear() Remove all key value pair elements boolean containsKey(Object key) Determines whether the collection contains the specified key boolean containsValue(Object key) Determines whether the specified value is included boolean isEmpty() Determine whether the collection is empty int size() The length of the set, that is, the number of key value pairs in the set public static void main(String[] args) { Map<String,String> map = new HashMap<String,String>(); map.put("Hello","World"); map.put("Map","HashMap"); System.out.println(map); // {Hello=World, Map=HashMap} System.out.println(map.remove("Hello")); // World System.out.println(map.remove("Test")); // null System.out.println(map); // {Map=HashMap} System.out.println(map.containsKey("Map")); // true map.clear(); System.out.println(map); // {} System.out.println(map.containsKey("Map")); // false }
-
Get function of Map collection
public static void main(String[] args) { Map<String,String> map = new HashMap<String,String>(); map.put("Hello","World"); map.put("Map","HashMap"); // get(Object key): get the value according to the key System.out.println(map.get("Hello")); // World // Set < k > keyset(): get the set of all keys Set<String> keySet = map.keySet(); for(String key : keySet){ System.out.println(key); // Hello Map } // Collection < V > values(): get the collection of all values Collection<String> values = map.values(); for(String value : values){ System.out.println(value); // World HashMap } }
-
File class
public class myFile{ public static void main(String[] args){ File f1 = new File("myFile\\java.txt"); // Delete the java.txt file in the current module directory System.out.println(f1.delete()); // true // Create the itcast directory under the current module System.out.println(f1.mkdir()); // true // Delete the itcast directory under the current module directory System.out.println(f1.delete()); // true // Create a directory itcast under the current module, and then create a file java.txt in this directory File f3 = new File("myFile\\itcast"); System.out.println(f3.mkdir()); // true File f4 = new File("myFile\\itcast\\java.txt"); System.out.println(f4.createNewFile()); // true } }
recursion
- Basic case
public class DiGui{ public static void main(String[] args){ // For the undead rabbit problem, find the logarithm of the rabbit in the 20th month // Number of rabbits per month: 1,1,2,3,5,8 int[] arr = new int[20]; arr[0] = 1; arr[1] = 1; for(int i = 2;i < arr.length; i++){ arr[i] = arr[i - 1] + arr[i - 2]; } System.out.println(arr[19]); // 6765 // Recursive Method f(20); // 6765 } public static int f(n){ if(n == 1 || n ==2){ return 1; }else { return f(n - 1) + f(n - 2); } } }
-
Factorial case
// Factorial: the factorial of a positive integer is the product of all positive integers less than or equal to the number. The factorial of natural number n is written as n! // 5! = 5*4*3*2*1 // Judge whether the value of the variable is 1 inside the method // Yes: Return 1 // No: return n*(n -1) public class DiGui{ public static void main(String[] args){ int result = jc(5); System.out.println("5 The factorial of is:"+ result); } public static int jc(int n){ if(n == 1){ return 1; }else { return n*jc(n - 1); } } }
Byte stream write file
public class Zijie{ public static void main(String[] args) throw FileNotFoundException { // FileOutputStream(String name): creates a file output stream and writes it to the file with the specified name FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt"); // void write(byte[] b): writes b.length bytes from the specified byte array to the file output stream byte[] bys = {97,98,99,100,101}; } } // fos.txt file abcde
-
Refer to the above case and the screenshot of the file directory