Java entry stage
Meaning of three Java versions
Java se (Java Standard Edition): Standard Edition, which is used on personal computers.
Java EE (Java Enterprise Edition): Enterprise Edition, targeting server-side applications. [mainstream]
JavaME (Java Micro Edition): Micro Edition, positioned in the application of consumer electronic products.
The development of the Internet of things will certainly be based on Android.
Java features and core advantages
Java core advantages: cross platform and portability
Features: security, object-oriented, simplicity, high performance, distributed, multithreading, robustness.
Running mechanism of Java application
Java first uses a text editor to write a java source program, and the suffix of the source file is java; Then the compiler (javac) is used to mutate the source program into a bytecode file, and the suffix of the bytecode file is. class; finally, the virtual machine (interpreter, Java) is used to interpret and execute.
JRE is the environment in which Java runs. It contains the Java virtual machine, or JVM.
Through the JVM, the program avoids directly dealing with the operating system and only needs to deal with the virtual machine, which is a core mechanism for cross platform implementation.
Differences among JDK, JRE and JVM
- JDK (Java Development Kit): Java Development Kit, including JRE and adding compiler and debugger, which is equal to the file of program development.
- JRE (Java Runtime Environment): contains the Java virtual machine, library functions, and files necessary to run Java applications.
- JVM (Java Virtual Machine): a virtual computer used to execute bytecode bytecode, which deals with the operating system.
JDK=JRE+JAVA development tool
JRE=JVM+lib class library
JAVA_HOME is to directly modify the environment variables here when the jdk version is changed without modifying the environment in Path.
First Java program
File name: welcome java
public class Welcome{ public static void main(String[] args){ System.out.println("Welcome!"); } }
Java operation principle:
(1) Write java source program with extension java;
(2)cmd window input: javac source file name java, compile the source code and generate a class bytecode file;
(3) Enter the command: java HelloWorld to interpret and run the class bytecode file.
In the process of practice and learning, mistakes are a rare opportunity for you to improve~
Don't be afraid of mistakes, because you can't grow without making mistakes!
Detailed analysis:
java is case sensitive; Public is the access modifier; Class represents a class. Objects are based on classes. A source file can contain multiple classes, and a class corresponds to a class file. However, only one public class can be declared in a source file, and the class name must be the same as the file name.
Most commonly used DOS commands
cd: enter a directory
cd...: enter parent directory
dir: view the list of files and subdirectories in this directory
cls: clear screen
Tab: automatic replenishment
Up and down keys: view the knocked commands
IntelliJ IDEA is a JAVA development software similar to Eclise
Data types and operators (video)
Basic Java syntax - identifiers, keywords and escape characters, process control
- Identifier: the name given to variables, classes, methods, etc.
Syntax specification:
(1) It is composed of letters, numbers, underscores and dollar sign $;
(2) Start with a letter, underscore or dollar sign;
(3) Class names are capitalized, methods and variables are lowercase, followed by humps;
(4) Identifiers cannot be keywords, contain spaces, or contain special characters. - Keyword: the identifier provided by java to represent the data type or supply and demand structure, such as public, double, etc.
- Separators include: {}, [], spaces, and dots.
- Escape character:
Special characters: 3
": double quotation marks
': single quotation mark
\: backslash
Control characters: 5
’Single quote character
\Backslash character
\r enter
\n line feed
\f. paper feed and page change
\t lateral skip
\b backspace - Process control: sequence, branch (if else, switch), loop (for, while, do while).
- Array: is an object; Store the same data type; Subscript starts from 0; Array features: consistency, order and immutability.
Definition of one-dimensional bit array: element data type [] array variable name
//Dynamic initialization. new after the array memory space is allocated, the element contents in the array are the default values of the array type.
int[] a = new int[3]; a[0] = 1; a[1] = 2; a[2] = 3
//Static initialization
int[] a = {1,2,3,4};
// Exercise: judge how many primes there are between 101-200 and output all primes. (change one line every 8) //Prime number: a natural number that has no other factors except 1 and itself among natural numbers greater than 1. public class CountPrime{ public static void main(String[] args){ int sum = 0; for(int i=101;i<=200;i++){ int count=0; for(int j=2;j<i;j++){ //Calculate whether each number between 101 and 200 is a prime number if(i%j == 0){ count++; } } if(count == 0){ System.out.print(i+" "); //If it is a prime number, the value is output //Wrap every 8 lines for easy viewing sum+=1; if(sum%8 == 0){ System.out.println(); } } } System.out.println(sum); //Output all primes } }
- Basic data types of Java: 8 basic types, corresponding wrapper classes, reference data types and conversion with String.
/** * Basic data types: 8 basic types * The corresponding wrapper class references the data type and the conversion with String. * String The basic data type refers to the relationship between transformations between data types. * * String.valueOf() Integer.parseInt(); * @author Administrator * */ public class TestWrapper { @Test public void StringtoWrapp(){ // Basic data type = = wrapper class = = = conversion between String classes. // Basic data type conversion String int i =10; Integer in =20; String st= String.valueOf(i); String st1= String.valueOf(in); // String converted to = = = = basic data type and reference data type int sf = Integer.parseInt(st); System.out.println(sf); System.out.println(in.toString()); } @Test public void tt(){ int in = 9; System.out.println(in); // Basic data type = = > Convert reference data type and directly call the constructor of reference type Integer ins= new Integer(in); // After the packaging class is converted to the basic data type jdk 5.0, discard this method and unpack and pack by yourself. in = ins.intValue(); System.out.println(ins.toString()); Float f= new Float(23.4f); System.out.println(f.toString()); Boolean ff =new Boolean("true"); Boolean f1 =new Boolean(true); System.out.println(ff+":"+f1); } @Test public void gg(){ // [auto packing] the basic data type is directly assigned to the packing class Integer fg= 13; // [automatic unpacking] - the packaging class is automatically converted to the basic data type. int fg1 =fg; } }
Classes and interfaces
Three characteristics of Java object-oriented: encapsulation, inheritance and polymorphism
- Encapsulation: hide some information from external visitors and realize operation and access through the methods provided by this class;
- Inheritance: keyword extend. If a class is not inherited with the extends keyword in the class, the class inherits the Object class by default;
- Polymorphism: objects have many forms. The same behavior has many different forms or forms.
Three necessary conditions for polymorphism: inheritance, rewriting, parent class reference pointing to child class object: Patent p = new child();
Class declaration and definition:
java class declaration format: access specifier class name extensions superclass name implements interface name
Access specifier: public or default. Classes defined in public can be accessed by all packages;
Class name: user defined;
Superclass Name: refers to an existing class;
Interface name: later
- java class body: including member variables and methods.
The access specifiers of member variables and methods are public, private and protected. - Interface in java: basic format of interface declaration public interface interface interface name extensions interface list
(1) Multiple inheritance attributes are prohibited in the java language, but you can help classes extend methods through interfaces.
(2) A large number of constants and methods can be defined in the interface, but the method is only a declaration without specific implementation. Use the class of the interface to implement these methods.
(3) The difference between an interface and a class is that an interface has no variable declaration but can define constants; an interface has only method declaration but no method implementation.
(4) The declaration syntax format of the interface is as follows:
[visibility] interface Interface name [extends Other interface names] { // Declare variable // Abstract method }
- Constructor: also known as construction method, it is a special function in JAVA. It has the same name as the function and has no return value.
Constructor function: used to initialize member properties and methods, that is, after the new object is generated, the properties and methods of the object are called and run only once. That is, the constructor runs as soon as the object is established. Generally, the function is executed only when the object is called. Generally, the function can be called multiple times.
Constructor features: (1) the function name is the same as the class name; (2) there is no need to define the return value type; (3) return statements cannot be written. - An instance of a class is a class object with state and behavior.
Class.
(1) Super: after extending its superclass with the keyword extends in the class declaration, super is used to reference the member variables in its superclass (parent class) in the extended class.
(2) this: the variable points to the current object or instance.
The two commonly used keywords in class are new, static, and fanal.
(1) new: used to create objects and open up space in the heap.
(2) static: modified methods are class methods; modified variables are class variables.
(3) final: modified classes cannot be inherited; modified variables or constants cannot be changed.
Collection interface
- Collection framework:
The Java Collection framework mainly includes two types of containers. One is a Collection, which stores a Collection of elements, and the other is a Map, which stores key / value pair mappings. The Collection framework is a unified architecture used to represent and manipulate collections. All Collection frameworks include the following contents:
(1) Interface: an abstract data type representing a Collection, such as Collection, List, Set, Map, etc. multiple interfaces are defined to operate Collection objects in different ways
(2) Implementation (class): it is the concrete implementation of the collection interface. In essence, they are reusable data structures, such as ArrayList, LinkedList, HashSet and HashMap.
(3) Algorithms: are useful calculations performed by methods in objects that implement set interfaces, such as search and sorting. These algorithms are called polymorphic because the same methods can have different implementations on similar interfaces.
Common classes
(1) Map class: implemented in the java.util package. The HashMap collection implements the map interface and has fast access speed. At most, the key of one record is allowed to be null. It does not support thread synchronization and is out of order.
(2) List class: it is ordered. ArrayList's underlying data structure is array structure, which is fast to query and slow to add and delete; LinkedList's underlying structure is linked list structure, which is slow to query and fast to add and delete.
(3) String related classes:
The string class is the final class. Whether the member method in the class is final; String class saves strings through char array.
Common methods:
public String substring(int beginIndex, int endIndex) //Gets a string from one location to another public String trim() //Remove spaces from string public String replace(char oldchar, char newchar) //Replace specified string public boolean equals(Object anObject) //Compare two strings for equality public int length() //String length public int indexOf(String str) //String retrieval
When modifying strings, you need to use StringBuffer and StringBuilder classes. Unlike the String class, the objects of the StringBuffer and StringBuilder classes can be modified multiple times without generating new unused objects.
The StringBuffer class provides a String variable series, which is similar to the String class, but the character sequence it stores can be modified arbitrarily, which is much more flexible than the String class. Common constructors: StringBuffer(), StringBuffer(String str), convert the data of the StringBuffer object into a String: public String toString()
StringBuilder class
Compare String, StringBuffer and StringBuilder:
Running speed: StringBuilder > StringBuffer > string
Usage:
String is used for a small number of strings;
StringBuffer is applicable to the case where a large number of operations are performed in the string buffer under multithreading and thread safety is required;
The StringBuilder class is suitable for a large number of operations in the character buffer under a single thread.
java constant pool: used to store class information, constants, static constants, etc. that have been loaded by the virtual machine. The constant pool is stored in the heap.
Create a string with double quotation marks ": first, search the constant pool for whether there is an equal constant object. If not, create the constant object in the constant pool; If yes, it will directly return the reference of this constant object.
Intern: for a string object created with new, if you want to add the reference of this object to the string constant pool, you can use the intern method. After calling intern, first check whether there is a reference to the object in the string constant pool. If it exists, return the reference to the variable. Otherwise, add the reference and return it to the variable.
About the + operator: when two or more string constants are added, the "+" will be optimized during precompiling, which is equivalent to automatically synthesizing two or more string constants into one string constant.
String constants are stored in the method area and strings are stored in the heap.
String str1="hello"; String str2 = "hello"; System.out.println(str1==str2);//true
public static void main(String[] args){ String s1 = new String("hello"); String s2 = "hello"; String s3 = new String("hello"); System.out.println(s1 == s2); //false, because = = refers to the address of the reference, s2 refers to the address of the constant object in the constant pool, and s1 refers to the address of the String object in the heap. System.out.println(s1.equals(2); //true, because the content of the string is compared System.out.println(s1 == s3); //false, because each String object is different and the reference points to a different pair of addresses }
(4) Date related classes: mainly used to format dates
Date currentTime = new Date(); //Initializes the object with the current date and time. SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss"); //Formatting dates using SimpleDateFormat System.out.println("Current time is: " + ft.format(currentTime)); //Get a formatted date
SimpleDateFormat is a non thread safe class.
(5) BigDecimal class
abnormal
Throwable class derives two classes: Exception class and Error class. The Error class is reserved by the system, and the Exception class is used by the program.
//Common methods in Exception class: public String toString(); //Returns a short description of the exception public String getMessage() //Returns the detailed description of the exception
Exceptions are divided into system defined Exceptions and user-defined exceptions. User-defined exceptions inherit from Exception. Common system exceptions:
Array subscript out of bounds exception: ArrayIndexOutOfBoundsException Arithmetic exception class: ArithmeticExecption //For example, the book is 0 ClassNotFoundException The class you want to load was not found NullPointerException Empty unallocated memory object
throws keyword, throw keyword:
The throws keyword is applied when declaring a method to specify the exceptions that the method may throw.
The throw keyword is used in the method body and throws an exception object. To catch and handle throw exceptions in the upper level, you must use the throws method to declare the exception to be thrown in the method that throws the exception; To capture, you must use a try catch statement block. Throw is generally used for user-defined exceptions.
try{ // Program code }catch(Variable name of exception type 1){ // Program code }catch(Variable name of exception type 2){ // Program code }finally{ // Exceptions will be executed when they are not exceptions (usually used to close file stream objects or database objects) // Program code }
Custom exception:
//Need to modify class InputMismatchException extends Exception{ public InputMismatchException (){ super(); } public InputMismatchException (String str){ super(str); } } try{ Input = input.nextInt(); }catch(InputMismatchException e){ System.out.println("The character entered is not a number!"); }
problem
1 use of parentheses
- Use the new keyword to call the construction method to create an object, which should be enclosed in parentheses (): Person p1 = new Person();
2. The execution order of these constructors
- If the parent class is inherited, the loading order is: parent class static -- > child class static -- > parent class member function -- > parent class construction method -- > child class member function -- > child class construction method
Among them, static code includes (static method, static variable, static code block, etc.), member function, that is (member method, member variable, member code block, etc.), the same code is loaded first when written above.
3 Access specifiers of member variables and methods public, private and protected usage methods
- public: visible to all classes;
- protected: it cannot be accessed across packages and is visible to classes and all subclasses in the same package;
protected needs to be analyzed and explained from the following two points:
(1) 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;
(2) 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. - private: visible in the same category;
- default: visible in the same package.
Correct mistakes
About constructors in java
- The constructor has no return value, and the return type is not void;
- The constructor must be the same as the class name, with or without parameters;
- A class can define multiple constructors;
- Note: if the constructor is not declared in the class, The JVM (Java Virtual Machine) will help us generate a constructor with empty parameters by default; if we declare a constructor with parameter list in the class, the JVM will not help us generate a constructor with empty parameters by default. If we want to use a constructor with empty parameters, we need to construct it ourselves. Therefore, there is no need to explicitly define a constructor in the class.
- Constructor function: create object; Object initialization.
- Characteristics of constructor in inheritance:
- Will the subclass call the function of the parent class?
A: the subclass inherits from the parent class. The parent class constructor will also be executed when the subclass object is initialized, because the subclass needs to use the properties in the parent class. - What is the relationship between the constructor of a subclass and the constructor of a parent class?
A: the default first line of the subclass constructor has an implicit statement super(), which will access the null parameter constructor in the parent class, unless there is no null parameter constructor in the parent class. At this time, the first line of the subclass constructor must explicitly call the constructor of the parent class, that is, super (int, x,...). - What should the constructor of subclasses pay attention to?
A: in the constructor of a subclass, the super() statement represents the constructor of the parent class; The this() statement represents a call to the constructor of the subclass itself. If the two statements are explicitly written, they must be placed on the first line of the constructor, and the two statements cannot coexist. The first line in a constructor is either this() or super(). - What is the difference between ordinary functions and constructors? reference
Answer:
(1) Call times are different: constructors run when the class object is created, while ordinary functions execute only when the object is called;
(2) Different execution times: after an object is created, its constructor is executed only once, that is, when it is created; while ordinary functions can be executed multiple times after the object is created, depending on the number of calls to the object.
(3) Constructors have no return value and cannot be modified with void. Ordinary methods must have a return value;
(4) In terms of naming rules, constructors are generally capitalized and consistent with the class name. Ordinary functions need to follow the small hump naming;
(5) Constructors cannot be called directly. They can only be called automatically when creating objects through the new operator, while general methods are called only when the program is executed;
(6) Constructors automatically call new methods with higher priority than normal methods.
//---------------------------File: Math1 java------------------------------------ package demo; public class Math1{ private int count; //Constructor public Math1(){ System.out.println("This is a constructor!"); } //Ordinary function public void math(){ System.out.println("This is the normal method"); } public int add(){ count++; return count; } public int getCount(){ return count; } public void setCount(int count){ this.count = count; } } //---------------------------File: test java------------------------------------ //Test function package demo; import demo.Math1; public class Text{ public static void main(String[] args){ //Initialize a Math1 a = new Math1(); //Call normal method a.math(); int count = a.getCount(); System.out.println(count); a.add(); int count1 = a.getCount(); System.out.println(count1); a.setCount(100); int count2 = a.getCount(); System.out.println(count2); } } //Output: This is the construction method! This is the normal method! 0 1 100
eclipse renames java files
- Click the file - press F2 to modify it.
Implementation of thread class in java
Inherit Thread class
- Thread class is the parent class of all thread classes, which implements the extraction and encapsulation of threads.
- To inherit the Thread class and create and start a multithread:
①. Define a class, inherit from the Thread class, and override the run method of the class. The method body of the run method represents the tasks that the Thread needs to complete. Therefore, the method body of the run method is called the Thread execution body
②. Create the object of Thread subclass, that is, create the sub Thread
③. Start the thread with the start method of the thread object - Demo
First create a ticket thread java file
package demo1; public class SellTickets extends Thread{ //shared data static int count = 100; //Override the run() method of the Thread class @Override public void run(){ //Circular ticketing while(count>0){ count--; System.out.println(Thread.currentThread().getName() + "One ticket sold, the rest" + count); } } }
Test class java file
import demo1.SellTickets; public class TheadDemo { public static void main(String[] args) { //Simulate four ticket sellers SellTickets s1 = new SellTickets(); SellTickets s2 = new SellTickets(); SellTickets s3 = new SellTickets(); // System.out.println(s1.currentThread().getName()); // The name of this thread is main s1.start(); s2.start(); s3.start(); } }
Implement Runnable interface
- The method of implementing Runnable interface is commonly used, because the way of implementing interface is more flexible than that of inheriting classes, and it can also reduce the coupling between programs.
- Steps to create and start multithreading by implementing Runnable interface:
①. Define an implementation class of Runnable interface and rewrite the run method in the interface. The method body of the run method is also the thread execution body of the thread
②. Create an instance of the Runnable implementation class, and use this instance as the target of the Thread to create the Thread object, which is the real Thread object
③. Call the start method of the thread object to start the thread - Demo
public class SellTickets{ static int count = 100; //Create an instance of the Runnable implementation class static Runnable r = new Runnable(){ //Override the run() method of the Runnable interface @Override public void run(){ while(count > 0){ count--; System.out.println(Thread.currentThread().getName() + "One ticket sold, the rest" + count); } } } public static void main(String[] args){ Thread t1 = new Thread(r); Thread t2 = new Thread(r); Thread t3 = new Thread(r); t1.start(); t2.start(); t3.start(); } }
Comparison between inheriting Thread class and implementing Runnable interface
- Inherit Thread class
(1) It is easy to write. If you want to access the current thread, you can use the super keyword in addition to the Thread.currentThread();
(2) Disadvantages: because the Thread class has inherited the Thread class, it cannot inherit other classes * * [single inheritance] * *. - How to implement the Runnable interface
(1) Thread classes only implement the Runnable interface and can inherit other classes * * [a class can inherit another class while implementing the interface] * *;
(2) Multiple threads can share the same target object, so it is very suitable for multiple threads to process the same resource;
(3) Disadvantages: programming is slightly complex and not intuitive. If you want to access the current thread, you must use Thread.currentThread().
The difference between calling the start() and run() methods
- The start() method creates a new thread and lets the thread execute the run() method.
Thread thread = new Thread(); thread.start();
- The call to run() can also be executed normally. However, instead of creating a new thread, it calls the run() method in the current thread, just as an ordinary method call.
Thread thread = new Thread(); thread.run();
- Suggestion: do not use run() to start a new thread. It will only serially execute the code in the run() method in the current thread.