“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

First Java program

Use Java to say Hello to the World

public class HelloWorld {
	 public static void main(String[] args) {
	        System.out.println("Hello World"); // Output Hello World}}Copy the code

staticIs one of the more difficult keywords to understand.Java Programming ideasA static method is a method without this. You cannot call a non-static method from inside a static method, and vice versa. And you can call static methods just from the class itself without creating any objects. This is actually the main purpose of static methods. In simple terms, a static modifier can be accessed without relying on any object. Source: RUNOOB.COMNote, however, that while non-static member methods and variables cannot be accessed in static methods, static member methods/variables can be accessed in non-static member methods.

Second, basic grammar

To enhance program readability, Java has the following conventions:

  1. Classes, interfaces: Nouns are usually used and the first letter of the word is capitalized (example: HelloWorld)
  2. How to do it: Usually use a verb with the first letter in lower case followed by uppercase segmentation of each word (hump: eatFoodFunction)
  3. Constants: all caps, words separated by underscores (example: PI)
  4. Variables: Nouns are usually used, followed by uppercase division of each word, avoiding the $sign

At the same time, the following points should be noted:

  1. Case sensitive, Hello is not the same as Hello in Java
  2. You cannot use keywords
  3. Know by name! Try to know what a variable stands for as soon as you see its name, okay
  4. The file name of the source file is the same as the public class name and is saved as.java
  5. Basic data types in Java: char 2 bytes (a string of English characters, numbers, symbols, etc.)
  6. Static import: If there are many static methods in the same package, you can use static import
  7. Constructors cannot use recursion
  8. Recursive functions may or may not have a return value
  9. Any class can be declared abstract
  10. Note: A class can only have “final”, “abstract”, and “public” as modifiers
  11. Digits are 0 to 9, and letters are upper and lower case letters, underscores (_), and dollar signs ($). They can also be characters in the Unicode character set, such as Chinese characters
  12. Packages (actually folders, used to manage classes) : All lowercase, multi-level packages separated by dots. General company domain name reverse writing
  13. Don’t use Chinese characters!
  14. Knock and think more!!

Java annotations

Java supports single-line and multi-line comments, and the characters in the comments are ignored by the Java compiler. Example:

/** * multiple line comments *@AuthorDish dish dish dish */

// Single-line comments: This is a Java starter program
public class HelloWorld {
	 public static void main(String[] args) {
		 /* This is also a single line comment output Hello World*/
	        System.out.println("Hello World"); }}Copy the code

Keywords & identifiers

Keywords concept and characteristics

Concept:

  • Java keywords are predefined and have special meaning to the Java compiler. They are used to represent a data type, or the structure of a program, etc. Keywords cannot be used as variable names, method names, class names, package names, or parameters.

Features:

  • All lowercase
  • Special colors in advanced compilers, such as Notepad++, special colors

Keywords:

There are 50 keywords and 3 reserved words that cannot be used to name identifiers in Java.

The keyword instructions The keyword instructions The keyword instructions The keyword instructions The keyword instructions
private private protected The protected public The public default The default abstract Statement of the abstract
class Class declarations extends inheritance final The final implements Implementation (interface) interface The statement interface
native Native methods (non-Java implementations) new create static static strictfp accurate synchronized thread
transient A brief volatile volatile break Jump out of the loop case The switch to choose continue Continue to
default The default do perform else Otherwise, for cycle if if
instanceof The instance return return switch Execute based on the value while cycle assert Asserts whether the expression is true
catch The catching finally Execute with or without exceptions throw Throws an exception object throws Declare that an exception may be thrown try Catch exceptions
import The introduction of package package boolean The Boolean byte Byte type char character
double Double precision floating point float Single precision floating point int The integer long Long integer short Short integer
super The parent class this The class void There is no return value goto The keyword const The keyword

Reserved keywords: true, false, and NULL. Reserved keywords are reserved in Java

What is the identifier

Anything that can be named by itself is called an identifier.

  • Example: project name, package name, class name. Method name

Identifier naming conventions

  • ① Cannot be a keyword
  • ② All identifiers must consist of a letter (A-Z or A-Z) or the numbers 0-9,$, and _
  • ③ Do not start with a number
  • ④ Case sensitive, camel name: FirstName, UserName
  • ⑤ All package names are lowercase, and all class names are big camel
  • ⑥ The meaning is known by its name

For example, project name :writetest Package name: com.ca. test Class name :TestDemo

Constants & variables

Constant: An amount that does not change while a program is running. (character “b”, string “ABC”, the integer 1, Boolean true | false)

Variable: The amount that can be changed during operation. (Local variables, class variables (static variables), member variables (non-static variables))

Scope: Starts on the line that defines a variable and ends with the curly brace to which it belongs.

Basic data types

type The number of bytes Maximum amount of data to be stored Data range
byte eight 255 – 128 ~ 127
short 16 65536 – 32768 ~ 32767
int 32 – 2 to the 32nd minus 1 Minus 2 to the 31st to plus 2 to the 31st minus 1
long A 64 – bit 2 to the 64th minus 1 Minus 2 to the 63rd to plus 2 to the 63rd minus 1
float 32 – 3.4 e-45 ~ 1.4 e38 Direct assignments must be followed by f or f
double A 64 – bit E308 e-324 4.9 ~ 1.8 You can assign with or without d
boolean 1 a The default value is false The value can be true or false
char 16 Store Unicode code Assign values in single quotes

Data type conversion

Automatic type conversion (implicit) : code does not need special processing, automatic completion, small to large

long num1 = 2021112;Copy the code

Casting (explicit) : Code requires special formatting that cannot be done automatically, from large to small

intNum = (int)2021112;Copy the code

Note:

  • 1. Precision loss and data overflow may occur during casting.

  • 2. Byte/short/char all three types can perform mathematical operations, such as addition “+”.

  • 3. The three byte/short/char types are upgraded to int types before they are evaluated. Conforms to the ASCII code table.

Operators & expressions

Arithmetic operator

Arithmetic operators: The four common operators, increment and decrement, do what they do in mathematics.

The operator describe example
+ add 1 + 1 to 2
* Reduction of 2-1 = 1
* take 2 * 5 = 10
/ In addition to 10/2 = 5
++ Since the increase int a=1; a++ or ++a =2
Since the reduction of int a=1; –a or a– =0
% Mod – The remainder of the left operand divided by the right operand 24% = 3

Example:

public class Test1{
    public static void main(String[] args){
        int a = 3;
        int b = 3;
        int x = 2*++a;
        int y = 2*b++;
        System.out.println("A = after the increment operator prefix operation"+a+",x="+x);
        System.out.println("B = after suffixed increment operator"+b+",y="+y); }}Copy the code

Results:

A = after the increment operator prefix operation4, x =8B = after the suffix of the increment operator4, y =6
Copy the code

Relational operator

Relational operators: Relational operators have six relationships: less than, greater than, less than or equal to, greater than or equal to, equal to, and not equal to. The result of the comparison is a Boolean value (true or false).

The operator describe example The results of
> Is greater than 2 > 1 true
> = Greater than or equal to 2 > = 1 true
< Less than 2 < 1 false
< = Less than or equal to 2 < = 1 true
= = Is equal to the 2 = = 1 false
! = Is not equal to 2! = 1 true

Logical operator

Logical operator: Used primarily to perform logical operations and join two Boolean values representing two conditions.

Assume that Boolean variable A is true and variable B is false

The operator describe example The results of
&& with (A && B) false
II or (AIIB) true
! non ! (A && B) true
^ Exclusive or 2 < = 1 A to the B.

Xor: One and only one of them can be true

Example:

public class Test2 {
  public static void main(String[] args) {
     boolean a = true;
     boolean b = false;
     System.out.println("a && b = " + (a&&b));
     System.out.println("a || b = " + (a||b) );
     System.out.println(! "" (a && b) = " + !(a && b));
     System.out.println("(a^b) = "+ (a ^ b)); }}Copy the code

Results:

a && b = false
a || b = true! (a && b) =true
(a^b) = true
Copy the code

The assignment operator

Assignment operator: The basic assignment operator is “=”. It has a lower priority than the other operators, so it is usually read last.

The operator describe example The results of
= Simple assignment operator that assigns the value of the right-hand operand to the left-hand operand C = A + B I’m going to assign the value of A plus B to C
+ = The addition and assignment operator assigns the left-hand operand to the left-hand operand by adding the left-hand and right-hand operand C + = A That’s the same thing as C is equal to C plus A
– = The subtraction and assignment operator, which assigns the subtraction from the left-hand operand to the left-hand operand C – = A That’s the same thing as C is equal to C minus A
* = The multiplication and assignment operator assigns the left-hand operand to the left-hand operand by multiplying the left-hand and right-hand operand C * = A That’s the same thing as C is equal to C times A
/ = The division and assignment operator assigns the left-hand operand to the left-hand operand by dividing the right-hand operand C / = A When C and A are of the same type, it is equivalent to the modulo and assignment operator C = C/A (%) =, which modulo the left-hand and right-hand operands and assigns them to the left-hand operand
< < = The left shift assignment operator C << = 2 The same thing as C is equal to C << 2
> > = The right shift assignment operator C >> = 2 This is the same thing as C = C >> 2
& = Bitwise and assignment operators & C = 2 That’s the same thing as C is equal to C squared
^ = Bitwise xor assignment operator C ^ = 2 That’s the same thing as C is equal to C squared
I= Bitwise or assignment operators C I= 2 That’s the same thing as C is equal to C I2

An operator

Bitwise operators: Bitwise operations are unitary and binary operations on bitwise or binary numbers of bitwise patterns in programming. On many older microprocessors, bit operations are slightly faster than addition and subtraction, and often much faster than multiplication and division.

The operator describe example The results of
& If both corresponding bits are 1, the result is 1; otherwise, it is 0 (kathi Jones from A&B) – You get 12, which is 0000, 1100
I If both corresponding bits are 0, the result is 0; otherwise, it is 1 – (A B)
^ – The result is 0 if the corresponding bit values are the same, otherwise 1 Minus A to the B. – You get 49, which is 0011, 0001
~ – bitwise reverses each bit of the operand, that is, 0 becomes 1,1 becomes 0. – (~ A) -61, which is 1100, 0011
<< – Bitwise left shift operator. The left operand moves the right operand by bits to the left -A << 2 – You get 240, which is 1111, 0000
>> – Bitwise right shift operator. The left operand moves right by bit to the number of digits specified by the right operand -A >> 2 So you get 15 which is 1111
>>> – Bitwise right shift zeroing operator. The value of the left-hand operand moves to the right by the number of digits specified by the right-hand operand, and the resulting space is filled with zeros – A>>>2 – You get 15 which is 0000 1111

Example:

Source / / https://www.runoob.com/java/java-operators.html
public class Test2 {
	  public static void main(String[] args) {
	     int a = 60; /* 60 = 0011 1100 */ 
	     int b = 13; /* 13 = 0000 1101 */
	     int c = 0;
	     c = a & b;       /* 12 = 0000 1100 */
	     System.out.println("a & b = " + c );
	 
	     c = a | b;       /* 61 = 0011 */
	     System.out.println("a | b = " + c );
	 
	     c = a ^ b;       /* 49 = 0011 0001 */
	     System.out.println("a ^ b = " + c );
	 
	     c = ~a;          /*-61 = 1100 0011 */
	     System.out.println("~a = " + c );
	 
	     c = a << 2;     /* 240 = 1111 0000 */
	     System.out.println("a << 2 = " + c );
	 
	     c = a >> 2;     /* 15 = 1111 */
	     System.out.println("a >> 2 = " + c );
	  
	     c = a >>> 2;     /* 15 = 0000 1111 */
	     System.out.println("a >>> 2 = "+ c ); }}Copy the code

Results:

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2  = 15
a >>> 2 = 15

Copy the code

Other operators

The conditional operator (? The: piece operator is also known as the ternary operator. This operator has three operands and needs to determine the value of a Boolean expression. The main purpose of this operator is to determine which value should be assigned to a variable. Example:

public class Test3 {
	 public static void main(String[] args) {
         //x ? y : z
         // if x==true, the result is y, otherwise the result is z
         int score = 80;
         String type = score < 60 ? "Fail":"Pass";// Must be mastered
         //if
         System.out.println(type);
// System.out.println(type); ​
         int score1 = 50;
         String type1 = score < 60 ? "Fail":"Pass"; // Must be mastered
         / / ifSystem.out.println(type1); }}Copy the code

Results:

Fail to pass theCopy the code

Instanceof operator: This operator is used to operate on an object instance and check whether the object is of a particular type (class type or interface type). Example:

String name = "Test";
boolean result = name instanceof String; // Since name is a String, true is returned
Copy the code

expression

Expressions: Expressions connected by operators are called expressions. A combination of numbers, operators, numeric grouping symbols (parentheses), free variables, and constrained variables in a meaningful arrangement that yields a numerical value. For example, 20+5. Another example: A + B

In Java, as; The code at the end is an expression

public class HelloWorld {
    public static void main(String[] args) {
        // Each sentence is an expression
        int i = 5;  / / 1.
        System.out.println(5); / / 2.
        ; / / 3.
        ; / / 4.
        ; / / 5.}}Copy the code

Seven, arrays,

An array is the simplest compound data type. It is a collection of ordered data. Each element in the array has the same data type, and a unified array name and different subscripts can be used to determine the unique elements in the array. According to the dimensions of an array, it can be divided into one-dimensional array, two-dimensional array and multidimensional array.

Example:

public class Test4 {
	public static void main(String args[]) {
		int data[] = new int[3]; /* creates an array of length 3 */
		data[0] = 10; // The first element
		data[1] = 30; // The second element
		data[2] = 50; // The third element
		for(int x = 0; x < data.length; x++) {
			System.out.println(data[x]); // Control indexes through loops}}}Copy the code

Results:

10
30
50
Copy the code

There are three ways to define Java arrays:

  1. 1. Declare first. 2. Allocate space. 3
  2. 1. Declare and allocate space. 2
  3. 1. Declare and allocate space then. The assignment

Example:

public class Test5{
	public static void main(String args[]) {
			System.out.println("----- method 1 -----");
		    int[] arr;    / / statement first
	        arr=new int[5];  // Allocate space
	        for(int i=0; i<5; i++)arr[i]=i*10;  / / assignment
	        for(int i=0; i<5; i++){ System.out.println("arr["+i+"] ="+arr[i]);
	        }
	        
	        System.out.println("----- Method 2 -----");
	        int[] arr1=new int[5];    // Declare and allocate space
	        for(int i=0; i<5; i++)arr1[i]=i*10;    / / assignment
	        for(int i=0; i<5; i++){ System.out.println("arr["+i+"] ="+arr1[i]);
	        }
	        
	        System.out.println("----- method three -----");
	        int[] arr2={20.68.34.22.34}; // Declare and allocate space then. Int [] arr= new []{20,68,34,22,34};
	        for(int i=0; i<5; i++){ System.out.println("arr["+i+"] ="+arr2[i]); }}}Copy the code

Results:

----- method 1 ----- arr[0] =0
arr[1] =10
arr[2] =20
arr[3] =30
arr[4] =40----- method 2 ----- arr[0] =0
arr[1] =10
arr[2] =20
arr[3] =30
arr[4] =40----- method three ----- arr[0] =20
arr[1] =68
arr[2] =34
arr[3] =22
arr[4] =34

Copy the code

Eight, methods,

Methods: Java methods are collections of statements that, when executed together, accomplish some function.

Syntax format:

Modifier returns value type method name (parameter type parameter name1Parameter type Parameter name2...) {execute statement...... ......returnThe return value. }Copy the code

Example:

 public static void main(String[] args){
   int sum = add(1.2); // 1 and 2 are arguments
   System.out.println(sum); 3 / / output
 }
 // A and b are formal parameters and can be defined as any names that comply with the naming rules
 public static int add(int a, int b){
   return a+b;
 }
Copy the code

Note: When designing the program, try to abstract out the contents of the main method as a method call, because the main method is in the stack.

Thank you

  1. Three ways to define arrays in Java
  2. The definition and Use of Arrays in Java
  3. Java instances of an operator, rounding – and (&), not (~), or (|), or (^)
  4. 5, bit operators (7) : instances
  5. JAVA operators and instances
  6. Brief introduction to Java variable assignment operators and related examples
  7. Java assignment operator
  8. Logical operators && | |!
  9. Logical operator
  10. What are Java expressions
  11. expression
  12. .runoob.com
  13. Java Basic Syntax (Summary)
  14. What is a method in Java and how is it defined
  15. What is a Java method?