[Java Core Technology] Java Basic Grammar

insert image description here

1. Keywords and reserved words

Keyword Definition and Characteristics

  • A string (word) that is endowed with special meaning by the Java language and used for special purposes
  • All letters in keywords are lowercase

Definition of reserved words

  • Not used by existing Java versions, but may be used as a keyword in future versions. Avoid these reserved words when naming identifiers.

Summary: 48 keywords, 2 reserved words, 3 literal values

用于定义数据类型的关键字
class interface enum byte short int long float double char boolean void
用于定义流程控制的关键字
if else switch case default while do for break continue return
用于定义访问权限修饰符的关键字
private protected public
用于定义类,函数,变量修饰符的关键字
abstract final static synchronized
用于定义类与类之间关系的关键字
extends implements
用于定义建立实例及引用实例,判断实例的关键字
new this super instanceof
用于异常处理的关键字
try catch finally throw throws
用于包的关键字
package import
其他修饰符关键字
native strictfp transient volatile assert
保留字
goto const

用于定义数据类型值的字面值
true false null  true

2. Identifier

Definition of identifier

  • The sequence of characters used by Java to name elements such as variables, methods, and classes is called an identifier

Skill: Any place where you can name it is called an identifier

Define legal identifier rules

  • Consists of 26 uppercase and lowercase English letters, 0-9, _ or $
  • numbers cannot start with
  • Keywords and reserved words are not allowed, but can contain keywords and reserved words
  • Strictly case-sensitive in Java, unlimited length
  • Identifiers cannot contain spaces

Naming Conventions in Java

  • Package name: All letters are lowercase when composed of multiple words: xxxyyyzzz
  • Class name, interface name: When composed of multiple words, the first letter of all words is capitalized: XxxYyyZzz
  • Variable name, method name: When composed of multiple words, the first letter of the first word is lowercase, and the first letter of each word is capitalized at the beginning of the second word: xxxYyyZzz
  • Constant name: All letters are capitalized, and each word is connected with an underscore when there are multiple words: XXX_YYY_ZZZ

Points to note:
1. When choosing a name, in order to improve readability, it should be as meaningful as possible, "see the name and know the meaning".
2. Java uses the unicode character set, so identifiers can also be declared using Chinese characters, but it is not recommended.

3. Variables

The concept of variables

  • a storage area in memory
  • The area's data can vary continuously within the same type range
  • A variable is the most basic storage unit in a program, including variable type , variable name , stored value

The role of variables

  • for storing data in memory

Note on using variables

  • Every variable in Java must be declared first and then used
  • Use variable names to access data in this area
  • The scope of a variable: within a pair of {} where it is defined
  • Variables are valid only within their scope
  • Variables with the same name cannot be defined in the same scope

Classification of variables

Classified by data type

  • basic data type
    • numeric
      • Integer type (byte short int long)
      • Floating point type (float double)
    • Character type (char)
    • Boolean (boolean)
  • reference data type
    • class _
    • interface _
    • array ([])

Sort by declaration location

  • Member variables
    • Instance variables (not modified with static)
    • Class variables (decorated with static)
  • local variable
    • Formal parameters (variables defined in methods, constructors)
    • Method local variables (defined inside the method)
    • Code block local variables (defined within a code block)

Integer variables: byte, short, int, long

  • Each integer type in Java has a fixed table number range and field length, which is not affected by the specific OS, so as to ensure the portability of Java programs.
  • Java's integer constants are of int type by default, and the declaration of long type constants must be added lorL
  • Variables in Java programs are usually declared as int, and long is used unless it is not enough to represent a large number
type take up storage space Table number range
byte 1 byte = 8bit -128~127
short 2 bytes - 2 15 2^{15} 215~ 2 15 2^{15} 215-1
int 4 bytes - 2 31 2^{31} 231~ 2 31 2^{31} 231 -1 (about 2.1 billion)
long 8 bytes - 2 63 2^{63} 263~ 2 63 2^{63} 263-1

bit: The smallest storage unit in a computer. byte: The basic storage unit in a computer.

Floating point type: float, double

  • Similar to the integer type, the Java floating-point type also has a fixed table number range and field length, which is not affected by the specific operating system
  • Floating-point constants have two representations:
    • decimal form
    • scientific notation form
  • float: single precision, the mantissa can be accurate to 7 significant figures. In many cases, the accuracy is difficult to meet the demand.
  • double: Double precision, twice the precision of float. This type is usually used.
  • Java's floating-point constants are double by default. To declare a float constant, add for after it F.
type take up storage space Table number range
float 4 bytes -3.403E38~3.403E38
double 8 bytes -1.798E308~1.798E308

Note: float means that the range of values ​​is larger than long

How to calculate the range of float values?

According to the IEEE754 standard, the sign bit, exponent bit, and significand bit are divided for calculation.

Character type: char

  • Char type data is used to represent "characters" in the usual sense (2 bytes)
  • All characters in Java use Unicode encoding, so a character can store a letter, a Chinese character, or a character of other written languages.
  • Three manifestations of character variables:
    • A character constant is a single character enclosed in single quotes ''.
    • Java also allows the use of the escape character '\' to convert the subsequent characters into special character constants.
    • Use Unicode values ​​directly to represent character constants.
  • The char type is operable. Because it all corresponds to Unicode encoding.
char c1 = 'a'; // 编译通过
// char c2 = 'AB'; // 编译不通过
char c3 = '中'; // 编译通过
char c4 = '\n'; // 编译通过
char c5 = '\u0043'; // 编译通过
// char c6 = ''; // 编译不通过
char c7 = 97; // a, 开发中极其少见

Commonly used ASCII code values: 'a' == 97; 'A' == 65;

Boolean: boolean

  • Can only take one of two values: true, false
  • Often used in conditional judgments and loop structures

Basic data type conversion

  • Automatic type conversion: A type with a small capacity is automatically converted to a data type with a large capacity. The data types are sorted by capacity as follows:char、byte、short --> int --> long --> float --> double
  • When there are multiple types of data mixed operations, the system first automatically converts all data types into the data type with the largest capacity, and then performs calculations
  • byte, short, and char will not be converted to each other, the three of them are first converted to int type during calculation

When Java is doing calculations, if the operands are all in the range of int, then all operations will be performed in the space of int.

  • The boolean type cannot be operated with other data types
  • When the value of any basic data type is connected with a string (String) (+), the value of the basic data type will be automatically converted into a string (String) type

Explanation: The capacity at this time refers to the size of the range of the indicated number. For example: float capacity is greater than long capacity

cast

  • The inverse process of automatic type conversion converts a data type with a large capacity into a data type with a small capacity. When using it, you must add the mandatory conversion character: (), but it may cause precision reduction or overflow , so pay special attention
  double d1 = 12.9;
  int i1 = (int)d1; // 12,截断操作

  int i2 = 128;
  byte b = (byte)i2; // -128
  • Usually, strings cannot be directly converted to basic types, but the conversion of strings to basic types can be realized through the wrapper class corresponding to the basic types
  String a = "43";
  int i = Integer.parseInt(a);
  • The boolean type cannot be converted to other data types

Description: For integer constants, the default type is int; for floating-point constants, the default type is double.

  byte b = 12;
  // byte b1 = b + 1; // 编译失败
  // float f1 = b + 12.3; // 编译失败

String type: String

  • String is not a basic data type, but a reference data type
  • The usage is consistent with the basic data types.
  • A string can be concatenated with another string, or directly concatenated with other types of data.
  String str = "abcd";
  str = str + "xyz";
  int n = 100;
  str = str + n; // abcdxyz100

4. Hexadecimal

  • All numbers exist in binary form at the bottom of the computer .
  • For integers, there are four representations:
    • Binary (binary): 0,1, full 2 ​​into 1, start with 0bor0B
    • Decimal (decimal): 0-9, 10 into 1
    • Octal (octal): 0-7, full 8 into 1, 0starting with a number
    • Hexadecimal (hex): 0-9 and AF, full 16 into 1, start with 0xor . 0XAF here is case insensitive.
  • Java integer constants are of type int by default. When an integer is defined in binary, its 32nd (highest bit) is the sign bit: when it is of type long, binary occupies 64 bits by default, and the 64th bit is the sign bit
  • Binary integers come in three forms:
    • Original code: Directly replace a value with a binary number. The highest bit is the sign bit (0 negative 1 positive)
    • Inverse code of negative number: It is the bitwise inversion of the original code, only the highest bit (sign bit) is confirmed as 1
    • The complement of a negative number: add 1 to its complement
  • The computer keeps all integers in two's complement form
    • The original code, inverse code and complement code of positive numbers are the same
    • The complement of a negative number is its complement + 1

5. Operators

An operator is a special symbol used to represent data operations, assignments, and comparisons.

  • arithmetic operator
  • assignment operator
  • Comparison Operators (Relational Operators)
  • Logical Operators
  • bitwise operator
  • ternary operator

arithmetic operator

operator operation example result
+ plus sign +3 3
- negative b=4; -b -4
+ add 5+5 10
- reduce 6-4 2
* take 3*4 12
/ remove 5/5 1
% modulo (remainder) 7%5 2
++ Auto-increment (before), first calculate and then get value a=2;b=++a; a=3;b=3
++ Auto-increment (post), value first and then operation a=2;b=a++; a=3;b=2
Self-decrement (before), first calculate and then take value a=2;b=–a; a=1;b=1
Self-decrement (after), take the value first and then operate a=2;b=a–; a=1;b=2
+ string concatenation “hey” + “llo” “Hello”

Difficulty point 1: %the remainder operation, the sign of the result is the same as the sign of the modulus

int m1 = 12;
int n1 = 5;
System.out.println("m1 % n1 = " + m1 % n1); // m1 % n1 = 2
int m2 = -12;
int n2 = 5;
System.out.println("m1 % n1 = " + m2 % n2); // m1 % n1 = -2
int m3 = 12;
int n3 = -5;
System.out.println("m1 % n1 = " + m3 % n3); // m1 % n1 = 2
int m4 = -12;
int n4 = -5;
System.out.println("m1 % n1 = " + m4 % n4); // m1 % n1 = -2

Difficulty 2: ++ and – do not change the data type of the variable itself

short s = 10;
//s = s + 1; //编译失败
s = (short) (s + 1); //正确
s++; //正确

byte b = 127;
b++;
System.out.println(b); //-128

assignment operator

Symbols: =Extended assignment operators: +=, -=, *=, /=,%=

  • When =the data types on both sides are inconsistent, you can use automatic type conversion or use the principle of mandatory type conversion for processing
  • Support for continuous assignment
int i, j;
//连续赋值
i = j = 10;

Difficulties: The extended assignment operator does not change the data type of the variable itself

short s = 10;
//s = s + 2; //编译失败
s += 2;
System.out.println(s); //12
int i = 1;
i *= 0.1;
System.out.println(i); // 0

comparison operator

operator operation example result
== equal to 4==3 false
!= not equal to 4!=3 true
< less than 4<3 false
> more than the 4>3 true
<= less than or equal to 4<=3 false
>= greater or equal to 4>=3 true
instanceof Check if it is an object of class “Hello” instanceof String true
  • The results of comparison operators are all boolean, that is, either true or false.
  • Comparison operators ==cannot be mistakenly written as=
  • > < >= <=: Can only be used between data of numeric type
  • ==: It can be used not only between numerical type data, but also between other reference type variables.

Logical Operators

&- Logical And
|- Logical Or
!- Logical NOT
&&- Short Circuit And
||- Short Circuit Or
^- Logical XOR

a b a&b a&&b a|b a||b !a a^b
true true true true true true false false
true false false false true true false true
false true false false true true true true
false false false false false false true false

distinguish between & and &&

  • Similarity 1: the operation results of & and && are the same
  • Same point 2: When the left side of the symbol is true, both will perform the operation on the right side of the symbol
  • The difference: when the left side of the symbol is false, & continues to perform the operation on the right side of the symbol, and && no longer performs the operation on the right side of the symbol

Distinguish between | and ||

  • Similarity 1: | and || have the same operation result
  • Same point 2: When the left side of the symbol is false, both will perform the operation on the right side of the symbol
  • 不同点1:当符号左边是true时,|继续执行符号右边的运算,而||不再执行符号右边的运算

位运算符

运算符 运算 范例
<< 左移 3 << 2 = 12 --> 3*2*2=12
>> 右移 3 >> 1 = 1 --> 3/2=1
>>> 无符号右移 3 >>> 1 = 1 --> 3/2=1
& 与运算 6 & 3 = 2
| 或运算 6 | 3 = 7
^ 异或运算 6 ^ 3 = 5
~ 取反运算 ~6 = -7

位运算时直接对整数的二进制进行的运算

运算符 描述
<< 空位补0,被移除的高位丢弃,空缺位补0
>> 被移除的二进制最高位是0,右移后,空缺位补0,若最高位是1,空缺位补1
>>> 被移位二进制最高位无论是0或者是1,空缺位都用0补
& 二进制位进行&运算,只有1&1时结果是1,否则是0
| 二进制位进行|运算,只有0|0时结果是0,否则是1
^ 相同二进制进行^运算结果是0:1^1=0,0^0=0;不相同二进制位^运算结果是1:1^0=1,0^1=1
~ 各二进制码按补码各位取反

m = k ^ n = (m ^ n) ^ n

三元运算符

  • 格式:(条件表达式) ? 表达式1 : 表达式2;
  • 表达式1和表达式2为同种类型

三元运算符与if-else的联系与区别

  • 三元运算符可简化if-else语句
  • 三元运算符要求必须返回一个结果
  • if后的代码块可有多个语句

附加:运算符的优先级

. () {} ; ,
R–>L ++ -- ~ !(data type)
L–>R * / %
L–>R + -
L–>R << >> >>>
L–>R < > <= >= instanceof
L–>R == !=
L–>R &
L–>R ^
L–>R |
L–>R &&
L–>R ||
R–>L ? :
R–>L = *= /= %=
+= -= <<= >>=
>>>= &= ^= |=

6、程序流程控制

  • 程序控制语句是用来控制程序中各语句执行顺序的语句,可以把语句组合成能完成一定功能的小逻辑模块。
  • 其流程控制方式采用结构化程序设计中规定的三种基本流程结果,即:顺序结构、分支结构、循环结构

分支结构

if-else结构

  • else 结构是可选的
  • 针对与条件表达式:
    • 如果多个条件表达式之间是“互斥”关系(或没有交集的关系),哪个判断和执行语句声明在上面还是下面,无所谓。
    • 如果多个条件表达式之间有交集的关系,需要根据实际情况,考虑清楚应该将哪个结构声明在上面。
    • 如果多个条件表达式之间有包含关系,通常情况下,需要将范围小的声明在范围大的上面。否则,范围小的就没有机会执行
  • if-else 结构是可以互相嵌套的。
  • 如果if-else结构中的执行语句只有一行时,对应的一对{}可以省略的。但是,不建议大家省略。
  • 多个if-else时,if-else的配对方式采用就近原则进行配对

switch-case结构

switch(表达式){
  case 常量1:
    语句1;
    // break;
  case 常量2:
    语句2;
    // break;
  ... ...
  case 常量N:
    语句N;
    // break;
  default:
    语句;
    // break;
}
  • 根据switch表达式中的值,依次匹配各个case中的常量。一旦匹配成功,则进入相应的case结构中,调用其执行语句。当调用完执行语句以后,则仍然继续向下执行其他case结构中的执行语句,直到遇到break关键字或此switch-case结构末尾结束为止。
  • break,可以使用在switch-case结构中,表示一旦执行到此关键字,就跳出switch-case结构
  • switch结构中的表达式,只能是如下的6种数据类型之一:byte、short、char、int、枚举类型(JDK5.0新增)、String类型(JDK7.0新增)
  • case 之后只能声明常量,不能声明范围。
  • break 关键字是可选的
  • default:相当于if-else结构中的else。default结构是可选的,而且位置是灵活的。
int number = 0;
// Console: zero
switch(number) {
  default:
    System.out.println("other");
  case 0:
    System.out.println("zero");
    break;
  case 1:
    System.out.println("one");
    break;
}
  • 凡是可以使用switch-case的结构,都可以转换为if-else。反之,不成立。
  • 当发现既可以使用switch-case且switch中表达式的取值情况不太多,又可以使用if-else时,我们优先选择使用switch-case。原因:switch-case执行效率稍高。

循环结构

循环语句的四个组成部分

  • 初始化部分
  • 循环条件部分
  • 循环体部分
  • 迭代部分

for循环结构

for(初始化部分;循环条件部分;迭代部分) {
  循环体部分
}

执行过程:初始化部分-循环条件部分-循环体部分-迭代部分-循环条件部分-循环体部分-迭代部分- ... - 循环条件部分

while循环结构

初始化部分
while(循环条件部分) {
  循环体部分
  迭代部分
}

执行过程:初始化部分-循环条件部分-循环体部分-迭代部分-循环条件部分-循环体部分-迭代部分- ... - 循环条件部分
  • 写while循环千万小心不要丢了迭代条件。一旦丢了,就可能导致死循环!
  • 写程序需要避免出现死循环。
  • for循环和while循环是可以相互转换的。区别在于for循环和while循环的初始化条件部分的作用范围不同。

do-while循环结构

初始化部分
do{
  循环体部分
  迭代部分
}while(循环条件部分);

执行过程:初始化部分-循环体部分-迭代部分-循环条件部分-循环体部分-迭代部分- ... - 循环条件部分
  • do-while循环至少会执行一次循环体!
  • 开发中,使用for和while更多一些。较少使用do-while

特殊关键字的使用

适用范围 不同点 相同点
break switch-case和循环结构中 结束当前循环 关键字后面不能声明执行语句
continue 循环结构中 结束当次循环 关键字后面不能声明执行语句
label: for(int i = 1; i <= 4; i++) {
          for(int j = 1; j <= 10; j++) {
            if (j % 4 == 0) {
              //break; //默认跳出包裹此关键字最近的一层循环
              //continue;
              
              //break label; //结束指定标识的一层循环结构
              continue label; //结束指定标识的一层循环结构当次循环
            }
          }
        }
  • return:并非专门用于结束循环的,它的功能是结束一个方法。当一个方法执行到一个return语句时,这个方法将被结束。
  • 与break和continue不同的是,return直接结束整个方法,不管这个return处于多少层循环之内

7、数组

  • 数组(Array),是多个相同类型数据按一定顺序排列的集合,并使用一个名字命名,并通过编号的方式对这些数据进行统一管理。
  • 数组本身是引用数据类型,而数组中的元素可以是任何数据类型,包括基本数据类型和引用数据类型。
  • 创建数组对象会在内存中开辟一整块连续的空间,而数组名中引用的是这块连续空间的首地址。
  • 数组的长度一旦确定,就不能修改。
//1.一维数组的声明和初始化		
int[] ids;//声明
//1.1静态初始化:数组的初始化和数组元素的赋值操作同时进行
ids = new int[]{1001,1002,1003,1004};
//1.2动态初始化:数组的初始化和数组元素的赋值操作分开进行
String[] names = new String[5];

数组元素的默认初始化值

  • 数组元素是整型:0
  • 数组元素是浮点型:0.0
  • 数组元素是char型:0或者’\u0000’,而非’0’
  • 数组元素是boolean型:false
  • 数组元素是引用数据类型:null

对于二维数组的理解:我们可以看成是一维数组array1又作为另一个一维数组array2的元素而存在。其实,从数组底层的运行机制来看,其实没有多维数组。

//一些错误的写法
//int[] ids;
//ids = {1,2,2}; //编译错误
//一些正确但是不标准的写法
int[] arr1 = {1,2,2,3}; //类型推断
int[] arr2[] = new int[][]{
   
   {1,2,2},{4,5},{6,7,8}}; // 数组[]位置可以随意
int[] arr3[] = {
   
   {1,2,2},{4,5},{6,7,8}};
String[] strArray1[] = {
   
   {"222", "2222"},{"111", "3333", "5555"}};

附加:Arrays工具类的使用

  • java.util.Arrays类即为操作数组的工具类,包含了用来操作数组的各种方法
方法 作用
boolean equals(int[] a,int[] b) 判断两个数组是否相等
String toString(int[] a) 输出数组信息
void fill(int[] a,int val) 将指定值填充到数组之中
void sort(int[] a) 对数组进行排序
int binarySearch(int[] a,int key) 对排列后的数组进行二分法检索指定的值

Guess you like

Origin blog.csdn.net/qq_51808107/article/details/131418978