Java basic programming structure

Keywords: Programming Java jvm

Sketch

Java originated from Oak, a development language developed by Sun company for set-top box, which was renamed "Java" because of its name. Java is an object-oriented development language. Its characteristic is "compile once, run everywhere". This implementation depends on JVM.

Basic design of Java program

A basic Java program consists of a class and its main entry:

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

HelloWorld explanation, as shown in the above code:

  • Public: access modifier, which controls the access level of other programs. Public is public and can be accessed by any class
  • Class: class keyword is used to declare a class, followed by the class name
  • {}: commonly known as block, HelloWorld {} is also called class block. main(String[] args) {} is also called method block
  • Main method to identify the main program entry of this class. The main method is fixed.
  • System.out is a class, println is a method, and "HelloWorld!" is the parameter using the method, that is, the parameter calling System.out class println method is HelloWorld!
  • ";" terminator, used after a method to indicate that a method has been used. Used after a variable to indicate that a variable has been declared. Used in a process to indicate the end of the process

Standard

  1. Declaration specification
    1. Class followed by class name
    2. Any class must have {}
    3. Fixed format of main method
    4. The parameters of each method must be declared inside ()
  2. Usage specification
    1. Static method consists of class name and method name
    2. Use the method with parameters. Put parameters through (), System.out.println (string parameter)
    3. Use ';' to terminate the method
  3. Naming specification
    1. Use camel nomenclature
    2. A class named by more than one word, each capitalized. For example: CamelCase
    3. $u starts with an alphanumeric character$_
public class HelloWorld{
	public static void main(String[] args) {  
		String x;  
		String $1;  
		String _1;  
		String $_a;  
		String $_abcd123;  
		String abcd123;  
	}
	
	class A{}
	
	class B1{}
	
	class _C{}
	
	class $C1{}
	
	class $C1_{}
}
  1. Annotation specification
//Single line notes

/*
multiline comment
*/

/**
Documentation Comments
*/

Java data types

java is a strongly typed language, which declares a type for each variable. There are eight primitive type s in java: byte, short, int, long, float, double, char, boolean

Integer type:

type Range of values
byte -128 ~ 127 (- 7 power of 2 ~ 7 power of 2-1)
short -32768 ~ 32767 (- 15 power of 2 ~ 15 power of 2-1)
int -2147483648 ~ 2147483647 (- 31 power of 2 ~ 31 power of 2-1)
long -9223372036854775808 ~ 9223372036854775807 (- 63 power of 2 ~ 63 power of 2-1)
byte bNum = 10;
short sNum = 10;
int inum = 10;

//Long is also called long shaping. Generally, l or l will be added after the declared value (lowercase L is not recommended. It is difficult to distinguish whether this is 1 or l).
long lNum = 10L;

/**
Be careful:
1.By default, the value uses int as the type. When byte is used as the type, it is an implicit conversion, similar to:
byte bNum = (byte) 10;
short sNum = (short)10;

2.When facing long integers, you can use "" to divide numbers, and the underline will be removed during compilation, similar to:
long lNum = 1_000_000_000L;

3.java The program reserves the use of binary, octal and hexadecimal as follows:
int x = 0b1001;  //9
int x = 010; // 8 
int x = 0x10; //16
*/

Floating point number

type Storage requirement Range of values
float 4 byte About ± 3.402 823 47e + 38F (significant digits are 6-7)
double 8 byte About ± 1.797 693 134862 315 70E + 308 (15 significant digits)
float fNum = 0.125F;
double dNum = 0.30D;

/**
By default, they are floating-point numbers of double type. If you need to declare them as float, you need to add f to the value.
*/

char type

char x = 'A';//Need to be enclosed in quotation marks

boolean

boolean x = true;
x = false;

//Boolean type, used to describe true | false, used for logical judgment

Variable constant

//Type space variable name assignment symbol value terminator; (semicolon)

//variable
int x = 10;

//Static variables
static int STATIC_X = 10;

//constant
final int fx = 10;

//Class constant
static final int MAX_NUMBER = 10;

/**
After variable initialization, the value is variable.
Static variable, declared in a class, named in all uppercase, variable value
 After constant initialization, the value is immutable.
*/

operator

In Java, arithmetic operators include +, -, *, / for addition, subtraction, multiplication and division. When both operands involved in / operation are integers, it means an integer division; otherwise, it means floating-point division. The remainder (modulo) of an integer is done using%.

Binary operator: x += 2 is equivalent to x = x + 2. General operators should be placed on the left side of = e.g. * =, / =-= If the operator gets a value that is different from the left operand type, a cast occurs. x += 3.5 is legal (int)(x + 3.5)

Autoincrement and autodecrement operators: + +, -, which distinguish prefixes and suffixes.

int m = 7;
int n = 7;

int a = 2 * m++; // a = 14, m = 8
int b = 2 * ++n; // b = 16, n = 8

Relational and boolean operators:

boolean x = 3==7; //Or 3! = 7, return true or false

boolean x = 3 > 7 || 3 < 7 || 3 >= 7 || 3 <= 7;

/**
	&& Logical and, & and operation
	|| Logical or, | operation
	! Logical non operation.
	&&Indicates short circuit and, ||indicates short circuit or
*/
expression1 && expression2. Both are true Only then true
expression1 || expression1. Both are false Only then false,Just one true Go ahead
!expression. Logical non operator, true,false Interconversion

//Binomial operator:
condition ? expression : expression2;
x > y ? 1 : 0;

int x = 1 > 2 ? 0 : 1; //x equals 1

Bitwise Operators

&("and") | ("or") ^ ("xor") ~ ("not")

Move N bits to the left

"< shift right N bits

"Move right N bits without symbols"

High position supplement 0

Operator level

operator Associativity
[].() From left to right
! ~ + + - + (unary operation) - (unary operation) () (CAST) new From right to left
* / % From left to right
+ - From left to right
<< >> >>> From left to right
< <= > >= instanceof From left to right
== != From left to right
& ^ | From left to right
&& || From left to right
?: From right to left
= += -= *= /= %= &= |= ^= <<= >>= >>>= From right to left

String: String

String is the character enclosed by double quotation marks, string x = ABCD; the value created by string is immutable. If you need to change the value of string, you can use StringBuilder and StringBuffer.

String common methods:

x.equals("string"); compare string values for equality. x == y compare the memory addresses of the two

boolean equals(String x); whether the two string values are the same
 Boolean equalsignorcecase (string other); ignore case comparison to see if the strings are the same
 boolean startsWith(String prefix); whether the prefix is this string
 boolean endsWith(String suffix); whether to end with the string
 int indexOf(String str); check the str's position in the current string, starting from 0 to the subscript, without returning - 1
 int lastIndexOf(String str); check the str's position at the end of the string, start matching from the end, and return - 1 if not
 int length(); get string length
 String substring(int beginIndex); gets from the specified start to the end and returns the substring
 String substring(int beginIndex, int lastIndexOf); specifies the beginning and ending string truncation and returns
 String trim(); remove white space at beginning and end
 String toUpperCase(); capitalize all
 String toLowerCase(); all lowercase

control flow

Single conditional statement, result if(true)implement ifstatement,Otherwise execution elstatement
if(condition){
	ifstatement
}else{
	elstatement
}

//Multi conditional statement
if(condition){
	statement
}else if(condition){
	statement
}else{
	statement
}

//loop
while If the cycle condition is true, the cycle will continue until the cycle condition is false
while(condition){
	statement
}

do-while Cycle, at least once. Test cycle conditions are false Stop, otherwise cycle
do{
	statement
}while(condition);

//Definite cycle
for(initialize;condition;increment);

for(int i = 0; i < 10; i++){
	System.out.println(i);
	
	/**
	0,i == 1
	1,i == 2
	2,i ==3
	3,i == 4
	4,i == 5
	5,i == 6
	6,i == 7
	7,i == 8
	8, i == 9
	9, i == 10
	Loop terminated because 10 < 10 is false
	*/
}

//Multiple choice
//If the number following the case is x, the statement in the case is executed. If the case does not use break to end the control, the statement is executed until the break or switch ends.
//For example, if x = 10, case 11 and case 12 will be executed after case 10 is executed successfully, and the break of default will not be terminated
default Indicates default. If none of them match, execute default Statement block in
switch(x){
	case 1:
		System.out.println("1")
		break;
	case 10:
	case 11:
	case 12:
	default:
		break;
}


break The keyword can be used to end the loop and end the control. For example:
while(true){
	break;
} The program should have been circulating, but break,The cycle is broken. This situation has been avoided

for(int i = 0; i < 10; i++){
	if(i == 3) break;
} When i == 3 Stop the cycle

int x =10;
do{
	if(--x == 3){
		break;
	}
}  First pair x Minus one, if x == 3,End cycle


lable:statements
label(Label) block to control a block. For example:
int size = 100;
read_data:
	while(true){
		if(--size == 30){
			break read_data;
		}
	} read_data So while Cycle, break Will only terminate read_data block

//It can also be used in this way to indicate that x is only used in the read ﹣ data block:
read_data:{ int x = 10; }

array

int[] x; declare that x variable is an int array, and use [] to indicate that it is an array. There are two declaration methods: int[] x; int x []; generally use the former one, and the latter one because it is difficult to distinguish whether it is a variable name or not when it is put together with a variable name
 Array of basic data types, with default values. All elements of int [] are 0

String[] str = new String[size]; size is the size of the array, which means how many strings can be accommodated in the array. Each string in the array is null by default, and the object array is null by default

int[] num = {1,2,3}; it is declared that num is an int array with three elements, namely 1, 2, 3. This is an array declaration with initialization

Multidimensional array:
int[][] mn = new int[3][2]; declare a 2-dimensional array. You can get the first element of the first group through mn[0][0], and so on

Array tool class: Arrays
 static String toString(type[] a); returns a string containing the data elements in a, which are placed in {} and separated by commas, {1,2,3}

static type copyOf(type[] a, int length); copy an array and specify the number of copies
 static void sort(type[] a); sort arrays
 static int binarySearch(type[] a, type v); sort arrays by dichotomy
 static boolean equals(type[] a,type[] b); check whether two arrays are the same




Posted by eelmitchell on Sat, 22 Feb 2020 03:13:30 -0800