Two: variables, identifiers, reserved words, variables

Posted by knickerlas on Sun, 03 Oct 2021 18:54:15 +0200

01. Keyword and Reserved Words

1. Definition and Features of Keyword

• Definition: A string (word) given special meaning to the Java language for a specific purpose
• Features: All letters in keywords are lowercase

2. Reserved word

Java reserved words: Existing Java versions are not yet used, but future versions may be used as keywords. Avoid using these reserved words goto, const when naming your own identifiers.

02. Identifier

2.1. What is an Identifier

• The sequence of characters Java uses to name elements such as variables, methods, and classes is called an identifier
• Tip: Anything you can name yourself is called an identifier.

2.2. Define legal identifier rules [Important]

1. Composed of 26 uppercase and lowercase letters, 0-9, _or \$
2. Numbers cannot start.
3. An identifier cannot contain spaces.
4. Keyword and reserved words are not allowed, but can contain keywords and reserved words.
5. Java is case-sensitive and has unlimited length.

Name Naming Specification in Java

1. Naming conventions in Java:

• Package name: All letters are lowercase when multiple words are formed: xxxyyzzz
• Class name, interface name: ** Uppercase all words: **XxxYyZzz
• Variable name, method name: when multiple words are composed, the first word is lowercase and the second word begins with each word in uppercase: xxxYyZzz
• Constant name: All letters are capitalized. When multiple words are used, each word is underlined: XXX_YYY_ZZZ

2. Points of Attention

• Note 1: When naming, in order to improve readability, try to be as meaningful as possible,'Know what you see'.
• Note that 2:java uses a unicode character set, so identifiers can also be declared in Chinese characters, but this is not recommended.
• See Code Clean Way for more details

03. Variables

3.1. Declarations and use of variables

1. Concepts of variables:

• A storage area in memory;
• The data in this area can change continuously over the same type of range;
• A variable is the most basic unit of storage in a program. It contains the type of variable, its name, and the stored value.

2. The role of variables:

• Used to save data in memory.

3. Use variables to note:

• Every variable in Java must be declared before it can be used;
• Use variable names to access data in this area;
• Scope of a variable: within the pair {} where it is defined;
• Variables are valid only within their domain of action;
• A variable with a duplicate name cannot be defined within the same scope.

4. Declare Variables

• Syntax: <Data Type> <Variable Name>
• For example: int var;

5. Assignment of Variables

• Syntax: <variable name> = <value>
• For example: var = 10;

6. Declare and assign variables

• Syntax: <Data Type><Variable Name>=<Initial Value>
• For example: int var = 10

7. Supplement: Classification of variables - by declared location

• Outside of a method, variables declared within a class are called member variables.
• Variables declared inside a method body are called local variables.

8. Note: The differences in initialization values between the two:

• Same: all have life cycles
• Differential: Local variables need to be explicitly initialized in addition to formal parameters.

3.2. Basic Data Types

2. Classification of variables by data type

For each type of data, a specific data type (strongly typed language) is defined, and different sizes of memory space are allocated in memory.

3.2.1, Integer type: byte, short, int, long

• java integer types have a fixed range of tables and field lengths and are not affected by specific OS to ensure portability of java programs.

• java integer constants default to int, long constants are declared with'l'or'L'

• Variables in java programs are usually declared int s, and long is used unless it is not sufficient to represent a large number

typeOccupy storage spaceTable Number Range
byte1 byte = 8 bits-128 ~ 127
short2 bytes-2^15~ 2^15-1
long8 bytes-2^63~ 2^63-1
• 1MB = 1024KB 1KB= 1024B B= byte ? bit?

• bit: The smallest unit of storage in the computer. byte: The basic storage unit in the computer.

/*
Java Defined data types

1. Variables are classified according to data type:
Basic data types:
Integer: byte \short \int \long
Floating Point: float \double
Character type: char
boolean: boolean

Reference data type:
class:
interface:
Array:array

2. Where variables are declared in a class:
Member variable vs local variable
*/
class VariableTest1{
public static void main(String[] args) {
//1.Integer: byte(1 byte = 8bit) short(2 bytes)int (4 bytes)long(8 bytes)
//(1) byte range: -128 ~ 127

byte b1 = 12;
byte b2 = -128;
//	b2 = 128; //compilation failed
System.out.println(b1);
System.out.println(b2);

// (2) Declare long variables, which must end with "1" or "L"
short s1 = 128;
int i1 = 12345;
long l1 = 345678586;
System.out.println(l1);
}
}



3.2.2, Floating point type: float, double

• Similar to integer types, Java floating point types also have a fixed range of tables and field lengths, independent of the specific operating system.
• Floating-point constants have two representations:
• Decimal number form: e.g. 5.12 512.0f.512 (must have decimal point)
• Form of scientific counting: e.g. 5.12e2 512E2 100E-2
• float: Single precision, the last number can be precise to 7 significant digits. In many cases, the accuracy is difficult to meet the requirements.
• double: double, twice as precise as float. This type is usually used.
• Java's floating-point constants default to double, declaring float constants followed by'f'or'F'.
typeOccupy storage spaceTable Number Range
Single precision float4 Bytes-3.403E38 ~ 3.403E38
double precision8 bytes-1.798E308 ~ 1.798E308

3.2.3, Character type: char

• char data is used to represent the usual "character" (2 bytes)
• All characters in Java are encoded using Unicode, so a character can store a letter, a Chinese character, or a character in another written language.
• Three representations of character variables:
• Character constants are single characters enclosed in single quotes (''). For example: char c1 ='a'; char c2 ='medium'; char c3 ='9';
• The escape character'\'is also allowed in Java to convert subsequent characters into special character-type constants. For example: char c3 ='\n'; //'\n' for line breaks
• Use Unicode values directly to represent character constants:'\uXXXX'. Where XXXX represents a hexadecimal integer. For example, \u000a represents \n.
• char types are operable because they all correspond to Unicode codes.
/*
Java Defined data types

1. Variables are classified according to data type:

Basic data types:
Integer: byte \short \int \long
Floating Point: float \double
Character type: char
boolean: boolean

Reference data type:
class:
interface:
Array:array

2. Where variables are declared in a class:
Member variable vs local variable
*/
class VariableTest1{
public static void main(String[] args) {
//2. Floating point type: float(4 bytes)  double(8 bytes)
//(1) Floating-point type, representing values with decimal points
//(2) float indicates a larger range of values than long

double d1 = 12.3;
System.out.println(d1 +1);

//When defining a float type variable, the variable ends with "f" or "F"
float f1 = 12.3F;
System.out.println(f1);

//(2) Typically, double variables are used when defining floating-point variables

//3.Character type: char(1 character = 2 bytes)
//1. Define char-type variables, usually using a pair of''
char c1 = 'a';
//Compilation failed
//c1 = 'AB';
System.out.println(c1);

char c2 = '1';
char c3 = 'in';
char c4 = '&';
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);

//(2) Representation: 1. Declare a character; 2. Escape a character; 3. Use Unicode values directly to represent character constants
char c5 = '\n';	//Line Break
c5 = '\t';	//Tab character
System.out.print("hello" + c5);
System.out.println("world");

char c6 = '\u0123';
System.out.println(c6);

char c7 = '\u0043';
System.out.println(c7);
}
}



Understanding: ASCII code

• Inside the computer, all data is represented in binary form. Each binary bit has two states, 0 and 1, so eight binary bits can be combined into 256 states, called a byte.A byte can be used to represent 256 different states, each corresponding to a symbol, which is 256 symbols, ranging from 0000000 to 1111111.
• ASCII Code: In the 1960s, the United States formulated a set of character codes that unify the relationship between English characters and binary bits. This is called ASCII code. ASCII codes specify a total of 128 characters, such as 32 (binary 00100000) for the space "SPACE" and 65 (binary 01000001) for the uppercase letter A.(including 32 control symbols that cannot be printed), which occupies only the last 7 bits of a byte, with the uniform rule of zero for the first 1 bit.
• Cannot represent all characters.
• The same encoding represents different characters: 130, for example, represents the letter Gimel in French encoding and the letter Gimel in Hebrew encoding.

Understanding: Unicode encoding

• Scrambling: There are many encoding methods in the world, and the same binary number can be interpreted as different symbols. Therefore, in order to open a text file, you must know how it is encoded, or if you interpret it in the wrong encoding, scrambling will occur.
• Unicode: An encoding that incorporates all the symbols in the world. Each symbol is given a unique encoding, and there is no scrambling problem with Unicode.
• Disadvantages of unicode: unicode only specifies binary code for symbols, but it does not specify how the binary code should be stored: unicode cannot be distinguished ASCII: Computers can't tell if three bytes represent one symbol or three symbols separately. In addition, we know that one byte is enough for English letters. If unicode uniformly states that three or four bytes are used for each symbol, then there must be two or three bytes in front of each letter that is zero, which is a huge waste of storage space..

Understanding: UTF-8

• UTF-8 is the most widely used implementation of Unicode on the Internet.
• UTF-8 is a variable-length encoding. It can use 1-6 bytes to represent a symbol and vary the byte length according to different symbols.
• Coding rules for UTF-8:
• For single-byte UTF-8 encoding, the highest bit of the byte is 0, and the remaining seven bits are used to encode the character (equivalent to ASCII code).
• For multi-byte UTF-8 encoding, if the encoding contains n bytes, the first n-bit of the first byte is 1, the n+1 bit of the first byte is 0, and the rest of the byte is used to encode the character. All bytes after the first byte are up to two "10", and the remaining six bits are used to encode the character.

3.3.4, boolean type: boolean

• The boolean type is used to determine logical conditions and is generally used for program flow control:
• if condition control statement;
• while loop control statement;
• do-while loop control statement;
• for loop control statement;
• Only true and false values are allowed for boolean type data, no null.
• false and true cannot be replaced with 0 or non-0 integers, which is different from C.
• There are no byte code instructions for boolean values in the Java virtual machine. The Java language expresses the boolean values that are operated on. After compilation, they are replaced by the int data type in the Java virtual machine: true is represented by 1, and false is represented by 0. --- Java Virtual Machine Specification Version 8
class VariableTest1{
public static void main(String[] args) {
//4.boolean: boolean
//1. Can only take one of two values: true and false.
//(2) Usually used in conditional judgment and circular structure
boolean bb1 = true;
System.out.println(bb1);

boolean isMarried = true;
if(isMarried){
System.out.println("No Entry!");
}else{
System.out.println("Can visit!");
}
}
}



3.3. Basic Data Type Conversion

• Automatic type conversion: Small capacity types are automatically converted to large capacity data types. Data types are sorted by capacity size:
• When there are multiple types of data mixing operations, the system first automatically converts all the data to the data type with the largest capacity, and then calculates it.
• byte,short,char do not convert to each other; they all convert to int first when calculating.
• boolean types cannot be manipulated with other data types.
• When you join values and strings of any basic data type (+), the values of the basic data type are automatically converted to String types.
/*
Rules of operation between basic data types:

Prerequisite: This discussion is only about the operation of basic data type variables in 7. It does not include boolean types.
1. Automatic type promotion:
When a variable of a small data type and a variable of a large data type are operated on, the result is automatically promoted to a large data type.
char,byte,short-->int-->long-->float-->double

In particular: when byte, char, short are three types of variables, the result is int type

2. Cast type:

Explanation: Capacity size refers to the size of the range representing the number. For example, float capacity is larger than long capacity
*/
class VariableTest2{
public static void main(String[] args) {
byte b1 = 2;
int i1 = 129;
//Compilation failed
//		byte b2 = b1 + i1;
int i2 = b1 + i1;
long l1 = b1 + i1;
System.out.println(i2);
System.out.println(l1);

float f = b1 + i1;
System.out.println(f);
//***************Special**********************************
char c1 = 'a';	//97
int i3 = 10;
int i4 = c1 + i3;
System.out.println(i4);

short s2 = 10;
//Compilation error
//		char c3 = c1 + s2;

byte b2 = 10;
//		char c3 = c1 + b2;//Compilation failed

//		short s3 = b2 + s2;//Compilation failed

//		short s4 = b1 + b2;//Compilation failed
}
}
class VariableTest4{
public static void main(String[] args){
//1.Coding situation
long l = 123456;
System.out.println(l);
//Compilation failed: too large integer
//long l1 = 452367894586235;
long l1 = 452367894586235L;

//**************************
//Compilation failed
//		float f1 = 12.3;

//2.Coding scenario 2:
//Integer variable, default type is int
//Floating-point variable, default type is double
byte b = 12;
//	byte b1 = b + 1;//Compilation failed

//	float f1 = b + 12.3;//Compilation failed
}
}



3.3, String Type: String

• String is not a basic data type, but a reference data type
• Use the same way as the basic data type. For example: String str= "abcd";
• A string can concatenate another string or other types of data directly. For example:
/*
String Use of type variables
1. String Of reference data type
2. When declaring String type variables, use a pair of''
3. String It can operate with eight basic data type variables, and the operation can only be a join operation;+
4. The result of the operation is still a String type

*/
class StringTest{
public static void main(String[] args){

String s1 = "Good Moon!";

System.out.println(s1);

String s2 = "a";
String s3 = "";

//		char c ='';//Compilation failed

//*******************************
int number = 1001;
String numberStr = "School Number:";
String info = numberStr + number;	//Join operation
boolean b1 = true;
String info1 = info + true;
System.out.println(info1);
}
}



Exercise 1

String str1 = 4; //Judgment right or wrong:no
String str2 = 3.5f + ""; //Judge str2 right or wrong:yes
System.out.println(str2); //Output: "3.5"
System.out.println(3+4+"Hello!"); //Output: 7Hello!
System.out.println("Hello!"+3+4); //Output: Hello!34
System.out.println('a'+1+"Hello!"); //Output: 98 Hello!
System.out.println("Hello"+'a'+1); //Output: Helloa1



3.4, Cast

• The inverse process of automatic type conversion converts a large data type to a small data type. Use a caster: (), but it may cause loss of precision or overflow, so be careful.
• Typically, a string cannot be converted directly to a base type, but it can be converted to a base type by a wrapper class corresponding to the base type.
• For example: String a = "43";inti= Integer.parseInt(a);
• boolean types cannot be converted to other data types.

Exercise 2

Determine whether compilation is possible

short s = 5;
s = s-2; //Judgment:no
byte b = 3;
b = b + 4;//Judgment:no
b = (byte)(b+4);//Judgment:yes
char c = 'a';
int i = 5;
float d = .314F;
double result = c+i+d; //Judgment:yes
byte b = 5;
short s = 3;
short t = s + b;//Judgment:no



04, Binary

Conversion between 4.1, binary and binary

• All numbers exist in binary form at the bottom of the computer.
• For integers, there are four representations:
• Binary: 0,1, full 2 in 1.Begin with 0b or 0B.
• Decimal: 0-9, full 10 into 1.
• Hex: 0-9 and A-F, full 16 in 1.Begin with 0x or 0X. A-F here is case insensitive. For example: 0x21AF +1= 0X21B0
class BinaryTest{
public static void main(String[] args){

int num1 = 0b110;
int num2 = 110;
int num3 = 0127;
int num4 = 0x110A;

System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
System.out.println("num3 = " + num3);
System.out.println("num4 = " + num4);
}
}



4.2, binary

• Java integer constants default to the int type, where the 32 bit is the symbol bit when the integer is defined in binary; when the long type, the 64 bit is the binary default, and the 64 bit is the symbol bit
• There are three forms of binary integers:
• Source code: directly converts a numeric value to a binary number. The highest bit is the sign bit
• Inverse code for negative numbers: Reverse the code bit by bit, only the highest bit (symbol bit) is determined to be 1.
• Complement for negative numbers: its inverse plus 1. The computer saves all integers as a binary complement.
• Positive numbers have the same source code, inverse code and complement, negative numbers have the same complement + 1

Why use the original, inverse and complement representations?

Computer recognition of "symbol bits" clearly complicates the basic circuit design of a computer!So people have come up with a way to put symbol bits in the operation as well.We know that subtracting a positive number from the algorithm equals adding a negative number, that is, 1-1 = 1 + (-1) = 0, so the machine can only add without subtracting, so the design of computer operations is simpler.

Binary - Decimal

Source code and inverse code exist to help deduce complement!!!

Decimal-Binary

• For positive numbers: the original code, the reverse code and the complement are the same: three codes in one.
• At the bottom of the computer are values represented in binary form.
• At the bottom of the computer, data is saved using numerical complements.

4.3, Interbinary Conversion

Decimal Binary Interchange

• Power of binary to decimal multiplied by 2
• Decimal to binary divided by 2 to take the remainder

Topics: Java