Java basics: basic knowledge

Java basics: basic knowledge

Contents:
1. Java overview
1. Java system
2. Commonly used DOS commands
3. JDK, JRE, cross-platform, Java platform
4. Java code writing and execution process
5. Notes
6. Keywords, identifiers
7. Java Data type
8. Constants in Java
2. Variables and operators
1. Variables and computer storage units
2. Data types and constants
3. Data type conversion
4. Operators and precedence
3. Reference data types, flow control statements and arrays
1. Reference data type
2. Flow control statement
3. Array
4. Method
1. Import
2. Syntax format
3. Method call
4. Note
5. Method overload
6. Variable parameter list

1. Java overview

1. Java system

  • Java is a system that includes :

  • java language

  • Virtual machines running on various platforms

  • class bytecode file format

  • java api (api provided in jdk), class library

  • Commercial or tripartite excellent open source library

Java system

2. Commonly used DOS commands

Commonly used DOS commands

3. JDK, JRE, cross-platform, Java platform

  • JDK : It is a Java development and operating environment. Of course, JDK must be installed on the programmer's computer;

JDK = JRE + development tool set (such as Javac compilation tools, etc.)

  • JRE : Java Runtime Environment is a Java runtime environment. If you don t need to develop and only need to run Java programs, then you can install JRE

JRE = JVM + JavaSE Standard Class Library

  • JDK contains JRE contains JVM

  • Cross-platform features

  • Platform refers to the operating system (Windows, Linux, Mac).

  • Java programs can be run on any operating system, written once and run everywhere

  • The realization of cross-platform needs to rely on Java virtual machine JVM (Java Virtual Machine)
    Why can cross-platform? Because the running of JAVA programs relies on virtual machines, and there are different versions of virtual machines for different operating systems

  • Java language is cross-platform, Java virtual machine is not cross-platform

  • Java platform

  • Java SE (Desktop Program) Standard Edition

  • Java EE (Web Program) Enterprise Edition

  • Java ME (Mobile Device) Micro Edition-Android, IOS has rarely been used since the rise

4. The writing and execution process of Java code

  • Source file : write Java source file (we also call it source code file), its extension is .java;
  • Compile : Then use the compiler to compile the source file into a bytecode file, the bytecode file extension is .class;
    why compile? JAVA program is run by a virtual machine, the code we write is not recognized by the virtual machine, we Translate the code written by yourself into a language recognized by the virtual machine
  • Run : Finally, use the interpreter to run the bytecode file.

The writing and execution process of Java code

5. Notes

  • Definition : The text used to explain and explain the program, the comment will not be executed

  • Category :

  • Single line comment ://Comment content

  • Multi-line comment :/*Comment content*/

  • Document comment :/**Comment content*/

  • Note :

  • For single-line and multi-line comments, the annotated text will not be interpreted and executed by the JVM

  • The documentation comments can be parsed by the tool javadoc provided by the JDK to generate a set of documentation for the program in the form of web pages

  • Single-line comments can be nested, and multi-line comments cannot be nested

6. Keywords, identifiers

  • Keyword

  • Definition : It is a word that is given a special meaning by the Java language and has a special purpose. For example, the class, int, and double that have been contacted before are all preset by Java

  • Features : All lowercase letters, note that String is not a keyword

  • Note : goto and const are reserved words in Java, that is, words that are not given a special meaning but are still occupied by Java

  • Identifier

  • Definition : the character sequence used when naming classes, interfaces, methods, variables, etc.

  • Composition rules (can only contain the following content, no other content):

  • English uppercase and lowercase letters

  • Numeric characters

  • $ And _

  • Matters needing attention :

  • Number cannot start

  • Keywords cannot be used

  • Strictly case sensitive, unlimited length

  • When naming, try to be as clear as possible

  • Common naming rules in identifiers (these rules are not subject to grammatical constraints):

  • Package name : when multiple words are formed, all letters are lowercase, use. To connect, and the domain name is reversed aaa.bbb.ccc

  • Class name & interface name : big hump type Aaa AaaBbbCcc

  • Variable name & method name : small camel case aaa aaaBbbCcc

  • Constant name : Multi-word composition is all letters in uppercase, use _ to connect AAA_BBB_CCC

7. Data Types in Java

Why are there data types ? The
Java language is a strongly typed language. For each type of data, a clear specific data type is defined

  • Classification of data types in Java

  • Basic data types : Basic data types are built-in types in the Java language, which are integer type, decimal type, character type, and boolean type. These four basic types are the simplest and most basic types.

  • Reference data type : It is a powerful data type, which is created based on basic data types.

  • A super class library is provided in JavaSE, which contains nearly ten thousand reference data types.

  • Basic type : class interface array enumeration

8. Constants in Java

  • Definition : A constant is a constant amount of data, and its value cannot be changed during the execution of the program
  • Integer constants are of type int by default

In Java, if the value of long integer data exceeds the range of int, it must be +L, otherwise it is wrong.

  • The decimal constant is of type double by default

The suffix D is double, and the suffix F is float
. The data of the float type must be followed by + f, otherwise the default is double

  • Constant classification :

  • Integer type

  • Decimal representation: normal numbers. Such as 13, 25, etc.

  • Binary representation: start with 0b (0B). Such as 0b1011, 0B1001

  • Hexadecimal representation: start with 0x(0X). Numbers are composed of 0-9 and AF, such as 0x23A2, 0xa, 0x10

  • Octal representation: start with 0. Such as 01, 07, 0721

  • Decimal type : such as 1.0, -3.15, 3.168, etc.

  • Boolean type : true, false, pay attention to strict case sensitivity

  • Character type :

  • Such as'a','A', '0','home'

  • Characters must be wrapped with ``, and it can only contain one character

  • String type :

  • String String type is a reference type, we first understand how to use it as a constant type

  • Such as "I love Java", "0123", "", "null"

  • The string must be wrapped with "", any length

  • In the computer, there are three representations of signed numbers: original code, inverse code and complement . All operations are based on data complement performed

  • Original code : +8: 0 000 1000 -8: 1 000 1000

It is the binary fixed-point representation, that is, the highest bit is the sign bit, 0 means positive, 1 means negative, and the remaining bits represent the magnitude of the value.

  • Inverse code : +8: 0 000 1000 -8: 1111 0111

The inverse code of a positive number is the same as the original code; the inverse code of a negative number is the inverse of its original code bit by bit, except for the sign bit.

  • Complement : +8: 0 000 1000 -8: 1111 1000

The complement of a positive number is the same as its original code; the complement of a negative number is the last bit of its complement plus 1

2. variables and operators

1. Variables and computer storage units

  • Variables are small boxes loaded with data in memory, you can only use them to store data and fetch data

  • Variable names are identifiers, which means that as long as they are legal identifiers, they can be used as variable names.

  • Notes on the use of variables

  • After the variable is defined, it is not necessary to assign a value, and then assign it when it is used. Cannot be used without assignment

  • There are scope restrictions when using variables. (Local variables and global variables)

  • Variables cannot be defined repeatedly

  • Computer storage unit

  • The smallest unit of storage and operation in a computer: one byte, that is, one byte (byte)

  • Common storage unit 1B (byte) = 8bit (bit)

1KB = 1024B
1MB = 1024KB
1GB = 1024MB
1TB = 1024GB 1PB
= 1024TB

2. Data types and constants

  • 4.categories and eight species

byte: 1 byte: -128 127 (data display range)
short: 2 bytes: -32768 32767
int: 4 bytes: -2147483648 2147483648
long: 8 bytes: -2^63 2^63-1
float: 4 bytes: -3.403E38 3.403E38
double: 8 bytes: -1.798E308 1.798E308
char: 2 bytes: represents a character, such as ('a','A ','0','home')
boolean: 1 byte: only two values true and false

  • Variables must have a clear type, what type of variable is loaded with what type of data
  • The data type range is sorted from small to large:

byte <char <short <int <long <float <double,
Boolean type boolean cannot participate in type conversion

3. Data type conversion

  • Automatic type conversion : indicates that a data type with a small range is converted into a data type with a large range. This method is called automatic type conversion.
    Automatic type conversion format : a large range of data type variables = a small range of data type values;

Default conversion : byte, short, char > int > long > float > double
byte, short, char are not converted between each other, they participate in the operation and first converted to int type

  • Coercive type conversion : indicates that a data type with a large range is converted to a data type with a small range. This method is called a coercive type conversion

Coercive type conversion format : small range data type variable = (small range data type) large range data type value;

4. Operators and precedence

Arithmetic Operator

+-*/% ++ -

+ : Positive sign, addition, and concatenated string
**++, --** When the operator is followed by, first use the original value of variable a to participate in the operation. After the operation is completed, the value of variable a will increase by 1 or automatically Subtract 1; When the
**++, --** operator is preceded, the value of the variable a is first incremented or decremented by 1, and then the updated new value is used to participate in the operation.

  • Matters needing attention :

  • The addition operator should pay attention when concatenating strings. Only when directly added to the string will it be converted into a string.

  • Division When both sides are integers, take the integer part and round off the remainder. When one of the sides is floating point, divide according to normal rules.

  • % Is the sign for the remainder of the divisor, and the remainder of the decimal is meaningless. The result sign is the same as the remainder sign.

  • An integer is the dividend, and 0 cannot be the divisor, otherwise an error will be reported.

  • The decimal is used as the dividend, the result of dividing 0 is Infinity , and the result of modulo 0 is NaN

Assignment operator

+= -= *=/= %=

  • ** + =, - =, * =,/= ** This assignment operator includes a cast operation, the result will be the right and left sides of the operation, after the cast is assigned to the left

  • Note: The left side of the assignment operator must be a variable

    int n = 10; byte by = 20; by += n;//After the calculation, the value of by is byte type 30, which is equivalent to the code by = (byte)(by + n);

Comparison operator

== != <> <= >=

  • The result can only be true and false
  • Comparison between characters, comparing their ASCII value
  • Floating point number and integer comparison, as long as the value is equal, it returns true

Logical Operators

&And-----false&true-----False
|or-----false|true-----True
^XOR-----true^flase-----True
!non- ----!true-----Flase
&& short-circuit and -----false&&true-----False
||short-circuit or -----false||true-----True

  • && : Also called the short-circuit operator, A&&B, if A is false, the value of B will not be calculated, and the result will be false.
    & : A & B, even if A is false, the value of B will be calculated.
  • || : is also a short-circuit operator, A || B, if A is true, the value of B will not be calculated, and the result will be true
    | : A | B, even if A is true, the value of B will be calculated.
  • XOR^ : If the left and right conditions have the same result, the result is false, and the left and right conditions have different results, and the result is true;

Ternary operator

  • Syntax: Boolean expression? Expression 1: Expression 2
  • When the value of the Boolean expression is true, the value of expression 1 is returned, otherwise the value of expression 2 is returned

Operator precedence

Priority description operator
1 Brackets (), []
2 Sign +,-
3 Increase and decrease, not ++, --,!
4 Multiply and divide, take remainder *,/,%
5 Add and subtract +,-
6 Shift operation <<, >>, >>>
7 magnitude relation>, >=, <, <=
8 equal relation ==, !=
9 bitwise and &
10 bitwise exclusive or ^
11 bitwise OR |
12 logic AND &&
13 Logical OR ||
14 Conditional operation?:
15 Assignment operation =, +=, -=, *=,/=, %=
16-bit assignment operation &=, |=, <<=, >>=,> >>=

Bit operator

Bit operator

  • Bit computing is a direct binary calculates

  • Bit operation, the operand must be an integer

  • The characteristics of the bitwise exclusive OR operator :

  • One data is XORed twice with another data bit, and the number itself remains unchanged.

  • XOR any number with itself, the result is 0

  • XOR any number and 0, the result is itself

  • << Shift one place to the left, which is equivalent to multiplying by 2 : 3 << 2 = 12 --> 3

    2

    2=12

  • >> Shift one place to the right, which is equivalent to dividing by 2 : 3 >> 1 = 1 --> 3/2=1

  • 3 >>> 1 = 1 --> 3/2=1

  • The same operation, the efficiency of bit operation is higher than arithmetic operation

3. reference data types, flow control statements and arrays

1. Reference data types

  • The variable definition and assignment format of the reference data type: data type variable name = new data type();

  • Call the function of this type of instance: variable name. method name ();

  • Scanner class :

  • Guide package : import java.util.Scanner;

  • Create an object instance : Scanner sc = new Scanner(System.in);

  • Calling method :

    int i = sc.nextInt();//used to receive the number entered by the console String s = sc.next();//used to receive the string entered by the console

  • Random

  • Method introduction

    public int nextInt(int maxValue)//Generate a random integer in the range of [0,maxValue), including 0, excluding maxValue; public double nextDouble()//Generate a random decimal in the range of [0,1), including 0.0, not including 1.0.

Random usage :

  • Import guide package : import java.util.Random
  • Create instance format : Random variable name = new Random();
  • Assignment : a = variable name.nextInt(maxValue);

2. Flow control statement

1. if 2. if...else... 3. if...else if...else... 4. while 5. for 6. do...while... 7. switch case default break //case penetrability: If the execution statement after multiple case conditions is the same, the execution statement only needs to be written once, which is a shorthand method Copy code

break statement

  • Role : Jump out of the loop body

  • How to use

  • Can not be used alone, break the keyword must be placed switch or loop in

  • Operation law

  • There is no need to judge any conditions, as long as it encounters a break change, it jumps out and executes the subsequent code. Will completely jump out of the selection or loop structure

  • Only out of the nearest code block, not across multi-level code blocks

  • mark

  • When the break statement appears in the inner loop of the nested loop, it can only jump out of the inner loop. If you want to use the break statement to jump out of the outer loop, you need to add a mark to the outer loop

  • Usage : Use it in front of a line outside the outer loop, followed by an identifier with a colon:, that is, the definition is complete.

  • When using, when break or continue is used in the inner loop , it can be followed by the label defined before.

    itcast: for (i = 1; i <= 9; i++) {//outer loop, itcast is marked for (j = 1; j <= i; j++) {//inner loop if (i> 4) {//Determine whether the value of i is greater than 4 break itcast;//Jump out of the outer loop}}

continue statement

  • Role : End this cycle early and continue to the next cycle
  • Use : can not be used alone, it continues keyword must be placed loop in
  • Running law : No need to judge any conditions, just jump out of the current cycle and proceed to the next cycle as long as you encounter continue

The difference between return, break, continue to jump out of control statements

  • break : End the current entire loop and execute the statement below the current loop.
  • continue : End this cycle and continue to the next cycle
  • return : Used to end a method and return to the upper caller. If it is in the main method, it is equivalent to ending the program.

Return can also be used to end a loop, because return is used to end a method. If there is a loop in the method, no matter how many levels of loops return is nested in, the loop will end.
The statement after the loop will no longer be executed

3. Array

One-dimensional array

  • Overview : immutable length, same element type

  • A set of data, each data in the array is called an'element'

  • You can store elements of any type in the array

  • But the types of elements stored in the'same array' must be consistent.

  • The array is'constant, fixed length

  • Array definition 1

  • Format : data type [] array name = new data type [length]; int[] x = new int[100];

  • Use attribute : array name.length

  • The minimum index of the array is 0, and the maximum index is the array. length-1

  • Array definition 2

  • Array initialization : Specifies the length of the array is defined only when the array elements automatically by the system initial value called dynamic initialization manner.

  • Format :

  • Data type [] Array name = new type [length]; int[] arr = new int[4];

  • Type[] array name = new type[]{element, element,...}; int[] arr = new int[]{1,2,3,4};

  • Type [] array name = {element, element, element,...}; int[] arr = {1, 2, 3, 4 };

JVM memory division

  • Register : between memory and CUP
  • Local method stack : JVM calls functions in the system
  • Method and data sharing : where the class file enters during runtime
  • Method stack : all methods enter memory when running
  • Heap : Stores containers and objects

Common exceptions in arrays

  • Array index out of bounds exception
  • Null pointer exception

Two-dimensional array

  • Define the format

    //The first definition format is equivalent to defining a 3*4 two-dimensional array, that is, the length of the two-dimensional array is 3, and each element in the two-dimensional array is an array of length 4

    • int[][] arr = new int[3][4];//not recommended

    //The second definition format//The second method is similar to the first, except that the length of each element in the array is uncertain, and new: arr[0] = new int[5];... int[ ][] arr = new int[3][];

    //The third definition format//There are three elements defined in a two-dimensional array. These three elements are all arrays, namely {1,2}, {3,4,5,6}, {7,8, 9} int[][] arr = {{1,2},{3,4,5,6},{7,8,9}};

Two-dimensional array memory

  • For example: int[][] arr = new int[3][2];
  • The outer array grows in the memory to open up 3 continuous large memory spaces, and each memory space corresponds to an address value.
  • Each large memory space opens up two consecutive small memory spaces.

Print array

//5.ways to print a one-dimensional array Arrays.toString(arr) for(int n: arr) System.out.println(n+", "); for (int i = 0; i <arr.length; i++) { System.out.print(arr[i] + ", "); } System.out.println(Arrays.asList(arr)); Arrays.asList(arr).stream().forEach(s -> System.out.println(s));//java8 //3.types of printing two-dimensional arrays for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[i].length;j++) { System.out.print(arr[i][j]+" "); } System.out.println();//Line break } for(int[] a:arr) { for(int b:a){ System.out.print(b+" "); } System.out.println();//line feed } for(int i=0;i<arr.length;i++) System.out.println(Arrays.toString(arr[i])); //3.three-dimensional arrays for printing int [][][] arrays=new int[4][3][2];//Create a space in the stack space for(int i=0;i<arrays.length;i++) { for(int i1=0;i1<arrays[i].length;i1++) { for(int i2=0;i2<arrays[i][i1].length;i2++) { System.out.print(arrays[i][i1][i2]); } System.out.println();//Two-dimensional line feed } System.out.println();//Three-dimensional line break } Copy code

4. the method

1. Introduction

Why is there a method : to improve the reusability of the code
What is a method : a code block that completes a specific function

2. Syntax

  • Access modifier : The scope of permission that the method allows to be accessed. (public, protected, private, no modifier)
  • Return type : void, any data type
  • Method name : Same as variable name rules. Lower case; For multiple words, the first letter of the first word is lowercase, and the remaining first letters are uppercase. myMethod
  • Parameter list : can be omitted. Parameter type + parameter name,...

3. Method call

  • You can use the object name calling methods, static methods is to use the class name calling

  • The method is included in the class, and the object of the class containing the method is created when calling, and then the object is used to call the method.

  • Create an object : class name object name = new class name ();

  • Call : object name. method name ();

4. Matters needing attention

  • Method parameter is the basic type , the value is passed. (Including String type), the change of formal parameters does not affect the actual parameters
  • Method parameter is a reference type , memory address value is passed. (Except for String type), the change of the formal parameters has an impact on the actual parameters
  • The definition of the method can only be placed in the class, not nested definitions . Therefore, the method cannot be defined directly in the main method
  • The method return value is void, return can be omitted in the method
  • The method is generally defined before the main method
  • When the method is called, the return value is void, which cannot be written in the output statement

5. Method overloading

  • Method overloading : In the same class, the method name is the same, but the parameter list is different. It has nothing to do with the return value type.

  • The parameter list is different :

  • The number of parameters is different

  • Different parameter types

  • The order of the parameters is different (it is overloaded, but not used in development). Note: it must be of different data types. The same type does not exist in a different order

  • Method overload considerations

  • Overloading has nothing to do with parameter variable names

  • Overloading has nothing to do with the return value type. For example, void method (int x) and int method (int y) are not method overloads and cannot exist at the same time.

  • Overloading has nothing to do with modifiers

  • Look overloaded method name and parameter list

6. Variable parameter list

  • Example: public void sum(int... n){}

  • If there are more than two parameters in the parameter list, the variable parameter must be at the end

  • You can pass an array to a variable parameter list

  • When an array is used as a parameter, you cannot pass multiple values to the array

  • The formal parameter list of a method can only have one variable parameter list

  • The same method name, a parameter is a variable parameter, the parameter is a one-dimensional array, the two methods are not overloaded, as a variable parameter equivalent to a corresponding type of one-dimensional array
    can be of variable argument lists, corresponding Array operations, such as finding the length

  • The method where the variable parameter list is located is the last to be executed and accessed

  • Method overloading when both methods have the same name can be defined variable parameters can also define methods to determine the number of arguments, when calling the method jvm, priority calls have the number of parameters to determine the method of

If you need to get more java learning materials, you can privately "learn" to the editor to get it!