**
An article allows you to learn Java from the beginning to the end
**
Detailed explanation of the first Java program + basic knowledge
The basis of java language mainly includes the following important aspects: classes, objects, methods, instances and variables.
- Object: an object is an instance of a class with state and behavior. For example, a dog is an object, and its status includes: color, name and variety; Behaviors include wagging tail, barking, eating, etc.
- Class: a class is a template that describes the behavior and state of a class of objects.
- Method: method is behavior. A class can have many methods. Logical operation, data modification and all actions are completed in the method.
- Instance variables: each object has unique instance variables, and the state of the object is determined by the values of these instance variables.
Next is the classic programmer will:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
This is the first program of Java. I will explain what the above parts mean.
In the main program, the sentence public static void main(String[] args) is the most important main function in all languages. His composition is mainly as follows:
Public: access modifier (this keyword indicates that the method main() is public and can be accessed by any method);
Static: keyword (this keyword tells the compiler that the main() method is static and does not need to be called through an instance.)
void: return type (it is important to indicate that the main() method does not return any value.)
String []: Sting class (remember to be case sensitive, which is very important)
args: string array.
String args []: together, it represents the command line parameters.
After explaining the most important main function, let's take a look at public class HelloWorld, which is well understood. The main purpose of this line of code is to declare a public class named HelloWorld.
When writing your own java program, you must pay attention to the following points:
- Case sensitive: Java is case sensitive, which means that the identifiers hello and hello are different.
- Source file name: the source file name must be the same as the class name. When saving a file, you should use the class name as the file name (remember that Java is case sensitive), and the suffix of the file name is
.java. (if the file name and class name are different, it will lead to compilation errors). - Main method entry: all Java programs are executed by the public static void main(String[] args) method. Be sure to note that it is a string instead of a string.
Identifier contained in Java: it is a little different from c language here. Java contains uppercase and lowercase letters, $characters and underscores. Under these three conditions, numbers can be included as long as they are not legal at the beginning of numbers.
Modifiers in Java are mainly divided into two categories:
- Access control modifiers: default, public, protected, private
- Non access control modifiers: final, abstract, static, synchronized
Variables in Java: 1, local variables 2, class variables (static variables) 3, member variables (non static variables)
Java enumeration: the main purpose of enumeration is to limit variables. For example, chestnut: you are a milk tea shop. There are only three types of milk tea, large, medium and small. Customers can only order these three types. If he orders half a cup, you must say that you can't sell it. For the program, you will directly report an error to you. (this will be described in detail later in this chapter)
Note: enumerations can be declared separately or in classes. Methods, variables, and constructors can also be defined in enumerations.
Keywords for Java:
Here comes the international form
Java annotation: there are two common annotation methods: / * + + + + + * / this is the annotation method of multi line annotation,
// This is an example of a single line comment
Java inheritance: in Java, a class can be derived from other classes. If you want to create a class and there is already a class with the properties or methods you need, you can inherit the newly created class from the class.
Using inherited methods, you can reuse the methods and properties of existing classes without rewriting these codes. The inherited class is called super class, and the derived class is called sub class.
Java interface: in Java, an interface can be understood as a protocol for mutual communication between objects. Interfaces play an important role in inheritance. Interface only defines the methods to be used for derivation, but the specific implementation of the method depends entirely on the derived class.
The difference between Java source program and compiled operation:
Java objects and classes
Java mainly supports the following methods in the object-oriented process:
Polymorphism, inheritance, encapsulation, abstraction, class, object, instance, method, overload.
Object: an object is an instance of a class with behavior, state, etc.
Class: a class is a template that describes the behavior and state of a class of objects.
Here, you should clearly understand the relationship between classes and objects. If you understand the relationship between the two, you will learn this section.
Take chestnuts for example: in the figure below, class represents a class and object represents an object
Objects in Java: software objects also have state and behavior. The state of a software object is an attribute, and its behavior is reflected by methods.
In software development, the method operates the change of the internal state of the object, and the mutual call of the object is also completed through the method.
Classes in Java: classes can be seen as templates for creating Java objects.
A class can contain the following types of variables:
- Variables or methods defined in statements are called local variables or methods. Variable declaration and initialization are in the method. After the method ends, the variable will be destroyed automatically.
- Member variables: member variables are variables defined in the class and outside the method body. This variable is instantiated when the object is created. Member variables can be accessed by methods in a class, constructor methods, and statement blocks of a specific class.
- Class variables: class variables are also declared in the class, outside the method body, but must be declared as static type.
Construction method: each class has a construction method. If you do not explicitly define a constructor for a class, the Java compiler will provide a default constructor for that class. In order to realize this function, the system customizes the default constructor and allows programmers to write their own construction methods to complete different operations. Construction method is a special class method with special functions. Its name is the same as the class name and has no return value. It is automatically called by the new operator when creating an object instance. At the same time, for the convenience of creating instances, a class can have multiple construction methods with different parameter lists, that is, the construction methods can be overloaded. In fact, both standard classes provided by the system and user-defined classes often contain multiple construction methods.
public class Puppy{ public Puppy(){ } public Puppy(String name){ // This constructor has only one parameter: name } }
Create objects: objects are created from classes. In Java, the keyword new is used to create a new object. Creating objects requires the following three steps:
- Declaration: declare an object, including object name and object type.
- Instantiation: use the keyword new to create an object.
- Initialization: when using new to create an object, the constructor will be called to initialize the object.
public class Puppy{ public Puppy(String name){ //This constructor has only one parameter: name System.out.println("What's the dog's name : " + name ); } public static void main(String[] args){ // The following statement will create a purchase object Puppy myPuppy = new Puppy( "tommy" ); } }
Data types in Java
There are two data types in Java:
- Built in data type
- Reference data type
After learning the previous content, the following code should be understandable
public class PrimitiveTypeTest { public static void main(String[] args) { // byte System.out.println("Basic type: byte Binary digits:" + Byte.SIZE); System.out.println("Packaging: java.lang.Byte"); System.out.println("Minimum: Byte.MIN_VALUE=" + Byte.MIN_VALUE); System.out.println("Maximum: Byte.MAX_VALUE=" + Byte.MAX_VALUE); System.out.println(); // short System.out.println("Basic type: short Binary digits:" + Short.SIZE); System.out.println("Packaging: java.lang.Short"); System.out.println("Minimum: Short.MIN_VALUE=" + Short.MIN_VALUE); System.out.println("Maximum: Short.MAX_VALUE=" + Short.MAX_VALUE); System.out.println(); // int System.out.println("Basic type: int Binary digits:" + Integer.SIZE); System.out.println("Packaging: java.lang.Integer"); System.out.println("Minimum: Integer.MIN_VALUE=" + Integer.MIN_VALUE); System.out.println("Maximum: Integer.MAX_VALUE=" + Integer.MAX_VALUE); System.out.println(); // long System.out.println("Basic type: long Binary digits:" + Long.SIZE); System.out.println("Packaging: java.lang.Long"); System.out.println("Minimum: Long.MIN_VALUE=" + Long.MIN_VALUE); System.out.println("Maximum: Long.MAX_VALUE=" + Long.MAX_VALUE); System.out.println(); // float System.out.println("Basic type: float Binary digits:" + Float.SIZE); System.out.println("Packaging: java.lang.Float"); System.out.println("Minimum: Float.MIN_VALUE=" + Float.MIN_VALUE); System.out.println("Maximum: Float.MAX_VALUE=" + Float.MAX_VALUE); System.out.println(); // double System.out.println("Basic type: double Binary digits:" + Double.SIZE); System.out.println("Packaging: java.lang.Double"); System.out.println("Minimum: Double.MIN_VALUE=" + Double.MIN_VALUE); System.out.println("Maximum: Double.MAX_VALUE=" + Double.MAX_VALUE); System.out.println(); // char System.out.println("Basic type: char Binary digits:" + Character.SIZE); System.out.println("Packaging: java.lang.Character"); // Convert character. As a numeric value instead of a character MIN_ Value output to console System.out.println("Minimum: Character.MIN_VALUE=" + (int) Character.MIN_VALUE); // Convert character. As a numeric value instead of a character MAX_ Value output to console System.out.println("Maximum: Character.MAX_VALUE=" + (int) Character.MAX_VALUE); } }
There is no superfluous explanation here.
Java constants: use the final keyword to modify constants in Java. The declaration method is similar to that of variables:
final double PI = 3.1415927;
Automatic type conversion: integer, real (constant) and character data can be mixed. In the operation, different types of data are transformed into the same type first, and then the operation is carried out.
Convert from low-level to high-level.
Low --------------------------------------- > High
byte,short,char—> int —> long—> float —> double
Data type conversion must meet the following rules:
- Cannot type convert boolean type.
- You cannot convert an object type to an object of an unrelated class.
- Cast must be used when converting a high-capacity type to a low-capacity type.
- Overflow or loss of accuracy may occur during conversion
Cast type:
- The condition is that the converted data types must be compatible.
- Format: (type)value type is the data type to be cast
Java variable type
In the Java language, all variables must be declared before use.
Format Description: type is Java data type. identifier is the variable name. You can declare multiple variables of the same type separated by commas.
Here is an example:
int a, b, c; // Declare three int integers: a, b, c int d = 3, e = 4, f = 5; // Declare three integers and give initial values byte z = 22; // Declare and initialize z String s = "runoob"; // Declare and initialize string s double pi = 3.14159; // The double precision floating-point variable pi is declared char x = 'x'; // Declare that the value of variable x is the character 'x'.
You should have seen the class variables, instance variables and local variables I mentioned before.
Here is a detailed explanation:
public class Variable{ static int allClicks=0; // Class variable String str="hello world"; // Instance variable public void method(){ int i =0; // local variable } }
Java local variable
- Local variables are declared in methods, construction methods or statement blocks;
- Local variables are created when methods, construction methods, or statement blocks are executed. When they are executed, the variables will be destroyed;
- Access modifiers cannot be used for local variables;
- A local variable is only visible in the method, constructor or statement block that declares it;
- Local variables are allocated on the stack.
- Local variables have no default value, so they can only be used after initialization after being declared.
Instance variable - Instance variables are declared in a class, but outside methods, constructor methods and statement blocks;
- When an object is instantiated, the value of each instance variable is determined;
- Instance variables are created when the object is created and destroyed when the object is destroyed;
- The value of the instance variable should be referenced by at least one method, construction method or statement block, so that the external can obtain the instance variable information through these methods;
- Instance variables can be declared before or after use;
- Access modifiers can modify instance variables;
- Instance variables are visible to methods, constructors, or statement blocks in a class. In general, instance variables should be set to private. You can make instance variables visible to subclasses by using access modifiers;
- Instance variables have default values. The default value of numeric variable is 0, the default value of boolean variable is false, and the default value of reference type variable is null. The value of the variable can be specified at the time of declaration or in the construction method;
- Instance variables can be accessed directly through variable names. But in static methods and other classes, you should use the fully qualified name: obejectreference VariableName.
Class variable (static variable) - Class variables, also known as static variables, are declared in the class with the static keyword, but must be outside the method.
- No matter how many objects a class creates, a class has only one copy of the class variable.
- Static variables are rarely used except declared as constants. Static variables are declared as public/private, final and static
Variable of type. Static variables cannot be changed after initialization. - Static variables are stored in the static storage area. It is often declared as a constant, and static is rarely used alone to declare variables.
- Static variables are created the first time they are accessed and destroyed at the end of the program.
- Has similar visibility to instance variables. However, in order to be visible to the users of the class, most static variables are declared as public.
- Default values are similar to instance variables. The default value of numeric variable is 0, the default value of Boolean is false, and the default value of reference type is null.
- The value of a variable can be specified at the time of declaration or in the construction method. In addition, static variables can be initialized in static statement blocks.
- Static variables can be through: classname Variablename.
- When a class variable is declared as public static final, it is generally recommended to use uppercase letters for the name of the class variable. If the static variable is not of public or final type, its naming method is consistent with that of instance variable and local variable.
Java modifier
Java modifiers fall into two categories:
1. Access modifier
2. Non access modifier
Modifiers are used to define classes, methods, or variables, and are usually placed at the front of a statement.
public class ClassName { // ... } private boolean myFlag; static final double weeks = 9.5; protected static final int BOXWIDTH = 42; public static void main(String[] arguments) { // Method body }
Access modifier
- default: visible in the same package without any modifiers. Use objects: classes, interfaces, variables, methods.
- private: visible in the same category. Use object: variable, method. Note: cannot decorate class (external class)
- public: visible to all classes. Objects used: classes, interfaces, variables, methods
- protected: visible to classes and all subclasses in the same package. Use object: variable, method. Note: you cannot decorate classes (external classes).
Access and control as like as two peas in the c language are not much more.
Inheritance of access - Methods declared public in the parent class must also be public in the child class.
- Methods declared as protected in the parent class are either declared as protected or public in the child class, and cannot be declared as private.
- Methods declared as private in the parent class cannot be inherited by subclasses.
Non access modifier
In order to realize some other functions, Java also provides many non access modifiers.
static modifier, used to modify class methods and class variables.
Final modifier is used to modify classes, methods and variables. The class modified by final cannot be inherited, the modified method cannot be redefined by the inherited class, and the modified variable is constant and cannot be modified.
Abstract modifier to create abstract classes and methods.
synchronized and volatile modifiers are mainly used for thread programming.
The various modifiers mentioned above have been explained in the front. I will explain the specific ones that are difficult to understand and need attention
abstract modifier
Abstract class:
Abstract classes cannot be used to instantiate objects. The only purpose of declaring abstract classes is to expand them in the future.
A class cannot be modified by abstract and final at the same time. If a class contains abstract methods, the class must be declared as an abstract class, otherwise a compilation error will occur.
Abstract classes can contain abstract and non abstract methods.
synchronized modifier
The method declared by the synchronized keyword can only be accessed by one thread at a time. The synchronized modifier can be applied to four access modifiers.
transient modifier
When the serialized object contains an instance variable modified by transient, the java virtual machine (JVM) skips the specific variable.
This modifier is included in the statement defining the variable and is used to preprocess the data types of the class and variable.
volatile modifier
Each time a volatile modified member variable is accessed by a thread, it forces the value of the member variable to be re read from the shared memory. Moreover, when the member variable changes, the thread will be forced to write the change value back to the shared memory. In this way, at any time, two different threads always see the same value of a member variable.
A volatile object reference may be null.
Java operator
There are the following in total:
1. Arithmetic operator
2. Relational operators
3. Bitwise operator
4. Logical operators
5. Assignment operator
6. Other operators
Arithmetic operator
Relational operator
Bitwise Operators
Logical operator
Assignment Operators
Java operator priority
Loops in Java
There are three main large loop structures commonly used in Java
while Loop
do... while loop
for loop
while loop
while is the most basic loop. Its structure is:
while( Boolean expression ) { //Cyclic content }
As long as the Boolean expression is true, the loop will continue to execute.
do... while loop
For the while statement, if the condition is not met, it cannot enter the loop. But sometimes we need to perform at least once even if the conditions are not met.
The do... While loop is similar to the while loop, except that the do... While loop is executed at least once.
for loop
Although all loop structures can be represented by while or do... While, Java provides another statement - for loop, which makes some loop structures simpler.
The number of times the for loop is executed is determined before execution.
There are the following explanations for the for loop:
- Perform the initialization step first. You can declare a type, but you can initialize one or more loop control variables or empty statements.
- Then, the value of the Boolean expression is detected. If true, the loop body is executed. If false, the loop terminates and starts executing the statement after the loop body.
- After executing a loop, update the loop control variable.
- Detect the Boolean expression again. Loop through the above procedure.
Java enhanced for loop
Java5 (commonly used for learning java8) introduces an enhanced for loop mainly used for arrays.
The syntax format of Java enhanced for loop is as follows:
for(Declaration statement : expression) { //Code sentence }
Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time.
Expression: an expression is the name of the array to be accessed, or a method whose return value is an array.
break keyword
break is mainly used in loop statements or switch statements to jump out of the whole statement block.
break jumps out of the innermost loop and continues to execute the following statements of the loop.
It may not be easy to understand here. Let's take a look at the following examples:
public class Test { public static void main(String[] args) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { // Jump out of loop when x equals 30 if( x == 30 ) { break; } System.out.print( x ); System.out.print("\n"); } } }
continue keyword
continue applies to any loop control structure. The function is to make the program jump to the iteration of the next cycle immediately.
In the for loop, the continue statement causes the program to immediately jump to the update statement.
In the while or do... While loop, the program immediately jumps to the judgment statement of Boolean expression.
public class Test { public static void main(String[] args) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { continue; } System.out.print( x ); System.out.print("\n"); } } }
Java conditional statement
The syntax of the if statement is as follows
if(Boolean expression) { //The statement that will be executed if the Boolean expression is true }
This chapter is exactly the same as c language, so I won't elaborate on its usage.
public class Test { public static void main(String args[]){ int x = 10; if( x < 20 ){ System.out.print("This is if sentence"); } } }
switch case statement in Java
The switch case statement determines whether a variable is equal to a value in a series of values. Each value is called a branch.
switch(expression){ case value : //sentence break; //Optional case value : //sentence break; //Optional //You can have any number of case statements default : //Optional //sentence }
- The variable type in the switch statement can be byte, short, int or char. Starting with Java SE 7, switch
The String type is supported, and the case label must be a String constant or literal. - A switch statement can have multiple case statements. Each case is followed by a value to compare and a colon.
- The data type of the value in the case statement must be the same as that of the variable, and can only be a constant or literal constant.
- When the value of the variable is equal to the value of the case statement, the statement after the case statement starts to execute, and the switch statement will not jump out until the break statement appears.
- When a break statement is encountered, the switch statement terminates. The program jumps to the statement execution after the switch statement. Case statements do not have to contain break statements. If no break statement appears, the program will continue to execute the next case statement until the break statement appears.
- A switch statement can contain a default branch, which is generally the last branch of the switch statement (it can be anywhere, but it is recommended to be in the last branch). Default is executed when the value of no case statement is equal to the value of the variable. The default branch does not require a break statement.
Math class in Java
Generally, when we need to use numbers, we usually use built-in data types, such as byte, int, long, double, etc.
Java's Math contains properties and methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions.
Math methods are defined in static form, and can be called directly in the main function through math class.
public class Test { public static void main (String []args) { System.out.println("90 Sine of degree:" + Math.sin(Math.PI/2)); System.out.println("0 Cosine value of degrees:" + Math.cos(0)); System.out.println("60 Tangent of degrees:" + Math.tan(Math.PI/3)); System.out.println("1 Arctangent of: " + Math.atan(1)); System.out.println("π/2 Angle value:" + Math.toDegrees(Math.PI/2)); System.out.println(Math.PI); } }
The result of the above code 90 Sine of degree: 1.0 0 Cosine value of degree: 1.0 60 Tangent value of degree: 1.7320508075688767 1 Arctangent of: 0.7853981633974483 π/2 Angle value: 90.0 3.141592653589793
The following table lists some methods commonly used by the number & math class:
Comparison of floor,round and ceil methods of Math
Java Character class
The Character class is used to manipulate a single Character.
The Character class wraps the value of a basic type Character in an object
char ch = 'a'; // Unicode character representation char uniChar = '\u039A'; // Character array char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
However, in the actual development process, we often encounter the need to use objects instead of built-in data types. To solve this problem, the Java language provides a wrapper class Character class for the built-in data type char.
The Character class provides a series of methods to manipulate characters. You can use the construction method of Character to create a Character class object
Escape sequence
Character method
To learn more about the specific composition methods, you can check the official API documents
Java official API link
Java String class
String is widely used in Java programming. In Java, string belongs to object. Java provides string class to create and operate string.
Create string
The syntax is as follows:
String str = "zifuchuan";
When a String constant is encountered in the code, the value here is "zifuchuan", which will be used by the compiler to create a String object.
Like other objects, you can use keywords and construction methods to create String objects.
The String created by String is stored in the public pool, while the String object created by new is on the heap:
String s1 = "Runoob"; // String create directly String s2 = "Runoob"; // String create directly String s3 = s1; // Same reference String s4 = new String("Runoob"); // String object creation String s5 = new String("Runoob"); // String object creation
String length
The method used to obtain information about an object is called an accessor method.
An accessor method of the String class is the length() method, which returns the number of characters contained in the String object.
After the following code is executed, the len variable is equal to 14:
public class StringDemo { public static void main(String args[]) { String site = "www.csdn.net"; int len = site.length(); System.out.println( "csdn URL length : " + len ); } }
The operation results are as follows:
csdn URL length : 12
Connection string
The String class provides a method to connect two strings:
string1.concat(string2);
More commonly, the '+' operator is used to connect strings, such as:
"Hello," + " World" + "!"
Create format string
We know that the printf() and format() methods can be used to output formatted numbers.
The String class uses the static method format() to return a String object instead of a PrintStream object.
The static method format() of the String class can be used to create reusable formatted strings, not just for one printout.
System.out.printf("The value of a floating-point variable is " + "%f, The value of an integer variable is " + " %d, The value of the string variable is " + "is %s", floatVar, intVar, stringVar);
The above figure shows some usage of strings, so I won't repeat it. You can try it yourself or go to the official API to learn more about it.
Java StringBuffer and StringBuilder classes
When modifying a string, 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.
When using the StringBuffer class, you will operate on the StringBuffer object itself every time instead of generating a new object. Therefore, if you need to modify the string, it is recommended to use StringBuffer.
The StringBuilder class is proposed in Java 5. The biggest difference between it and StringBuffer is that the StringBuilder method is not thread safe (cannot be accessed synchronously).
Because StringBuilder has a speed advantage over StringBuffer, it is recommended to use StringBuilder class in most cases.
StringBuffer method
Java array
Arrays provided in the Java language are used to store fixed size elements of the same type.
You can declare an array variable, such as numbers[100], instead of directly declaring 100 independent variables, number0, number1,..., number99.
Declare array variables
dataType[] arrayRefVar; // Preferred method or dataType arrayRefVar[]; // The effect is the same, but it is not the preferred method
Note: it is recommended to use the declaration style of dataType[] arrayRefVar to declare array variables. dataType arrayRefVar [] style comes from C/C + + language. It is adopted in Java to enable C/C + + programmers to quickly understand the Java language.
Array declaration method commonly used in Java
double[] myList; // Preferred method or double myList[]; // The effect is the same, but it is not the preferred method
Create array
Create an array as follows:
arrayRefVar = new dataType[arraySize];
Another way to create
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Example:
public class TestArray { public static void main(String[] args) { // Array size int size = 10; // Define array double[] myList = new double[size]; myList[0] = 5.6; myList[1] = 4.5; myList[2] = 3.3; myList[3] = 13.2; myList[4] = 4.0; myList[5] = 34.33; myList[6] = 34.0; myList[7] = 45.45; myList[8] = 99.993; myList[9] = 11123; // Calculate the sum of all elements double total = 0; for (int i = 0; i < size; i++) { total += myList[i]; } System.out.println("The sum is: " + total); } }
Output result:
Total: 11367.373
The following image depicts the array myList. Here, there are 10 double elements in the myList array, with subscripts from 0 to 9.
java date and time
java. The util package provides a Date class to encapsulate the current Date and time. The Date class provides two constructors to instantiate the Date object.
The first constructor initializes the object with the current date and time.
Date( )
The second constructor receives a parameter that is the number of milliseconds from January 1, 1970.
Date(long millisec)
After the object is created, you can call the following methods
Get current date and time
Use the toString() method of the Date object to print the current Date and time
import java.util.Date; public class DateDemo { public static void main(String[] args) { // Initialize Date object Date date = new Date(); // Use the toString() function to display the date and time System.out.println(date.toString()); } }
The above code is a code example of time acquisition. You can try it in the compilation environment, and the results will not be demonstrated to you.
Java sleep
Point oh
sleep() causes the current thread to enter a stagnant state (blocking the current thread) and gives up the use of CPU. The purpose is not to let the current thread occupy the CPU resources obtained by the process alone, so as to leave a certain time for other threads to execute.
You can let the program sleep for a millisecond or any period of time for the long life of your computer. For example, the following program will sleep for 3 seconds:
import java.util.*; public class SleepDemo { public static void main(String[] args) { try { System.out.println(new Date( ) + "\n"); Thread.sleep(1000*3); // Sleep for 3 seconds System.out.println(new Date( ) + "\n"); } catch (Exception e) { System.out.println("Got an exception!"); } } }
Java regular expression
Regular expressions are generally used to match text and search text.
Regular expression instance
java. util. The regex package mainly includes the following three classes:
- Pattern class: a pattern object is a compiled representation of a regular expression. The pattern class has no public constructor. To create a pattern object, you must first call its public static compilation method, which returns a pattern object. This method takes a regular expression as its first argument.
- Matcher class:
The Matcher object is an engine that interprets and matches input strings. Like the Pattern class, Matcher has no public constructor. You need to call the Matcher method of the Pattern object to get a Matcher object. - PatternSyntaxException: PatternSyntaxException is a non mandatory exception class that represents a syntax error in a regular expression pattern.
import java.util.regex.*; class RegexExample1{ public static void main(String[] args){ String content = "I am coder " + "from csdn.com."; String pattern = ".*csdn.*"; boolean isMatch = Pattern.matches(pattern, content); System.out.println("Whether the string contains 'csdn' Substring? " + isMatch); } }
Output result:
Whether the string contains 'csdn' Substring? true
Capture group
Capture group is a method to process multiple characters as a single unit. It is created by grouping the characters in parentheses.
For example, a regular expression (dog) creates a single group containing "d", "o", and "g".
Capture groups are numbered by calculating their open parentheses from left to right. For example, in the expression ((A) (B (C))), there are four such groups:
((A)(B©))
(A)
(B©)
©
You can see how many groups the expression has by calling the groupCount method of the matcher object. The groupCount method returns an int value indicating that the matcher object currently has multiple capture groups.
There is also a special group (group(0)), which always represents the entire expression. The group is not included in the return value of groupCount.
Example:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String[] args ){ // Find in string according to specified pattern String line = "This order was placed for QT3000! OK?"; String pattern = "(\\D*)(\\d+)(.*)"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create the matcher object Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); System.out.println("Found value: " + m.group(3) ); } else { System.out.println("NO MATCH"); } } }
regular expression syntax
In other languages, \ means: I want to insert a normal (literal) backslash into a regular expression, please don't give it any special meaning.
In Java, \ means that I want to insert a backslash of a regular expression, so the following characters have special meaning.
Therefore, in other languages (such as Perl), one backslash \ is enough to escape, while in Java, regular expressions need two backslashes to be resolved to escape in other languages. It can also be simply understood that in Java regular expressions, two \ represent one in other languages, which is why the regular expression representing one digit is \ d, while the regular expression representing an ordinary backslash is \.
The figure above shows some usage of regular expressions. You can try it yourself.
Java Procedure
In the previous chapters, we often use system out. Println (), so what is it?
println() is a method.
System is a system class.
out is the standard output object.
What is the method:
A Java method is a collection of statements that together perform a function.
Method is an ordered combination of steps to solve a class of problems
Method is contained in a class or object
Methods are created in the program and referenced elsewhere
Advantages of the method:
- Make the program shorter and clearer.
- It is conducive to program maintenance.
- The efficiency of program development can be improved.
- It improves the reusability of code.
Naming rules for methods:
1. The first word of the method's name should start with a lowercase letter, and the following words should start with a capital letter without a connector. For example: addPerson.
2. The underscore may appear in the JUnit test method name to separate the logical components of the name. A typical pattern is: test_, For example, testPop_emptyStack.
Definition of method
Modifier return value type method name(Parameter type parameter name){ ... Method body ... return Return value; }
Method contains a method header and a method body. Here are all parts of a method:
- Modifier: modifier, which is optional and tells the compiler how to call the method. Defines the access type of the method.
- Return value type: the method may return a value. returnValueType
Is the data type of the return value of the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void. - Method name: is the actual name of the method. The method name and parameter table together constitute the method signature.
- Parameter type: the parameter is like a placeholder. When the method is called, the value is passed to the parameter. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.
- Method body: the method body contains specific statements that define the function of the method.
Method call
Java supports two methods of calling methods, which are selected according to whether the method returns a value.
When a program calls a method, the control of the program is handed over to the called method. When the return statement of the called method executes or reaches the closed bracket of the method body, return the control right to the program.
When a method returns a value, the method call is usually treated as a value.
Example:
public class TestMax { /** Main method */ public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( i + " and " + j + " By comparison, the maximum value is:" + k); } /** Returns the larger value of two integer variables */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } }
Overloading of methods
The max method used above is only applicable to int data. But what if you want to get the maximum value of two floating-point data types?
The solution is to create another method with the same name but different parameters, as shown in the following code:
public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; }
If you pass an int parameter when calling the max method, the max method of the int parameter will be called;
If a double parameter is passed, the max method of double type will be called, which is called method overloading;
That is, two methods of a class have the same name, but have different parameter lists.
The Java compiler determines which method should be called based on the method signature.
Method overloading can make the program clearer and easier to read. Methods for performing closely related tasks should use the same name.
Overloaded methods must have different parameter lists. You can't overload methods just based on modifiers or return types.
finalize() method
Java allows you to define such a method, which is called before the object is destructed by the garbage collector. This method is called finalize(), which is used to clear the recovered objects.
For example, you can use finalize() to ensure that the file opened by an object is closed.
In the finalize() method, you must specify the operation to be performed when the object is destroyed.
The general format is finalize:
protected void finalize() { // End the code here }
The keyword protected is a qualifier that ensures that the finalize() method is not called by code outside the class.
Java stream, file, and IO
Java. The IO package contains almost all the classes required for operation input and output. All of these stream classes represent input sources and output destinations.
Java. Streams in io packages support many formats, such as basic types, objects, localized character sets, and so on.
A stream can be understood as a sequence of data. The input stream represents reading data from a source, and the output stream represents writing data to a target.
Read console input
Java console input is provided by system In complete.
In order to get a character stream bound to the console, you can put system In is wrapped in a BufferedReader object to create a character stream.
The following is the basic syntax for creating BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After the BufferedReader object is created, we can use the read() method to read a character from the console or the readLine() method to read a string.
Read multi character input from console
int read( ) throws IOException
Example:
//Use BufferedReader to read characters on the console
import java.io.*; public class BRRead { public static void main(String[] args) throws IOException { char c; // Use system In create BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Input character, Press 'q' Press the key to exit."); // Read character do { c = (char) br.read(); System.out.println(c); } while (c != 'q'); } }
Read string from console
Reading a string from standard input requires the readLine() method of BufferedReader.
The syntax format is as follows:
String readLine( ) throws IOException
Example:
//Use BufferedReader to read characters on the console import java.io.*; public class BRReadLines { public static void main(String[] args) throws IOException { // Use system In create BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'end' to quit."); do { str = br.readLine(); System.out.println(str); } while (!str.equals("end")); } }
The compilation and running results of the above examples are as follows
Enter lines of text. Enter 'end' to quit. This is line one This is line one This is line two This is line two end end
Read write file
A stream is defined as a sequence of data. The input stream is used to read data from the source and the output stream is used to write data to the target.
The following figure is a class hierarchy diagram describing input flow and output flow
FileInputStream
This stream is used to read data from a file, and its object can be created with the keyword new.
There are several construction methods for creating objects.
You can create an input stream object with a string file name to read the file:
InputStream f = new FileInputStream("C:/java/hello");
You can also use a file object to create an input stream object to read the file. First, we have to use the File() method to create a file object:
File f = new File("C:/java/hello"); InputStream in = new FileInputStream(f);
After creating the InputStream object, you can use the following methods to read the stream or perform other stream operations.
FileOutputStream
This class is used to create a file and write data to the file.
If the target file does not exist before the stream opens the file for output, the stream creates the file.
There are two construction methods that can be used to create a FileOutputStream object.
Create an output stream object using a string file name:
OutputStream f = new FileOutputStream("C:/java/hello")
You can also use a file object to create an output stream to write files. First, we have to use the File() method to create a file object:
File f = new File("C:/java/hello"); OutputStream fOut = new FileOutputStream(f);
Other stream operations
Java Scanner class
java.util.Scanner is a new feature of Java 5. We can get user input through scanner class.
The following is the basic syntax for creating Scanner objects:
Scanner s = new Scanner(System.in);
Next, we demonstrate the simplest data input and obtain the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext and hasNextLine to judge whether there is still input data:
import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // Receive data from keyboard // Receive string in next mode System.out.println("next Reception mode:"); // Determine whether there is any input if (scan.hasNext()) { String str1 = scan.next(); System.out.println("The data entered is:" + str1); } scan.close(); } }
Specific results, you can try.
Using the nextLine method:
import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // Receive data from keyboard // Receive string in nextLine mode System.out.println("nextLine Reception mode:"); // Determine whether there is any input if (scan.hasNextLine()) { String str2 = scan.nextLine(); System.out.println("The data entered is:" + str2); } scan.close(); } }
What is the difference between next() and nextLine()
next():
1. Be sure to read valid characters before you can end the input.
2. The next() method will automatically remove the blank space encountered before entering valid characters.
3. Only after entering a valid character will the blank space after it be used as the separator or terminator.
next() cannot get a string with spaces.
nextLine():
1. Take Enter as the ending character, that is, the nextLine() method returns all characters before entering carriage return.
2. You can get blank.
If you want to input data of type int or float, it is also supported in the Scanner class, but you'd better use hasNextXxx() method for verification before entering, and then use nextXxx() to read:
import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // Receive data from keyboard int i = 0; float f = 0.0f; System.out.print("Enter integer:"); if (scan.hasNextInt()) { // Judge whether the input is an integer i = scan.nextInt(); // Receive integer System.out.println("Integer data:" + i); } else { // Enter wrong information System.out.println("The input is not an integer!"); } System.out.print("Enter decimal:"); if (scan.hasNextFloat()) { // Judge whether the input is decimal f = scan.nextFloat(); // Receive decimal System.out.println("Decimal data:" + f); } else { // Enter wrong information System.out.println("The input is not a decimal!"); } scan.close(); } }
The output results are:
$ javac ScannerDemo.java $ java ScannerDemo Input integer: 12 Integer data: 12 Enter decimal: 1.2 Decimal data: 1.2
Java exception handling
Exceptions are some errors in the program, but not all errors are exceptions, and errors can sometimes be avoided.
For example, if your code is missing a semicolon, the result will be that the error is Java lang.Error; If you use system out. Println (11 / 0), then you will throw Java because you use 0 as the divisor Exception of lang.arithmeticexception.
There are many reasons for exceptions, usually including the following categories:
- The user has entered illegal data
- The file to open does not exist
- The connection is interrupted during network communication, or the JVM memory overflows.
Some of these exceptions are caused by user errors, some are caused by program errors, and others are caused by physical errors.
To understand how Java exception handling works, you need to master the following three types of exceptions:
1. Checking exceptions: the most representative checking exceptions are those caused by user errors or problems, which cannot be foreseen by programmers. For example, when you want to open a nonexistent file, an exception occurs. These exceptions cannot be simply ignored at compile time.
2. Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time.
3. Error: the error is not an exception, but a problem out of the control of the programmer. Errors are usually ignored in code. For example, when the stack overflows, an error occurs, and they cannot be checked during compilation.
Hierarchy of Exception class
All exception classes are from Java A subclass inherited by the lang.exception class.
The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable also has a subclass Error.
Java programs usually do not catch errors. Errors usually occur in the case of serious failures, which are outside the scope of Java program processing.
Error is used to indicate an error in the runtime environment.
Exception classes have two main subclasses: IOException class and RuntimeException class
Java built-in exception class
Subclasses of the standard runtime exception class are the most common exception classes. Due to Java Lang package is loaded into all Java programs by default, so most exceptions inherited from runtime exception classes can be used directly.
Java also defines some other exceptions according to various class libraries. The following table lists Java's non checking exceptions.
The following table lists the Java definitions in Java Lang package.
Abnormal method
The following list is the main methods of the Throwable class:
Catch exception
Use the try and catch keywords to catch exceptions. try/catch code blocks are placed where exceptions can occur.
The code in the try/catch code block is called protection code. The syntax of using try/catch is as follows:
try { // Program code }catch(ExceptionName e1) { //Catch block }
The catch statement contains a declaration of the type of exception to catch. When an exception occurs in the protection code block, the catch block after try will be checked.
Example:
In the following example, an array with two elements is declared. When the code tries to access the fourth element of the array, an exception will be thrown.
// File name: exceptest java import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } }
Results obtained after running the above program:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
Multiple capture block
The case where a try code block is followed by multiple catch code blocks is called multiple capture.
Grammatical model
try{ // Program code }catch(Variable name of exception type 1){ // Program code }catch(Variable name of exception type 2){ // Program code }catch(Variable name of exception type 3){ // Program code }
The above code snippet contains three catch blocks.
You can add any number of catch blocks after a try statement.
If an exception occurs in the protection code, the exception is thrown to the first catch block.
If the data type of the exception thrown matches ExceptionType1, it will be caught here.
If it does not match, it is passed to the second catch block.
This is done until the exception is caught or passed through all catch blocks.
This is the end of the basic java tutorial. I will do an advanced Java Tutorial later. You can also pay attention to it. If there are mistakes in the article, welcome to discuss