Detailed explanation of Java basic syntax

Keywords: Java

1 data types and operators

1.1 variables

Overview of variable types

1.1.1 integer variable

Integer type: byte, short, int, long

Basic syntax format:
Data type variable name = initial value;
Code example:

int  num1 = 10;//Define an integer variable
System.out.println(num1);
long  num2  = 10L;//Defines a long integer variable whose initial value can be the uppercase letter L
System.out.println(num2);//It can also be written as a lowercase L (not a number 1)

If the result of the operation exceeds the maximum range of int, overflow will occur

int maxValue = Integer.MAX_VALUE;//Maximum value of int
System.out.println(maxValue+1);//The output result is the minimum value of int
int mINValue = Integer.MIN_VALUE;//Minimum value of int
System.out.println(minValue-1);//The output result is: the maximum value of int

be careful:

1. The integer constant of Java is of type int by default. The declaration of a long constant must be followed by a lowercase letter 'l' or an uppercase 'l'
2. Variables in Java programs are usually declared as int type. long is used unless it is insufficient to represent a large number

1.1.2 floating point variables

float: single precision, mantissa can be accurate to 7 significant digits. In many cases, the accuracy is difficult to meet the requirements.
Double: double precision. The precision is twice that of float. This type is usually used.

Basic syntax format:
Variable type: variable name = initial value;
Code example:

double num3 = 1.0;//Define a double variable
System.out.println(num3);
float  num4 = 1.0f;//Define a single precision variable
System.out.println(num4);

be careful:

1. The floating point constant of Java is double by default. When declaring a floating constant, it must be followed by 'f' or 'f'.
2. The decimal itself does not have an exact number, but can only be accurate to a few digits

1.1.3 character and Boolean variables

character
char data is used to represent "characters" (2 bytes) in the usual sense

All characters in Java are encoded in Unicode, so one character can store one word
Parent, a Chinese character, or a character in other written languages.

There are three forms of character variables:
A character constant is a single character enclosed in single quotation marks ('').
For example:

  char c1 = 'a';
   char c2= 'in'; 
   char c3 = '9';

The escape character '\' is also allowed in Java to convert subsequent characters into special character constants.
For example:

 char c3 = '\n'; // '\ n' indicates a newline character

Use Unicode values directly to represent character constants:
‘\uXXXX’. Where XXXX represents a hexadecimal integer. For example: \ u000a means \ n.

char type can be operated on. Because it all corresponds to Unicode code.

Boolean
boolean type is used to judge logical conditions and is generally used for program flow control:

if conditional control statement;

while loop control statement;

Do while loop control statement;

for loop control statement;

matters needing attention:

1.boolean type data can only take values of true and false without null.

2. boolean type and int in Java cannot be converted to each other, and 0 or non-0 integers can not be used to replace false and true, which is different from C language.

3. Some JVM implementations of Boolean data only occupy one byte, and some occupy one bit. This is not clearly specified.

There are no bytecode instructions dedicated to boolean values in the Java virtual machine. The boolean values expressed in the Java language are replaced by the int data type in the Java virtual machine after compilation: true is represented by 1 and false by 0 - Java virtual machine specification version 8

1.1.4 string type variables

String is not a basic data type, but a reference data type

Basic syntax format:
String variable name = "initial value"

Some specific characters in the string that are not convenient for direct representation need to be escaped.
Examples of escape characters:

//Create a string My name is "Superman"
String name = "My name is \"superman\"";

//The usage method is consistent with the basic data type.
//For example:
 String str = "abcd";
 //A string can be concatenated with another string, or other types of data can be directly concatenated.
// For example:
str = str + "xyz" ;//String and string
int n = 100;//String and integer

The above code shows that when there is a string in a + expression, the string splicing behavior is executed.

Print multiple strings or numbers at the same time

int a = 10;
int b = 20;
System.out.println("a = "+a+"b = "+b);

1.1.5 scope of variable

That is, the effective range of the variable, which is generally the code block (braces) where the variable definition is located
Code example:

class Test{
    public static void main(String[] args){
    {
        int x = 10;
        System.out.println(x);//Compile passed
    }
    System.out.println(x);//Compilation failed, variable x not found 
    }
}

1.1.6 naming specification of variables

Hard index:

1. A variable name can only contain numbers, letters and underscores ($yes, not recommended)
2. The number cannot begin
3. Variable names are case sensitive. Num and num are two different variables

Soft index:

1. Descriptive, see the meaning of the name
2. Pinyin should not be used (not absolute)
3. It is recommended to use nouns in part of speech
4. The small hump naming method is recommended. When a variable is composed of multiple words, the initials of other words are capitalized except the first word

Example of small hump naming:

int maxValue = 100;
String studentName = "superman";

1.2 conversion between basic data types

1.2.1 constants

Constant means that the type cannot be changed at run time, and the constant has been determined at compile time

1. Literal constant

10 // int literal constant (decimal) 
010 // The int literal constant (octal) starts with the number 0. 010 is the decimal 8 
0x10 // The int literal constant (hexadecimal) starts with the number 0x. 0x10 is the decimal 16 
10L // long literal constant. It can also be written as 10l (lowercase L) 
1.0 // double literal constant. It can also be written as 1.0D or 1.0D 
1.5e2 // double literal constant. Expressed in scientific notation. Equivalent to 1.5 * 10 ^ 2 
1.0f // float literal constant can also be written as 1.0F 
true // boolen literal constant, and also false 
'a' // char literal constant. There can only be one character in single quotation marks
"abc" // String literal constant. There can be multiple characters in double quotation marks

2. Constant modified by final keyword

final int a = 10;
a = 20;//Compilation error, prompting that the final variable a cannot be assigned a value

1.2.2 understanding type conversion

As a strongly typed programming language, Java has strict verification when different types of variables are assigned to each other
int and long / double are assigned to each other

int a = 10; 
long b = 20; 
a = b; // Compilation error, prompt may lose precision 
b = a; // The compilation passed 
//Long indicates a larger range. You can assign int to long, but you can't assign long to int
int a = 10; 
double b = 1.0; 
a = b; // Compilation error, prompt may lose precision 
b = a;
//Double represents a larger range. You can assign int to double, but you can't assign double to int

Conclusion: the assignment between variables of different numerical types indicates that the type with smaller range can be implicitly converted to the type with larger range, otherwise it is not

int and boolean are assigned to each other

int a = 10; 
boolean b = true; 
b = a; // Compilation error, prompt incompatible types
a = b; // Compilation error, prompt incompatible types

Conclusion: int and boolean are two irrelevant types and cannot be assigned to each other

int literal constant to byte

byte a = 100; // Compile passed
byte b = 256; // An error is reported during compilation, indicating that conversion from int to byte may be lost
//Note: byte indicates that the data range is - 128 - > + 127, 256 has exceeded the range, and 100 is still within the range

Conclusion: when using literal constant assignment, Java will automatically perform some checks to determine whether the assignment is reasonable
Summary:
1. Assignment between variables of different numeric types indicates that types with a smaller range can be implicitly converted to types with a larger range
2. If you need to assign a type with a large range to a type with a small range, you need to force type conversion, but the precision may be lost
3. When assigning a literal constant, Java will automatically check the number range

1.2.3 understanding numerical improvement

Mixed operation of int and long

int a = 10; 
long b = 20; 
int c = a + b; // Compilation error, prompt that converting long to int will lose precision
long d = a + b; // The compilation passed

Conclusion: when int and long are mixed, int will be promoted to long, and the result is still of long type. You need to use variables of long type to receive the result. If you do not want to use int to receive the result, you need to use forced type conversion

Operation of byte and byte

byte a = 10; 
byte b = 20; 
byte c = a + b; 
System.out.println(c); 
// Compilation error
//Test.java:5: error: incompatible type: conversion from int to byte may be lost
// byte c = a + b; 

Conclusion: byte and byte are of the same type, but the compilation error occurs. The reason is that although a and b are both bytes, calculating a + b will first promote a and b to int, and then calculate. The result is also int. if this is assigned to c, the above error will occur
Since the CPU of the computer usually reads and writes data from the memory in units of 4 bytes, for the convenience of hardware implementation, types less than 4 bytes, such as byte and short, will be promoted to int first, and then participate in the calculation

Correct writing:

byte a = 10; 
byte b = 20; 
byte c = (byte)(a + b); 
System.out.println(c);

Summary of type promotion:
1. For mixed operations of different types of data, those with a small range will be promoted to those with a large range

2. Short and byte, which are smaller than 4 bytes, will be promoted to 4-byte int before operation

1.2.4 conversion between string and int

Convert int to String

int num = 10; 
// Method 1 
String str1 = num + ""; 
// Method 2 
String str2 = String.valueOf(num); 

Convert String to int

String str = "100"; 
int num = Integer.parseInt(str);

1.2.5 conversion of basic data types (key points)

Automatic type conversion:
Types with small capacity are automatically converted to data types with large capacity.
The data types are sorted by capacity:

Summary:
1. When there are multiple types of data mixed operation, the system will automatically convert all data into the data type with the largest capacity first, and then calculate.
2. Byte, short and char are not converted to each other. They are first converted to int type during calculation.
3.boolean type cannot operate with other data types.
4. When the value of any basic data type is connected with the string (+), the value of the basic data type will be automatically converted to the string type.

1.3 operators

1.3.1 arithmetic operators

Overview of arithmetic operators:

Points needing attention in Division:
1. The result of int / int is still int, which needs to be calculated with double

int a = 1;
int b = 2;
System.out.println(a / b);
//The result is 0
  1. 0 cannot be a divisor

  2. %It represents remainder. You can find modules not only for int, but also for double

System.out.println(11.5%2.0);
//Operation results
1.5

1.3.2 relational operators

Overview of relational operators:

be careful:
1. The results of relational operators are boolean, that is, they are either true or false.
2. The relational operator "= =" cannot be written as "=".

1.3.3 logical operators

There are three main logical operators:

&&  //Both operands are true, and the result is true; otherwise, it is false
||  //All are false, the result is false, otherwise it is true
!  //Logical reverse operation

be careful:
The operation result and return value of the logical operator are boolean

Short-circuit evaluation

&&And | follow the short circuit evaluation rules.

System.out.println(10 > 20 && 10 / 0 == 0);//Print false
System.out.println(10 < 20 || 10 / 0 == 0);//Print true
//Calculating 10 / 0 will cause the program to throw an exception. However, the above code can run normally,
// It means that 10 / 0 is not really evaluated

Conclusion:
1. For & &, if the left expression value is false, the overall value of the expression must be false, and there is no need to calculate the right expression
2. For 𞓜, if the left expression value is true, the overall value of the expression must be true, and there is no need to calculate the right expression
3. & and | are not recommended and do not support short circuit evaluation

1.3.4 bitwise operators

Overview of bitwise operators:

Bit operations represent calculations in binary bits

be careful:

  1. The number of 0x prefix is hexadecimal. Hexadecimal can be regarded as a simplified form of binary. One hexadecimal corresponds to four binary bits.
  2. 0xf represents 15 in hexadecimal, that is, 1111 in binary
  3. Shift 1 bit to the left, which is equivalent to the original number * 2. Shift N bits to the left, which is equivalent to the nth power of the original number * 2
  4. Shift 1 bit to the right, which is equivalent to the original number / 2. Shift N bits to the right, which is equivalent to the nth power of the original number / 2
  5. Because the shift efficiency of computer calculation is higher than that of multiplication and division, when a code exactly multiplies and divides to the nth power of 2, it can be replaced by shift operation
  6. Moving negative digits or shifting too many digits is meaningless

1.3.5 conditional operators

Conditional operators are also called ternary operators

Syntax format:

Expression 1? Expression 2: expression 3

When the value of expression 1 is true, the value of the whole expression is the value of expression 2; If false, the value of the entire expression is the value of expression 3.

//Find the maximum of two numbers
int a = 10;
int b = 20;
int max = a > b ? a : b;

2 program flow control

1. Sequential structure

Sequential structure, that is, it is executed line by line in the order of code writing

System.out.println("aaa");
System.out.println("bbb");
System.out.println("ccc");
//Operation results
aaa
bbb
ccc

2. Branch structure

2.1.1 if statement

Basic grammatical form 1

if (Boolean expression){//It can only be Boolean expression, which is different from C language
    //Code executed when conditions are met
}

Basic grammatical form 2

if(Boolean expression){
    //Code executed when conditions are met
}else{
    //Code executed when conditions are not met
}

Basic grammatical form 3

if(Boolean expression){
    //Execute code when conditions are met
}else if(Boolean expression){
    //Execute code when conditions are met
}else{
    //Execute code when none of the conditions are met
}

Code example:

//Determine whether a number is odd or even
int num = 10;
if(num % 2 == 0){
    System.out.println("num It's an even number");
}else{
     System.out.println("num It's an odd number");
}

Note: suspension else problem

int x = 10;
int y = 10;
if (x == 10) 
     if (y == 10)
         System.out.println("aaa");
else
     System.out.println("bbb");

if / else statements can be written without parentheses. However, statements can also be written (only one statement can be written). At this time, else matches the closest if
But in the actual development, we don't recommend this. It's best to add braces.

2.1.2 switch statement

Basic syntax:

switch(integer|enumeration|character|character string){
     case Content 1 : {
         Execute statement when content is satisfied;
         break;
         }
     case Content 2 : {
         Execute statement when content is satisfied;
         break;
         }
     ...
     default:{
         Execute the statement when the content is not satisfied;
         break;
         } 
}

matters needing attention:

  1. Do not omit break, otherwise you will lose the effect of "multi branch selection"
  2. The value in switch can only be an integer | enumeration | character | string
  3. The data types of parameters that cannot be used for switch are: long, float, double, Boolean

3. Circulation structure

2.3.1 while cycle

Basic syntax format:

while(Cycle condition){//If the loop condition is a Boolean expression, execute the statement, otherwise end the loop.
    Loop statement;
}

Example code 1: calculate the sum of 1-100

int n = 1; 
int result = 0; 
while (n <= 100) { 
    result += n; 
    n++; 
} 
System.out.println(num); 
// results of enforcement
5050

be careful:
The following statement of while may not write {}, but only one statement can be supported when it is not written.

2.3.2 break and continue

The function of break is to end the loop early

Code example: find the multiple of the first 3 in 100-200

int num = 100; 
while (num <= 200) { 
    if (num % 3 == 0) { 
    System.out.println("A multiple of 3 was found, by:" + num); 
    break; 
    } 
    num++; 
} 
// results of enforcement
 Found a multiple of 3, 102

The function of continue is to skip this cycle, and the following code will no longer run

Code example: find multiples of all 3 in 100-200

int num = 100; 
while (num <= 200) { 
    if (num % 3 != 0) { 
    num++; // Don't forget the + + here! Otherwise, there will be a dead cycle 
    continue; 
    } 
    System.out.println("A multiple of 3 was found, by:" + num); 
    num++; 
}

2.3.3 for loop

Basic syntax:

for(Expression 1; Expression 2; Expression 3){
    Circulatory body;
}

Expression 1: used to initialize loop variables
Expression 2: loop condition
Expression 3: update loop variable

Example code: calculate 1+ 2!+ 3!+ 4!+ 5!

int sum = 0; 
for (int i = 1; i <= 5; i++) { 
    int tmp = 1; 
    for (int j = 1; j <= i; j++) { 
    tmp *= j; 
    }  
    sum += tmp; 
} 
System.out.println("sum = " + sum);

4. Input and output

2.4.1 output to console

Basic Calligraphy:

System.out.println(msg); // Output a string with newline
System.out.print(msg); // Output a string without line breaks
System.out.printf(format, msg); // Format output

println output content comes with \ n, print does not \ n
The format output mode of printf is basically the same as that of C language

2.4.2 input from keyboard

Use Scanner to read string / integer / floating point number

import java.util.Scanner; // The util package needs to be imported
Scanner sc = new Scanner(System.in); 
System.out.println("Please enter your name:"); 
String name = sc.nextLine(); 
System.out.println("Please enter your age:"); 
int age = sc.nextInt(); 
System.out.println("Please enter your monthly salary:"); 
float salary = sc.nextFloat(); 
System.out.println("Your information is as follows:"); 
System.out.println("full name: "+name+"\n"+"Age:"+age+"\n"+"Salary:"+salary); 
sc.close(); // Note that remember to call the close method
// results of enforcement
 Please enter your name:
superman
 Please enter your age:
19
 Please enter your monthly salary:
25000 
Your information is as follows:
full name: superman
 Age: 19
 Salary: 25000

Use the Scanner loop to read N numbers

Scanner sc = new Scanner(System.in); 
double sum = 0.0; 
int num = 0; 
while (sc.hasNextDouble()) { 
    double tmp = sc.nextDouble(); 
    sum += tmp; 
    num++; 
} 
System.out.println("sum = " + sum); 
System.out.println("avg = " + sum / num); 
sc.close(); 
// results of enforcement
10 
40.0 
50.5 
^Z 
sum = 150.5 
avg = 30.1

Note: when multiple data are input circularly, ctrl+z is used to end the input, and ctrl+D is used in IDEA

Supplement to Java syntax knowledge points

Naming conventions in Java

Naming conventions in Java:

Package name: all letters are lowercase when composed of multiple words: xxxyyyzzz z

Class name and interface name: when composed of multiple words, the first letter of all words is capitalized: xxxyyyzz

Variable name and method name: when composed of multiple words, the first word is lowercase, and the second word starts each
Word initial capital: xxxyyyzz

Constant name: all letters are capitalized. When there are multiple words, each word is underlined: XXX_YYY_ZZZ

Keywords in Java


Posted by andygrant on Mon, 18 Oct 2021 17:38:22 -0700