Basic Concepts [Variables and Data Types and Operators, Binary and Decimal, Decimal to Binary, Binary to Decimal] (1) - Comprehensive Detailed Explanation (Learning Summary --- From Introduction to Deepening)

 

Table of contents

Variables and data types and operators

Binary and decimal conversion 

decimal to binary 

binary to decimal 

note 

 Identifiers and keywords

keywords/reserved words 

 variable

Classification and scoping of variables 

Constant

Basic data type (primitive data type) 

integer 

 Floating Point Number

 character type


 

Variables and data types and operators

binary

 

Binary, a number system widely used in computing technology, was invented in 1679 by Leibniz, a German master of mathematics and philosophy. Binary data is a number represented by two digits, 0 and 1. Its base is 2, and the carry rule is "every two makes one". Digital computers can only recognize and process codes consisting of strings of '0'.'1' symbols. Its mode of operation is binary. Binary corresponds to two states and is widely used in electronics science. For example: it can correspond to the switching state of electronic devices, the corresponding signal voltage state (+5V is equivalent to logic "1", 0V is equivalent to logic "0"), whether the corresponding cassette is punched, electromagnetic storage (magnet state: south is 0, North is 1) and so on. 

 

Binary is widely used in every aspect of our life. For example, the widely used Morse code consists of two basic signals: a short dot signal "·", read "drip"; a long signal "—" that lasts for a certain period of time, read "click". Then, 26 letters are formed to spell out the corresponding word. 

Of course, we don't need to remember these. If you want to learn, just remember SOS ^_^

 

Binary and decimal conversion 

Online hex conversion tool: https://tool.lu/hexconvert/

Correspondence between binary and decimal numbers

 

 

decimal to binary 

The conversion of decimal integers to binary integers adopts the method of "divide by 2, take the remainder, and arrange in reverse order".

The decimal number 29 converted to binary is: 11101

binary to decimal 

Binary conversion to decimal adopts "weighted addition method".

note 

The benefits of writing comments: Be a programmer that everyone loves!

The advantage of not writing comments: Be a programmer who leaves the company and the former company has to beg you! Comments will not appear in the bytecode file, that is, the Java compiler will skip comment statements when compiling. In Java, according to the different functions of annotations, it is mainly divided into single-line annotations, multi-line annotations, and document annotations. 

[Example 2-1] Know the three types of annotations in Java

/**
* Welcome 类(我是文档注释)
* @author 童小纯
* @version 1.0
*/
public class Welcome {
//我是单行注释
public static void main(String[ ] args/*我是行内注释 */) {
System.out.println("Hello World!");
}
/*
我是多行注释!
我是多行注释!
*/
}

 Identifiers and keywords

Identifiers are used to name variables, classes, methods, and packages.

4 big rules:

   1. It must start with a letter, an underscore _, and a dollar sign $.

   2. Other parts can be any combination of letters, underscore "_", dollar sign "$" and numbers.

   3. It is case-sensitive and unlimited in length.

   4. It cannot be a Java keyword. 

 

Java does not use the ASCII character set, but the Unicode character set. Therefore, the meaning of letters here is not only English, but also Chinese characters and so on. But it is not recommended to use Chinese characters to define identifiers!

 [Example 2-2] Legal identifiers

int a = 3;

int _123 = 3;

int $12aa = 3;

int variable 1 = 55; //It is not recommended to use Chinese-named identifiers

[Example 2-3] Illegal identifier

int 1a = 3; // cannot start with a number

int a# = 3; // cannot contain special characters like #

int int = 3; // cannot use keywords

keywords/reserved words 

Java keywords are reserved for internal use in the Java language, such as class is used to define a class. We cannot use keywords as variable names or method names.

rookie minefield

Due to the inertial thinking of exam-oriented education, many novices are likely to memorize the words above. Starting from practical thinking, we don’t need to memorize it deliberately! With the deepening of learning, it is naturally very familiar. 

 variable

the nature of variables 

1. A variable essentially represents an "operable storage space". The location of the space is certain, but the value placed in it is uncertain.

2. The "corresponding storage space" can be accessed through the variable name, thereby manipulating the value stored in this "storage space".

3. Java is a strongly typed language, each variable must declare its data type. The data type of a variable determines the size of the storage space occupied by the variable. For example, int a=3; means that the space size of variable a is 4 bytes.

variable declaration 

double salary;

long earthPopulation;

int age;

Constants of different data types will allocate different spaces in memory, as shown in Figure 2-1.

 

[Example] Declaration and initialization of variables

int age = 18;

double e = 2.718281828;

int i , j; // the data type of both variables are int 

Classification and scoping of variables 

There are three types of variables: local variables, member variables (also known as instance variables), and static variables.

veteran advice

 Member variables and static variables are not the current focus, don't worry too much about understanding or not. When we learn object-oriented, we will focus on explaining member variables and static variables. 

local variable

A variable defined inside a method or statement block. The life cycle starts from the declaration position to the execution of the method or statement block. Before using a local variable, it must be declared, initialized (assigned with an initial value) and then used. 

[Example] Declaration of local variables

public void test() {
    int i;
    int j = i+5 ; // 编译出错,变量 i 还未被初始化
}
public void test() {
    int i;
    i=10;
    int j = i+5 ; // 编译正确
} 

Member variable (also called instance variable member variable) [I don’t need to master it yet, let’s talk about object-oriented]

Variables defined outside methods and inside classes. Subordinate to the object, the life cycle is always with the object. If not initialized by itself, it will be automatically initialized to the default initial value of the type.

[Example 2-8] Declaration of instance variables 

public class Test {
    int i;
}

Static variable (class variable static variable) [I don’t need to master it yet, let’s talk about object-oriented]

Use static definitions. Subordinate to the class, the life cycle is always with the class, from class loading to unloading. (Note: Let's go deeper after the memory analysis! Let's put this concept first!) If you don't initialize it yourself, it will be automatically initialized to the default initial value of the type just like the member variable.

Note: At present, you only need to understand the basic classification concepts. You don't need to master it, and you will learn more about methods, objects, and classes later.

Constant

 In the Java language, use the keyword final to define a constant. Constants cannot be changed once they are initialized.

Declaration format: final type varName = value

[Example 2-9] Declaration and use of constants

public class TestConstants {
public static void main(String[] args) {
    final double PI = 3.14;
   // PI = 3.15; //编译错误,不能再被赋值!
   double r = 4;
   double area = PI * r * r;
   double circle = 2 * PI * r;
   System.out.println("area = " + area);
   System.out.println("circle = " + circle);
  }
}

For better distinction and expression, 1, 2, 3, 'a', 'b', true, false, "helloWorld", etc. are generally called character constants, while PI modified with final is called symbolic constants.

veteran advice

Variable and Constant Naming Conventions

 All variables, methods, class names: see the name

 Class member variables: lowercase first letter and camel case principle: monthSalary

 Local variables: lowercase first letter and camel case

 Constants: capital letters and underscores: MAX_VALUE

 Class names: Capitalization and CamelCase: Man, GoodMan

 Method name: lowercase first letter and camel case principle: run(), runRun()

Basic data type (primitive data type) 

Java data types are divided into two categories: basic data types (primitive data type) and reference data types (reference data type).

Precautions

 The size of the reference data type is unified to 4 bytes, and the address of the referenced object is recorded!

 This chapter only explains basic data types. Reference data types are explained in the subsequent array and object-oriented chapters. 

integer 

 

Four representations of Java language integer constants

 Decimal integers, such as: 99, -500, 0

 Octal integer, required to start with 0, such as: 015

 Hexadecimal numbers, requiring 0x or 0X at the beginning, such as: 0x15

 Binary numbers, requiring 0b or 0B at the beginning, such as: 0b01110011 

The integer constant of Java language is int type by default, and ' l ' or ' L ' can be added after declaring long type constant.

[Example] How to write long type constants and declare variables

long a = 55555555; //编译成功,在 int 表示的范围内(21 亿内)。
long b = 55555555555;//不加 L 编译错误,已经超过 int 表示的范围。

 Error: The literal 55555555555 of type int is out of range, so we need to modify the code to:

long b = 55555555555L;

 Floating Point Number

1. The float type is also called a single-precision type, and the mantissa can be accurate to 7 significant figures.

2. Double means that the numerical precision of this type is about twice that of the float type, also known as the double precision type, and most applications use the double type. 

3. Java floating-point type constants have two representations

    (1) Decimal format: Example: 3.14 314.0 0.314

     (2) Example of scientific notation: 3.14e0 3.14E2 3.14E-1

4. Floating point type is imprecise, do not use for comparison

Floating point numbers have rounding errors and numbers cannot be represented exactly. Floating-point numbers are suitable for ordinary scientific and engineering calculations, and the precision is sufficient; but they are not suitable for commercial calculations with very high precision requirements, and BigDecimal should be used for operations and comparisons at this time.

5. The default type of floating-point constant is double. To change it to float, you can add F or f after it

[Example] Use scientific notation to assign values ​​to floating-point variables

 

double f = 314e2; //314*10^2-->31400.0
double f2 = 314e-2; //314*10^(-2)-->3.14

The value of the float type has a suffix F or f, and the floating point value without the suffix F/f defaults to the double type. You can also add the suffix D or d after the floating-point value to make it clear that it is a double type.

[Example] How to write float type constants and declare variables

float f = 3.14F;//float 类型赋值时需要添加后缀 F/f
double d1= 3.14;
double d2 = 3.14D;

[Example 2-13] Comparison of floating-point data 1

float f = 0.1f;
double d = 1.0/10;
System.out.println(f==d);//结果为 false

[Example 2-14] Comparison of floating-point data II

float d1 = 423432423f;
float d2 = d1+1;
if(d1==d2){
    System.out.println("d1==d2");//输出结果为 d1==d2
}else{
    System.out.println("d1!=d2");
}

Run the above two examples and find that the result of Example 2-13 is "false", while the output of Example 2-14 is "d1==d2". This is because due to the limited word length, the number that can be accurately represented by floating-point numbers is limited and therefore discrete. Floating-point numbers generally have rounding errors, and many numbers cannot be represented precisely (for example, 0.1), and the result can only be close to, but not equal to. Binary floating-point numbers cannot accurately represent negative powers of 10 such as 0.1, 0.01, and 0.001. Not all decimals can be represented exactly in binary floating point. There are two useful classes under the java.math package: BigInteger and BigDecimal, which can handle numbers of any length. BigInteger implements arbitrary-precision integer arithmetic. BigDecimal implements arbitrary-precision floating-point arithmetic.

rookie minefield

Don't use floating point numbers for comparisons! Many newcomers and even many experienced programmers with poor theory will make this mistake! For comparison, please use the BigDecimal class 

 character type

 

The ASCII character set represents English letters, numbers, special characters, control characters, the ancestor of all character sets, and everyone will be compatible with it. But one byte can represent 256 states, while ASCII characters only use 128, and the latter 128 are always empty.

So there is ISO8859-1, aliased as latin-1, which contains 256 characters. The first 128 characters are exactly as in ASCII. The latter 128 include characters corresponding to Western European languages, Greek, Thai, Arabic, and Hebrew.

With the popularization of computers in our country, the processing of Chinese characters also has our own scheme. That is GB2312, two bytes represent a Chinese character. Two bytes can represent 65536 states, and no matter how many Chinese characters there are, all of them can be included. Later, there were GBK and GB18030.

The Taiwan region of our country has developed a set of big five codes BIG5 that display traditional Chinese.

Every place in the world has its own text encoding. Due to the incompatibility, it often causes garbled characters. 

If there is a unified character set that includes all language characters in the world, and each character is given a globally unique code, then the problem of garbled characters will disappear. Thus, a unified character set of all language characters used by all countries and nations in the world was born, which is the Unicode character set.

The Unicode character set is to give all characters in the world a unique encoding. The English corresponding to "unique" is Unique, and the encoded English is code. 

Unicode adopts a strategy of separating character sets and encodings. Before Unicode, before the birth of Unicode, character sets and character encodings could be confused, but in Unicode they must be strictly distinguished.

The Unicode character set uniformly uses two bytes to represent a character, including English letters. However, since English occupies the vast majority of Internet information. When it is actually stored and transmitted, it will cause great waste; therefore, at present, UTF8 encoding is mainly used to realize specific storage and transmission. UTF-8 is a variable-length encoding that encodes Unicode characters with 1-6 bytes. Western European characters are still 1 byte, and Chinese characters are 3 bytes.

The character type occupies 2 bytes in memory, and single quotation marks are used to represent character constants in Java. For example, 'A' is a character, which is different from "A", which means a string containing one character. The char type is used to represent characters in the Unicode code table. Unicode encoding is designed to handle text in various languages, it occupies 2 bytes and allows 65536 characters.

[Example 2-16] Character demonstration

char eChar = 'a'; 
char cChar ='中';

Unicode has encodings from 0 to 65535, and they are usually represented by hexadecimal values ​​from '\u0000' to '\uFFFF' (the prefix u indicates Unicode)

[Example 2-17] Representation method of character type hexadecimal value

char c = '\u0061';

The Java language also allows the escape character '\' to convert the following characters into other meanings. Commonly used escape characters, their meanings and Unicode values ​​are shown in Table 2-6.

[Example 2-18] escape character

char c2 = '\n'; //代表换行符

 

Notes The String class we will learn later is actually a character sequence (char sequence), essentially an array of char characters. 

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131712286