Today's content
Tip: the following is the main content of this article. The following cases can be used for reference
1, Data type conversion
The data required to participate in the calculation in Java programs must ensure the consistency of data types. If the data types are inconsistent, type conversion will occur.
1. Automatic type conversion
-
When the data types are different, data type conversion will occur.
-
Automatic type conversion (implicit)
Features: the code does not need special processing and is completed automatically.
Rule: data range from small to large.
The automatic type conversion (implicit) code is as follows
public class Demo01DataType { public static void main(String[] args) { System.out.println(1024); // This is an integer. The default is int System.out.println(3.14); // This is a floating point number. The default is double // On the left is the long type, and on the right is the default int type. The left and right are different // An equal sign represents assignment, and the int constant on the right is given to the long variable on the left for storage // Int -- > long, which meets the requirements of data range from small to large // This line of code has automatic type conversion. long num1 = 100; System.out.println(num1); // 100 // double type is on the left and float type is on the right. The left and right are different // Float -- > double, which conforms to the rule from small to large // Automatic type conversion also occurred double num2 = 2.5F; System.out.println(num2); // 2.5 // The float type is on the left and the long type is on the right. The left and right are different // Long -- > float, the range is larger, which conforms to the rule from small to large // Automatic type conversion also occurred float num3 = 30L; System.out.println(num3); // 30.0 } }
2. Cast type
-
Cast (explicit)
Features: the code needs special format processing and cannot be completed automatically.
Format: type with small range variable name with small range = (type with small range) data with large range;
The cast (explicit) code is as follows
public class Demo02DataType { public static void main(String[] args) { // The int type is on the left and the long type is on the right. It's different // Long -- > int, not from small to large // Automatic type conversion cannot occur! // Format: type with small range variable name with small range = (type with small range) data with large range; int num = (int) 100L; System.out.println(num);// 100 } }
-
matters needing attention:
Cast type conversion is generally not recommended because precision loss and data overflow may occur;
Schematic diagram of cast data overflow:
byte/short/char these three types can perform mathematical operations, such as addition "+";
byte/short/char will be promoted to int first and then calculated;
Data type conversion cannot occur for boolean types.
public class Demo02DataType { public static void main(String[] args) { // The int type is on the left and the long type is on the right. It's different // Long -- > int, not from small to large // Automatic type conversion cannot occur! // Format: type with small range variable name with small range = (type with small range) data with large range; /* int num = (int) 100L; System.out.println(num); */ // long cast to int type int num2 = (int) 6000000000L; System.out.println(num2); // 1705032704 // Double -- > int, cast type int num3 = (int) 3.99; System.out.println(num3); // 3. This is not rounding. All decimal places will be discarded char zifu1 = 'A'; // This is A character variable with the capital letter A inside System.out.println(zifu1 + 1); // 66, that is, the capital letter A is treated as 65 // The bottom of the computer will use A number (binary) to represent the character A, which is 65 // Once the char type is mathematically operated, the character will be translated into a number according to certain rules byte num4 = 40; // be careful! The value size on the right cannot exceed the type range on the left byte num5 = 50; // byte + byte --> int + int --> int int result1 = num4 + num5; System.out.println(result1); // 90 short num6 = 60; // byte + short --> int + int --> int // Cast int to short: note that the logical real size must not exceed the short range, otherwise data overflow will occur short result2 = (short) (num4 + num6); System.out.println(result2); // 100 } }
3.ASCII coding table
-
Cross reference table of numbers and characters (coding table):
ASCII code table: American Standard Code for Information Interchange.
ASCII encoding table:
Unicode code table: universal code. It is also a comparison between numbers and symbols. The beginning 0-127 is exactly the same as ASCII, but it contains more characters from 128.
48 - '0'
65 - 'A'
97 - 'a'
public class Demo03DataTypeChar { public static void main(String[] args) { char zifu1 = '1'; System.out.println(zifu1 + 0); // 49 char zifu2 = 'A'; // In fact, the bottom layer stores the number 65 char zifu3 = 'c'; // On the left is the int type and on the right is the char type, // Char -- > int is really from small to large // Automatic type conversion occurred int num = zifu3; System.out.println(num); // 99 char zifu4 = 'in'; // Correct writing System.out.println(zifu4 + 0); // 20013 } }
2, Arithmetic operator
1. Four principles and modular operation
Operator: a symbol that performs a specific operation. For example:+
Expression: an expression connected by operators is called an expression. For example: 20 + 5. Another example: a + b
-
Four operations:
Add:+
Minus:-
Multiply:*
Except:/Modulus (remainder):%
First calculate the result of the expression, and then print out the result.
Review the division formula for the first grade of primary school:
Divisor / divisor = quotient... Remainder
For the expression of an integer, the division method uses integer division. When an integer is divided by an integer, the result is still an integer. Just look at the quotient, not the remainder.
The modulo operator has the meaning of remainder only for the division of integers.
-
matters needing attention:
Once there are different types of data in the operation, the result will be the one with a wide range of data types.
public class Demo04Operator { public static void main(String[] args) { // Mathematical operations can be performed between two constants System.out.println(20 + 30);// 50 // Mathematical operations can also be performed between two variables int a = 20; int b = 30; System.out.println(a - b); // -10 // Variables and constants can be mixed System.out.println(a * 10); // 200 int x = 10; int y = 3; int result1 = x / y; System.out.println(result1); // 3 int result2 = x % y; System.out.println(result2); // Remainder, modulus, 1 // int + double --> double + double --> double double result3 = x + 2.5; System.out.println(result3); // 12.5 } }
2. Multiple uses of plus sign
The plus sign "+" in the four operations has three common uses:
- For numbers, that's addition.
- For character char type, char will be promoted to int before calculation.
Comparison table between char type characters and int type numbers: ASCII and Unicode - For the String string (capitalized, not keyword), the plus sign represents the String join operation.
When any data type is connected to a string, the result will become a string
public class Demo05Plus { public static void main(String[] args) { // Basic use of string type variables // Data type variable name = data value; String str1 = "Hello"; System.out.println(str1); // Hello System.out.println("Hello" + "World"); // HelloWorld String str2 = "Java"; // String + int --> String System.out.println(str2 + 20); // Java20 // Priority issues // String + int + int // String + int // String System.out.println(str2 + 20 + 30); // Java2030 System.out.println(str2 + (20 + 30)); // Java50 } }
3. Self increasing and self decreasing operator
Autoincrement operator:++
Subtraction operator: –
-
Basic meaning: let a variable increase by a number 1, or let a variable decrease by a number 1
-
Use format: write before or after the variable name. For example, + + num, or num++
-
Usage:
Use alone: it is not mixed with any other operation and becomes a step independently.
Mixed use: mixed with other operations, such as assignment, printing, etc.
-
Use difference:
When used alone, there is no difference between pre + + and post + +. That is, + + num; And num + +; It's exactly the same.
When mixing, there are [significant differences]
If it is [first + +], the variable [immediately + 1], and then use it with the result. [add before use]
If it is [post + +], first use the original value of the variable, [and then let the variable + 1]. [add after use]
-
Note: only variables can use self increasing and self decreasing operators. Constants cannot be changed, so they cannot be used.
public class Demo06Operator { public static void main(String[] args) { int num1 = 10; System.out.println(num1); // 10 ++num1; // Used alone, front++ System.out.println(num1); // 11 num1++; // Used alone, after++ System.out.println(num1); // 12 System.out.println("================="); // When mixed with print operation int num2 = 20; // Mixed use, first + +, the variable immediately becomes 21, and then print the result 21 System.out.println(++num2); // 21 System.out.println(num2); // 21 System.out.println("================="); int num3 = 30; // After mixed use, + +, first use the original 30 of the variable, and then let the variable + 1 get 31 System.out.println(num3++); // 30 System.out.println(num3); // 31 System.out.println("================="); int num4 = 40; // Mixed with assignment operation int result1 = --num4; // Mixed use, before --, the variable immediately - 1 becomes 39, and then give the result 39 to the result1 variable System.out.println(result1); // 39 System.out.println(num4); // 39 System.out.println("================="); int num5 = 50; // After mixed use --, first give the original number 50 to result2, and then - 1 becomes 49 myself int result2 = num5--; System.out.println(result2); // 50 System.out.println(num5); // 49 System.out.println("================="); int x = 10; int y = 20; // 11 + 20 = 31 int result3 = ++x + y--; System.out.println(result3); // 31 System.out.println(x); // 11 System.out.println(y); // 19 // 30++; // Wrong writing! Constants cannot use + + or-- } }
3, Assignment operator
-
Assignment operators are divided into:
Basic assignment operator: it is an equal sign "=", which means to give the data on the right to the variable on the left. int a = 30;
Compound assignment operator:
+=a += 3 is equivalent to a = a + 3
-=b -= 4 is equivalent to b = b - 4
*=c *= 5 is equivalent to c = c * 5
/=d /= 6 is equivalent to d = d / 6
%=E% = 7 is equivalent to e = e% 7
-
matters needing attention:
Only variables can use assignment operators, and constants cannot be assigned.
Compound assignment operator, which implies a cast.
public class Demo07Operator { public static void main(String[] args) { int a = 10; // Translate according to the formula: a = a + 5 // a = 10 + 5; // a = 15; // a was originally 10, but now it is reassigned to 15 a += 5; System.out.println(a); // 15 int x = 10; // x = x % 3; // x = 10 % 3; // x = 1; // x used to be 10, but now re assign it to get 1 x %= 3; System.out.println(x); // 1 // 50 = 30; // Constants cannot be assigned and cannot be written to the left of the assignment operator. Wrong writing! byte num = 30; // num = num + 5; // num = byte + int // num = int + int // num = int // num = (byte) int num += 5; System.out.println(num); // 35 } }
4, Comparison operator
-
Comparison operator:
Greater than: >
Less than:<
Greater than or equal to: >=
Up to:<=
Equality: = = [two equal signs are equal, and one equal sign represents assignment]
Unequal:= -
matters needing attention:
The result of the comparison operator must be a boolean value, true or false
If you make multiple judgments, you can't write in succession.
In mathematics, for example, 1 < x < 3
This is not allowed in the program.
public class Demo08Operator { public static void main(String[] args) { System.out.println(10 > 5); // true int num1 = 10; int num2 = 12; System.out.println(num1 < num2); // true System.out.println(num2 >= 100); // false System.out.println(num2 <= 100); // true System.out.println(num2 <= 12); // true System.out.println("==============="); System.out.println(10 == 10); // true System.out.println(20 != 25); // true System.out.println(20 != 20); // false int x = 2; // System.out.println(1 < x < 3); // Wrong writing! Compilation error! You can't write in tandem. } }
5, Logical operator
- And (and) & & are all true, is true; Otherwise, it is false
- Or (or) | at least one is true, that is true; It's all false. It's false
- Not (reverse)! Originally true, it becomes false; It was false, but it became true
With "& &" or "|", it has a short-circuit effect: if the final result can be judged according to the left, the code on the right will no longer be executed, so as to save some performance.
-
matters needing attention:
Logical operators can only be used with boolean values.
And, or need to have a boolean value on the left and right respectively, but the reverse can only have a unique boolean value.
And, or two operators. If there are multiple conditions, they can be written continuously.
Two conditions: condition a & & condition B
Multiple conditions: condition a & & condition B & & condition C
TIPS:
For the case of 1 < x < 3, it should be split into two parts and connected with the and operator:
int x = 2; 1 < x && x < 3
public class Demo09Logic { public static void main(String[] args) { System.out.println(true && false); // false // true && true --> true System.out.println(3 < 4 && 10 > 5); // true System.out.println("============"); System.out.println(true || false); // true System.out.println(true || true); // true System.out.println(false || false); // false System.out.println("============"); System.out.println(true); // true System.out.println(!true); // false System.out.println("============"); int a = 10; // false && ... System.out.println(3 > 4 && ++a < 100); // false System.out.println(a); // 10 System.out.println("============"); int b = 20; // true || ... System.out.println(3 < 4 || ++b < 100); // true System.out.println(b); // 20 } }
6, Ternary operator
-
Unary operator: an operator that can operate on only one data. For example: reverse Self increasing + +, self decreasing –
-
Binary operator: an operator that requires two data to operate. For example: addition +, assignment=
-
Ternary operator: an operator that requires three data to operate.
-
Format:
Data type variable name = condition judgment? Expression A: expression B;
-
technological process:
First, judge whether the conditions are true:
If established as true,Then the expression A The value of is assigned to the variable on the left; If not established as false,Then the expression B The value of is assigned to the variable on the left; Choose one of the two.
-
matters needing attention:
Both expression A and expression B must meet the requirements of the left data type.
The result of the ternary operator must be used.
public class Demo10Operator { public static void main(String[] args) { int a = 10; int b = 20; // Data type variable name = condition judgment? Expression A: expression B; // Judge whether a > b is true. If it is true, assign the value of a to max; If not, assign the value of B to max. Choose between the two int max = a > b ? a : b; // Maximum variable System.out.println("Maximum:" + max); // 20 // int result = 3 > 4 ? 2.5 : 10; // Wrong writing! System.out.println(a > b ? a : b); // Write correctly! // a > b ? a : b; // Wrong writing! } }
7, Simple method definitions and calls
1. Introduction to methods_ Concept introduction
When we learn operators, we create a new class and main square for each operator separately
Method, we will find that writing code in this way is very cumbersome, and there is too much repeated code. Can we avoid these repeated codes? We need to use methods to implement them.
Method: extract a function and define the code in a brace to form a separate function.
When we need this function, we can call it. This not only realizes the reusability of the code, but also solves the phenomenon of code redundancy.
2. Definition of method
-
Define the format of a method:
public static void Method name() { Method body }
-
The naming rule of method name is the same as that of variable, using small hump.
-
Method body: that is, braces can contain any statement.
-
matters needing attention:
The order in which methods are defined does not matter.
The definition of a method cannot produce nested containment relationships.
After the method is defined, it will not be executed. If you want to execute, you must call the method.
public class Demo11Method { public static void main(String[] args) { } // cook public static void cook() { System.out.println("Wash vegetables"); System.out.println("cut up vegetables"); System.out.println("Stir fry"); System.out.println("Plate loading"); } // I public static void me() { System.out.println("eat"); } // Peddler public static void seller() { System.out.println("Transport to farmers' market"); System.out.println("Raise the price"); System.out.println("Shout"); System.out.println("Sell to the cook"); } // Farmer uncle public static void farmer() { System.out.println("sow"); System.out.println("watering"); System.out.println("apply fertilizer"); System.out.println("Pest control"); System.out.println("harvest"); System.out.println("Sell to small vendors"); } }
3. Method call
-
How to call a method, format:
Method name();
public class Demo11Method { public static void main(String[] args) { farmer(); // Call farmers' methods seller(); // Call the vendor's method cook(); // Call the cook's method me(); // Call my own method } // cook public static void cook() { System.out.println("Wash vegetables"); System.out.println("cut up vegetables"); System.out.println("Stir fry"); System.out.println("Plate loading"); } // I public static void me() { System.out.println("eat"); } // Peddler public static void seller() { System.out.println("Transport to farmers' market"); System.out.println("Raise the price"); System.out.println("Shout"); System.out.println("Sell to the cook"); } // Farmer uncle public static void farmer() { System.out.println("sow"); System.out.println("watering"); System.out.println("apply fertilizer"); System.out.println("Pest control"); System.out.println("harvest"); System.out.println("Sell to small vendors"); } }