Java language basics 03 - identifiers, keywords, literals, variables, data types

Posted by phpisawesome on Mon, 25 Oct 2021 11:36:44 +0200

About identifiers in java language

  • 1. What is an identifier
    • In java source programs, all words that programmers have the right to name themselves are identifiers.
    • The identifier is highlighted in black in the EditPlus editor
    • What elements can identifiers identify?
      • Class name
      • Method name
      • Variable name
      • Interface name
      • Constant name
      • ...
  • 2. Naming rules for identifiers [if this rule is not followed, the editor will report an error, which is the syntax]
    • It can only be composed of "number, letter, underscore and dollar sign $", and cannot contain other symbols
    • Cannot start with a number
    • Strictly case sensitive
    • Keywords cannot be used as identifiers
    • Theoretically, there is no length limit, but it is best not to be too long
  • 3. Naming specification of identifier [it is only a specification, not a syntax, and the editor will not report an error if it does not comply with the specification]
    • It's best to see the name and know the meaning
    • Follow hump naming rules
      SystemService
      UserService
      CustomerService
    • Class name and interface name: capitalize the first letter, followed by the first letter of each word.
    • Variable name and method name: the first letter is lowercase, and the first letter of each subsequent word is uppercase.
    • Constant name: all words are capitalized, and words are connected with underscores

Keywords in java language

  • What are keywords?
    • When SUN develops the java language, it formulates some character sequences with specific meanings in advance.
    • Words with special meaning in the language constitute the skeleton of java programs. These words need to be remembered. They cannot be written at will and are case sensitive.
  • Keywords are all lowercase in the java language
  • Keywords are highlighted in blue in the EditPlus tool
  • What are the common keywords?
    • public
    • class
    • static
    • void
    • if
    • for
    • while
    • do
    • default
    • byte
    • short
    • int
    • switch
    • true
    • false
    • throw
    • throws
    • try
    • catch
    • ...
  • Reminder: key words do not need to be memorized separately. They need to be memorized in the process of programming.

About literal values in java language

  • Literal value:
    • 10,100
    • 3.14
    • "abc"
    • 'a'
    • true,false
  • Literal values are data
  • Literals are part of java source programs. Including identifiers and keywords, they are all part of the java source program.
  • Data is classified in the real world, so data also has categories in computer programming language: [data type]
    • 10,100         Is an integer literal
    • three point one four               Is a floating-point literal
    • true,false      Is a Boolean literal
    • "abc" and "Chinese" are string literals
    • 'A', 'person'           Is A character literal
  • be careful:
    All string literals in the java language must be enclosed in double quotes, which are half angles
    All character literal values in the java language must be enclosed in single quotes. Single quotes are half width, and only a single character can be stored in single quotes.

About variables in java language

  • 1. What are variables?
    • In essence, a variable is a space in memory with "data type", "name" and "literal value"
    • The variable consists of three parts: data type, name, literal value [data]
    • Variables are the most basic units for storing data in memory
  • 2. What is the role of data types?
    • Different data have different types. Different data types will allocate different sizes of space at the bottom.
    • Data types guide how much memory a program should allocate at run time.
  • 3. Variable requirements:
    The specific "data" stored in the variable must be consistent with the "data type" of the variable. In case of inconsistency, compile and report an error.
  • 4. Syntax format for declaring / defining variables: data type variable name
    • Data type:
      For example, integer data, int
    • Variable name:
      As long as it is a legal identifier. The specification requires: the first letter is lowercase, and the first letter of each subsequent word is uppercase.
      For example: int i; int age; int length; int size
      Where int is the data type, and I, age, length and size are variable names
  • 5. How to assign values after variable declaration?
    • Syntax format: variable name = literal value
      Requirement: the data type of literal value must be consistent with that of variable.
      =The equal sign is an operator, called the assignment operator. The assignment operator first operates the expression on the right of the equal sign, and the result after the execution of the expression is assigned to the variable on the left.
  • 6. Declarations and assignments can be done together
int i = 10;
  • 7. After the variable is assigned, it can be re assigned, and the value of the variable can be changed:
int i = 10;
System.out.println(i);//10
int i = 20;
System.out.println(i);//20
int i = 100;
System.out.println(i);//100
  • 8. With the concept of variable, memory space is reused:
int i = 10;
System.out.println(i);
...
System.out.println(i);
  • 9. There are two ways to access a variable:
    • The first is to read the specific data stored in the variable   Get / get
    • The second is to modify the specific data saved in the variable   Set / set
i = 20; //set
System.out.println(i);  //get
  • 10. Variables can be declared in more than one line
int a,b,c
  • 11. Variables in java must be declared and then assigned before they can be accessed
    int i; When the program is executed here, the memory space is not opened up, and the variable I is not initialized. Therefore, it cannot be accessed before assignment

give an example:

public class VarTest01
{
	public static void main(String[] args){
	//Declare an int variable named i
	int i;
	//Compilation error. Variable i is not initialized
	//System.out.println(i);
	//Assign a value to the i variable. The i variable is initialized here and the memory is opened up
	i = 100;
	System.out.println(i);
	//i reassign again
	i = 200;
	System.out.println(i);
	
	//A row can declare multiple variables at the same time
	//a and b are not initialized, and c is assigned to 300
	int a,b,c = 300;
	//Compilation error
	//System.out.println(a);
	//Compilation error
	//System.out.println(b);
	System.out.println(c);
	a = 0;
	b = 1;
	System.out.println(a);
	System.out.println(b);
	}
}
  • 12. In the same scope, variable names cannot be duplicated, but variables can be reassigned
public class VarTest03{
	public static void main(String[] args){
		int i = 100;
		System.out.println(i);
		i = 200;
		System.out.println(i);
		//An error will be reported, and the variable names in the same scope are duplicate
		int i = 500;
		System.out.println(i);
	}
}
  • 13. Scope of variable
    • What is scope?
      The scope of a variable actually describes the effective range of the variable.
      Within what range can be accessed, as long as it is out of this range, the variable cannot be accessed.
    • Just remember one sentence about the scope of variables.
      We don't know each other without braces
public class VarTest03
{
	//Note that the static here should not be removed
	static int k = 90;
	public static void main(String[] args){
		//The scope of variable i is the main method
		//It is effective, visible and accessible in the whole main method
		int i = 100;
		System.out.println(i);   //sure
		System.out.println(k);   //sure
		//The scope of a variable is the whole for loop. After the for loop ends, the memory of a variable is released
		for(int a=0;a<10;a++){
		}
		//Variable a cannot be accessed here
		//System.out.println(a);
		int j;//The scope is the main method
		for(j=0;j<10;j++){
		}
		System.out.println(j);//The j variable in the main method is accessed
	}
	public static void dosome(){
	//Variables in the main method cannot be accessed here;
	//The scope of the i variable has been
	//System.out.println(i); // may not
	System.out.println(k);   //sure
	}
}
  • 14. Classification of variables
    • Classify according to the location of variable declaration:
      • Local variables: variables declared in the method body are called local variables
      • Member variables: variables declared outside the method body [class body] are called member variables
    • Variable names can be the same in different scopes
    • Variable names cannot be duplicated in the same scope
public classs VarTest04
{
	//Main method: entrance
	public static void main(String[] args){
		//i variables are local variables
		int i = 3;
		System.out.println(i);//java follows the "proximity principle"
	}
	//Member variable
	int i = 200;  //No order in class body
	//java statements cannot be written directly in the class body [except declaring variables]
	//System.out.println(i);
	public static void dosome(){
		//local variable
		int i = 100;
	}
}

On data types in java language

  • 1. What is the function of data type?
    • There are a lot of data in the program, and each data has related types. The data space occupied by different data types is different.
    • The function of data type is to guide the JVM how much memory space to allocate to the data when running the program.
  • 2. There are two types of data in java:
    • Basic data type
    • Reference data type [later]
      • class
      • Interface
      • array
      • ...
  • 3. About basic data types:
    • Basic data types include four categories and eight categories:
      • Type I: integer type
        byte ,short,int,long
      • Type II: floating point type
        float,double
      • Class III: Boolean
        boolean
      • Type IV: character type
        char
  • 4. The string "abc" does not belong to the basic data type, but belongs to the reference data type, and the character belongs to the basic data type
    • String uses double quotation marks' '
    • Characters use single quotation marks' '
  • 5. How much space does each of the eight basic data types occupy?
Basic data typeOccupied space size [unit: byte]
byte1
short2
int4
long8
float4
double8
boolean1
char2
  • 6. The computer can only recognize binary in any case, for example, only 1010101010
    [the bottom layer of modern computer adopts the mode of alternating current. There are two states: on and off. The computer only recognizes 1 or 0, and the others do not recognize]
  • 7. What is binary?
    • A representation of data. The decimal system is the full decimal one principle, and the binary system represents the full binary one principle.
      For example, 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
      18 19 20
      For example, 0 1 10 11 100 101 110 111 1000
  • 8. Bytes:
    1 byte = 8 bits [1 byte = 8 bits] 1 bit represents 1 binary bit: 1 / 0
    1 KB = 1024 Byte
    1 MB = 1024 KB
    1 GB = 1024 MB
    1 TB = 1024 GB
  • 9. The byte type in the integer type occupies 1 byte, so the byte type data occupies 8 bits. What is the value range of byte type?
    • As for the number types in java, numbers are positive and negative, so there is a binary bit in the binary of numbers, which is called "sign bit". And this "sign bit" is on the leftmost side of all binary bits. 0 represents a positive number and 1 represents a negative number.
    • Maximum byte type: 01111111
    • The maximum value of byte type: the 7th power of 2 - 1, and the result is 127
    • Minimum value of byte type: - 128 [related to original code, inverse code and complement, not 11111111]
  • 10. Binary and decimal conversion rules: omitted
  • 11. Computers only know binary, so how do computers know words in real life?
    • Among the eight basic data types, byte, short, int, long, float, double and Boolean are easy to represent by computer, because the bottom layer is numbers, and there is a fixed conversion rule between decimal numbers and binary.
    • However, among the eight basic data types, char type represents text in the real world. There is no conversion relationship between text and computer binary by default.
    • In order for the computer to represent the characters in the real world, we need human intervention, and people are responsible for formulating the comparison relationship between "text" and "binary" in advance. This comparison conversion relationship is called character coding.
    • At first, the computer only supported English, and the first character code was ASCII code [one byte code]
      'a'–>97[01100001] 'b'–>98 ...
      'A'–>65  'B'–>66 ...
      '0'–>48  '1'–>49 ...
      • Later, a coding method appeared, which unifies all characters in the world and has a large capacity. This coding method is called unicode coding. There are many specific implementations of unicode coding:
        • UTF-8
        • UTF-16
        • UTF-32
        • ...
      • The java language source code adopts unicode coding, so the "identifier" can be in Chinese, for example, the class name can be in Chinese.
      • Now in actual development, UTF-8 coding is generally used
  • 12. Value range of eight basic data types:
data typeValue range
byte[-128 ~ 127]
short[-32768 ~ 32767]
int
long
float
double
boolean[true,false]
char[0 ~ 65535]

Note: the total number of species represented by short and char is the same, but char has no negative number.

  • 13. Default values for eight basic data types
public class DataTypeTest02
{
	//Variables still follow this syntax: they are declared first and then assigned a value before they can be accessed
	//Member variables are not assigned manually, and the system will assign values by default [local variables will not]
	static int f;//Member variable
	public static void main(String[] args){
		/*
		int i;//local variable
		System.out.println(i);
		*/
		System.out.println(f);//0
	}
}
data typeDefault value
byte,short,int,long0
float,double0.0
booleanFalse [in c language, true is 1 and false is 0]
char\u0000

The default value of the eight basic data types is that everything is aligned with 0.

Elaborate on various data types

  • 1,char
public class DataTypeTest01
{
	public static void main(String[] args){
		//Define a variable of char type, named c, and assign the character 'a'
		char c = 'a';
		System.out.println(c);
		//A Chinese character takes up 2 characters, and the char type is exactly 2 bytes
		//Therefore, the char type variable in java can store a Chinese character
		char x = 'country';
		System.out.println(x);
		
		//Compilation error
		//ab is a string and cannot be enclosed in single quotes
		//char y = 'ab';
		
		//'a' is a string type
		//The k variable is of type char
		//Incompatible types, compilation error
		char  k = "a";
		
		//First statement
		char e;
		//assignment
		e = 'e';
		//Reassignment
		e = 'f';
	}
}
  • Escape character    
    Escape characters convert special characters to normal characters before special characters appear
    • \n newline
    • \t tab
    • \'ordinary single quotation marks
    • \Normal backslash
    • \"Normal double quotation marks
public class DataTypeTest03
{
	public static void main(Sting[] args){
	//Normal n characters
	char c1 = 'n';
	System.out.println(c1);
	
	//This is a newline character, which belongs to char type data
	//Backslash has escape function in java language
	char c2 = '\n';
	
	//Differences between System. out.println() and System.out.print():
	//println is a line feed after output. print indicates output, but no line feed

	//Normal t character
	char x = 't';
	System.out.println(x);
	
	//tab
	//Emphasize that tabs and spaces are different, and their ASCII is different, which is reflected in the two different "keys" on the keyboard
	char y = '\t';
	System.out.print("A");
	System.out.println(y);
	System.out.println("B");//A	B
	
	//Requires "backslash character" to be output on the console
	//The backslash escapes the following single quotation mark into an ordinary single quotation mark character without special meaning
	//The single quotation mark on the left is missing the closing single quotation mark character, and an error is reported during compilation
	/*char k = '\';
	System.out.println(k);*/
	
	/*
	\\
	Explanation: the first backslash has escape function, which can escape the backslash to ordinary backslash characters
	Conclusion: in java, two backslashes represent a common backslash character
	*/
	char k = '\\';
	System.out.println(k);
	
	//Output an ordinary single quote character on the console
	//The first single quotation mark and the last single quotation mark are paired
	char a = '\,';
	System.out.println(a);
	
	char f = '"';
	System.out.println(f);//Output“
	
	System.out.println("HelloWorld!");
	System.out.println(""HelloWorld!"");//Inside are full angle double quotes
	//Compilation error
	//System.out.println(""HelloWorld! ""); / / it is a semi full angle character inside
	System.out.println("\"HelloWorld!\"");
	
	char m = 'in';
	System.out.println(m);
	//The native2ascii.exe command in JDK can convert text into unicode encoding
	//On the command line, enter native2ascii, enter text, and then enter to get the unicode code
	char n = '\u4e2d';//The unicode code corresponding to 'medium' is 4e2d
	System.out.println(n);
	
	//Compilation error
	//char g = '4e2d';
	//Compilation error
	//char g = 'u4e2d';
	//Pass: the backslash u is combined, and the next string of numbers is the unicode code of a text
	char g = '\u4e2d';
	//Default value for char type
	char c10 = '\u0000';
	System.out.println(c10);//Null character
	System.out.println(c10+1);//1
	}
}
  • 2. Integer type
data typeOccupied space sizeDefault valueValue range
byte10[-128~127]
short20[-32768~32767]
int40[-2147483648~2147483647]
long80L
  • The "integer literal" in the java language is treated as an int type by default. To treat this "integer literal" as a long type, you need to add l/L after the "integer literal"; it is recommended to use uppercase L.
  • There are three representations of integer literals in the java language:
    • The first method: decimal [is a default method]
    • The second method: octal [start with 0 when writing octal integer literal]
    • The third method: hexadecimal [start with 0x when writing hexadecimal integer literal]
public class DataTypeTest04
{
	public static void main(Sring[] args){
		int a = 10;
		int b = 010;
		int c = 0x10;
		System.out.println(a);//10
		System.out.println(b);//8
		System.out.println(c);//16
		System.out.println(a + b + c);//34
		
		//123 this integer literal is of type int
		//The i variable is also of type int when declared
		//123 of type int is assigned to variable i of type int, and there is no type conversion.
		int i = 123;
		
		//456 integer literals are treated as int types, occupying 4 bytes
		//When declared, the x variable is of long type, occupying 8 bytes
		//The literal 456 of int type is assigned to the variable x of long type, and there is type conversion
		//Convert int type to long type
		//int type is small capacity
		//The long type is large capacity
		//Small capacity can be automatically converted to large capacity
		long x = 456;
		System.out.println(x);
		
		//The 2147483647 literal is of type int, occupying 4 bytes
		//y is a long type, occupying 8 bytes. Automatic type conversion
		long y = 2147483647;
		System.out.println(y);
		
		//Compilation error: too large integer: 2147483648
		//2147483648 is treated as 4 bytes of int type, but this literal is outside the range of int type
		//long z = 2147483648;
		
		//Resolve errors
		//2147483648 literals are treated as long as they come up, and L is added after the literals
		//2147483648L is an 8-byte long type
		//z is a long variable, and the following program does not have type conversion
		long z = 2147483648L;
		System.out.println(z);
	}
}
public class DataTypeTest05
{
	public static void main(String[] args){
	//100L is a long type literal
	//x is a variable of type long
	//No type conversion, direct assignment
	long x = 100L;
	
	//The x variable is of type long, 8 bytes
	//The y variable is of type int, 4 bytes
	//The following program compilation error is reported: large capacity cannot be directly assigned to small capacity
	//int y = x;
	
	//Conversion from large capacity to small capacity requires forced type conversion
	//Casts require a cast character
	//With a cast, the compilation passes, but the runtime may lose precision.
	//Therefore, cast is used with caution, because the loss of precision may be serious.
	//Strong rotation principle:
	  //Original data: 00000000 00000000 00000000 00000000 00000000 01100100
	  //Data after forced conversion: 00000000 00000000 01100100
	  //Cut off the 4-byte binary on the left [this is how all data is forced]
	int y = (int)x;
	System.out.println(y);
	
	//Original data: 00000000 00000000 00000000 10000000 00000000 00000000 00000000 00000000
    //Data after forced conversion: 10000000 00000000 00000000 00000000
    //1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    //So 10000000 00000000 00000000 00000000 is now a complement form
    //Converting the above complement to the original code is the final result
	long k = 2147483648L;
	int a = (int)k;
	System.out.println(a);//The loss of precision is serious, and the result is negative [- 2147483648]

	//Analyze whether the following programs can be compiled?
	//According to what we have learned so far, the following program cannot be compiled
	//Reason: 50 is the literal value of int type and b is the literal value of byte type. Obviously, it is a conversion from large int to small byte
	//To convert a large capacity into a small capacity, you need to add a forced type converter. The following program does not add a strong conversion symbol, so an error is reported during compilation
	//However, in the actual compilation, the following code has been compiled, which shows that in the java language, when an integer literal
	//If it does not exceed the value range of byte type, the literal can be directly assigned to a variable of byte type.
	byte b = 50;//Compile passed
	byte b = 127;//Compile passed
	//An error is reported during compilation. The int literal 128 has exceeded the value range of byte type and cannot be directly assigned to a variable of byte type
	//byte b = 128;
	
	//To correct the error, you need to use a cast character
	//But the accuracy will be lost
	//Original data: 00000000 00000000 10000000
	//After forced conversion: 10000000 [this is stored inside the computer and is in the form of complement, what is its original code?]
	byte b = (byte)128;//-128
	System.out.println(b);
	
	/*
	There are three forms of computer binaries:
		Original code
		Complement
		Inverse code
	In any case, the computer adopts the form of complement when representing and storing data at the bottom
	Complement of positive number: the same as the original code
	Complement of negative numbers: the binary code corresponding to the absolute value of negative numbers. All binary numbers are reversed and 1 is added
	Complement: 10000000
	Original code calculation process:
		1.Minus 101111111
		2.Reverse all, 10000000 (128)
		3.If it is determined as a negative number according to the complement, the final original code is - 128
	*/
	//short s = 32767;// adopt
	//short s = 32768;// Compilation error
		
	//65535 is of type int, 4 bytes
	//cc is char type, 2 bytes
	//According to the previous knowledge points, the following program is compiled with errors.
	//char cc = 65535;// adopt
	//char cc = 65536;// Compilation error

	/*Summary:
		When an integer value does not exceed the value range of byte, short and char, this literal value can be directly assigned to byte, short and char variables. This mechanism is allowed by SUN to facilitate programmers' programming.
	*/
	}
}
  • 3. Floating point type
    • float single precision [4 bytes]
      Double double precision [8 bytes, high precision]
    • The accuracy of double is too low [relatively speaking], so it is not suitable for financial software. Finance involves money and requires higher accuracy. Therefore, SUN has prepared a type with higher accuracy for programmers in the basic SE class library, but this type is a reference data type and does not belong to the basic data type. It is java.math.BigDecimal
    • In fact, SUN provides a huge set of class libraries in java programs. java programmers develop with this basic set of class libraries. Therefore, you should know where the bytecode of java SE class library is and where the source code of java SE class library is.
      • SE class library bytecode: D:\JAVA\java8\pack\jre\lib\rt.jar
      • SE class library source code:
        D:\JAVA\java8\pack\src.zip
    • For example: String.java and String.class
      The String in our (String [] args) uses the String.class bytecode file
    • In the java language, all floating-point literals [3.0] are treated as double by default
      To handle this literal as a float type, you need to add F/f after the literal.
    • be careful:
      double and float are approximate values when stored in binary inside the computer.
      In the real world, there is a number that circulates indefinitely, such as 3.3333
      Computer resources are limited, with limited resources to store unlimited data, only approximate values can be stored.
public class DataTypeTest06
{
	public static void main(String[] args){
		//3.0 is a literal of type double
		//d is a variable of type double
		//No type conversion exists
		double d = 3.0;
		System.out.println(d);
		
		//5.1 is a literal of type double
		//f is a variable of type float
		//The conversion from large capacity to small capacity requires a cast character, so the following program is written incorrectly
		//float f = 5.1;
		//Solution:
		//The first solution: cast
		float f = (float)5.1;
		//The second solution: no type conversion
		float f = 5.1F;
	}
}
  • 4. Boolean
    • boolean
    • In the java language, boolean has only two values, true and false, and no other values
    • Unlike c, 0 and 1 can represent false and true.
    • In the underlying storage, the boolean type only occupies 1 byte, because in the actual storage, the false underlying is 0 and the true underlying is 1
    • Boolean type is very important in practical development and is often used in logical operations and conditional control statements.
public class DataTypeTest07
{
	public static void main(String[] args){
		//Compilation error: incompatible type
		//boolean flag = 1;
		boolean loginSucsess = true;
		if(loginSucsess )
		{
			System.out.println("Congratulations, login succeeded");	}
		else{
			System.out.println("Sorry, the same account name does not exist or the password is wrong!");
			}
	}
}
  • 5. Data type conversion
    • Among the eight basic data types, except boolean type, the remaining seven data types can be converted to each other.
    • The conversion from small capacity to large capacity is called automatic type conversion, and the capacity is sorted from small to large:
   byte < short < int < long < float < double
        < char  <
   Note:
   		Any floating-point type, no matter how many bytes it takes, has a larger capacity than an integer type
   		char and short The number of types that can be represented is the same, but char You can take a larger positive integer.
  • Converting a large capacity into a small capacity is called forced type conversion. A forced type converter needs to be added before the program can be compiled. However, precision may be lost in the running stage, so use it with caution.
  • When the face value of the whole number does not exceed the value range of byte, short and char, it can be directly assigned to variables of type byte, short and char
  • When byte, short and char are mixed, they are converted to int type before operation
  • The mixed operation of multiple data types shall be converted to the type with the largest capacity before operation
  • Note: analyze the compile phase and run phase, and do not mix run operations in the compile phase
byte b = 3;//It can be compiled and 3 does not exceed the value range of byte type

int i = 10;
byte b = i / 3;//The compiler reports an error. The compiler only checks the syntax and does not "operate" i/3. The error is of type int/int, and the result is of type int. when it is converted to byte, no forced type converter is added
//10 and 3 are int by default, so the maximum type after operation is int, which is 3
//So it's right
int f = 10 / 3;// 3

//First calculate 10 / 3 to 3, and then convert 3 to 3.0 according to automatic type conversion
double dd = 10 / 3;// 3.0

//First convert 3 to 3.0, then calculate 10.0 / 3.0, and then convert to double type
dd = 10.0 / 3;//3.33333333333333

long g = 10;
//Error: G is a long type. When g/3 is calculated, 3 will be converted from int type to long type, so g/3 gets the long type, but converts the long type to int type without castor
int h = g/3;
int h = (int)g/3;//correct
long h = g/3;//correct

//Error: g is first cast from long type to int type, then from int to byte type, while byte/int is finally int type according to the maximum capacity principle, byte h = int, without cast character
byte h = (byte)(int)g/3;
//Note: the javac compiler only checks syntax and does not evaluate
byte h = 3;//correct
byte h = (byte)(int)(g/3);//Correct. Calculate the priority principle. First calculate the priority in the brackets on the right
byte h = (byte)g/3;//Cannot convert because of priority problem. byte/int type is int type
byte h = (byte)(g/3);//Can be converted because the operation result does not exceed the byte value range

//Compilation error. short and byte operations will be converted to int type before operation
//Therefore, the operation result is int, but because the compiler does not calculate, it can only judge the syntax, so it judges to convert a large int into a small short without forced type conversion, and an error will be reported
short i = 10;
byte j = 5;
short k = i + j;
short k = 15;//The compilation passed and 15 did not exceed the short value range
short k = (short)(i + j);//Compile passed

char l = 'a';
System.out.println(l);//a
//Cast char type to byte type, but since it does not exceed the byte value range, there is no precision loss, and it is still 97
System.out.println((byte)l);//97

//First convert char type l to int type, 97, and then add it to 100
int m = l + 100;
System.out.println(m);//197

Topics: Java