Java basic syntax

Keywords: Java Vue.js intellij-idea

Key points of Java basic syntax

Type conversion

1. Basic data type Conversion

In Java programs, the values of different basic data types often need to be converted to each other. The seven numeric types provided by java language can be converted to each other. There are two conversion methods for basic data type conversion: automatic type conversion and forced type conversion.

2. Automatic type conversion (implicit type conversion)

Automatic conversion:

  • Automatically promote a type with a small value range to a type with a large value range.

Conversion rules for basic data types

Summary: through the above case, we can get the conversion relationship of data types (value range from small to large), as shown in the figure:

(1) When a value with a small storage range (constant value, variable value, result value of expression calculation) is assigned to a variable with a large storage range,

int i = 'A';//char is automatically upgraded to int
double d = 10;//int is automatically upgraded to double

byte b = 127; //The integer constant value on the right must be in the range of - 128 ~ 127
//byte bigB = 130;// Error, the integer constant value on the right exceeds the byte range
long num = 1234567; //If the integer constant value on the right is in the int range, it can be compiled and run through. Here, data type conversion is involved
long bigNum = 12345678912L;//If the integer constant value on the right exceeds the int range, L must be added, otherwise the compilation fails

(2) When a data type with a small storage range is mixed with a data type with a large storage range, it will be calculated according to the largest type

int i = 1;
byte b = 1;
double d = 1.0;

double sum = i + b + d;//Mixed operation, upgrade to double

(3) When the byte, short and char data types perform arithmetic operations, they are processed according to the int type

byte b1 = 1;
byte b2 = 2;
byte b3 = b1 + b2;//An error is reported during compilation. b1 + b2 is automatically upgraded to int

char c1 = '0';
char c2 = 'A';
System.out.println(c1 + c2);//113 

(4) boolean type does not participate

3. Forced type conversion (display type conversion)

What happens when 1.5 is assigned to a variable of type int? Failed to generate compilation. It must be unable to assign value.

int i = 3.14; // error

If you want to assign a value successfully, you can assign a value only by casting a double type to an int type.

  • Forced type conversion: converts a type with a large value range into a type with a small value range.

In comparison, automatic conversion is performed automatically by Java, and forced conversion needs to be performed manually by ourselves.

Conversion format:

Data type variable name = ((data type) forced data value;

(1) When a value with a large storage range (constant value, variable value, result value of expression calculation) is assigned to a variable with a small storage range, forced type conversion is required. Prompt: there is a risk that precision may be lost or overflow may occur

int i = (int)3.14;//Cast, loss of precision

double d = 1.2;
int num = (int)d;//Loss accuracy

int i = 200;
byte b = (byte)i;//overflow

(2) boolean type does not participate

(3) Cast can also be used when a value wants to promote a data type

int i = 1;
int j = 2;
double shang = (double)i/j;

Tip: there is no risk of cast in this case.

4. Special data type conversion

1. When "+" operation is performed between any data type and String type, the result must be String type

System.out.println("" + 1 + 2);//12

2. However, the String type cannot be converted to another type through mandatory type ()

String str = "123";
int num = (int)str;//FALSE
int num = Integer.parseInt(str);//It can be mentioned later that it can be transferred with the help of packaging methods

5. Practice

1,Exercise: judge whether the following code has been compiled. If so, what is the result?
short s1 = 12;
short s2 = 8;
short s3 = s1 + s2; //An error is reported during compilation. s1 + s2 is automatically upgraded to int

No, the reason is when byte,short,char When performing arithmetic operations on data types, the int Type processing
		short s1 = 12;
        short s2 = 8;
        short s3 = (short) (s1 + s2);

2,Exercise: judge whether the following code has been compiled. If so, what is the result?
short s1 = 12;
short s2 = 8;
byte s3 = (byte)(s1 + s2);

//          byte
//          Memory occupied: 1 byte
//          Storage range: - 128 ~ 127, from large to small
 Output result 20



3,Exercise: judge whether the following code has been compiled. If so, what is the result?
char c1 = '0';
char c2 = '1';
char c3 = c1 + c2;

Cannot be converted to by character addition int Type needs to be converted to char perhaps int output a  And 97 
		char c1 = '0';
        char c2 = '1';
        char c3 = (char)(c1 + c2);
        int  C3 = c1 + c2;
        System.out.println(c3);
        System.out.println(C3);
        


4,Exercise: judge whether the following code has been compiled. If so, what is the result?
char c1 = '0';
char c2 = '1';
System.out.println(c1 + c2);

This direct output operation result 97 is converted to int Type operation

5,Exercise: judge whether the following code has been compiled. If so, what is the result?
int i = 4;
long j = 120; //Because the right 120 is of type int by default, it is possible to assign the value of int to the long type, and the type conversion will be automatic. However, it is required that the int value cannot exceed the storage range of int. if it exceeds the storage range of int, L must be added
double d = 34;
float f = 1.2;//Because 1.2 on the right is of double type by default, the value of double cannot be directly assigned to float. Either add F or use forced type conversion.

System.out.println(i + j + d + f);//Finally, double






6,Exercise: judge whether the following code has been compiled. If so, what is the result?
int i = 1;
int j = 2;
double d = i/j;
System.out.println(d);

Output result 0.0



The difference between double and float

Because of some doubts in question 5, it turns out that writing decimals defaults to double

Decimals in Java can be double and float. The default is double,

The default decimal is double. You can add D or d after it, but this is superfluous. For example, 1.0d is the default, so you can write 1.0 without adding it

Decimal. If you want to specify float, you must add f after it, such as 1.0f

6. Supplement: storage range of basic data types of Java

1. Integer series

(1) Byte: byte type

  • Memory occupied: 1 byte

  • Storage range: - 128 ~ 127

(2) Short: short integer type

  • Memory occupied: 2 bytes

  • Storage range: - 32768 ~ 32767

(3) int: integer

  • Memory occupied: 4 bytes

  • Storage range: - 31st power of 2 ~ 31st power of 2 - 1

(4) long: integer

  • Memory occupied: 8 bytes

  • Storage range: - 63rd power of 2 ~ 63rd power of 2 - 1

Note: if you want to represent a constant integer beyond the int range, which is of type long, you need to add L after the number

2. Floating point series (decimal)

(1) float: single precision floating point

  • Memory occupied: 4 bytes

  • Precision: 6 ~ 7 digits after the decimal point of scientific notation

Note: if you want to indicate that a constant decimal is of float type, you need to add f or F after the number, otherwise it is of double type

(2) Double: double precision floating point

  • Memory occupied: 8 bytes

  • Accuracy: 15 ~ 16 digits after the decimal point of scientific notation

float f = 12.0F;//If you assign a decimal constant value to the right, you must add f or F

3. Single character type: char

  • Memory occupied: 2 bytes

4. Boolean type

boolean: only true or false can be stored

Although the underlying computer uses 0 and 1 to represent false and true, variables of boolean type cannot be assigned 0 and 1 in the code, only false and true can be assigned

Operator

1. Remainder operation

Modular operation refers to modular operation, that is, finding the remainder of m/n.

 
 		System.out.println(3 % 4);// Three four times zero plus one equals three
 		System.out.println(5%2);//One two times two plus one equals five
		System.out.println(5%-2);//1 - 2 times - 2 plus 1 equals 5
		System.out.println(-5%2);//-1  
		System.out.println(-5%-2);//-1	
Why is this a little windy
		//Quotient * divisor + remainder = divisor
		//5% - 2 = = > quotient is - 2, when the remainder is 1 (- 2) * - 2) + 1 = 5
		//-5% 2 = = > quotient is - 2, remainder is - 1 (- 2) * 2 + (- 1) = - 4-1 = - 5


2. Two usages of "+" sign

  • The first kind: if both sides of + are numeric values, + means addition
  • The second: if at least one side of + is a string, + means splicing
public class OperatorDemo02 {
	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 + 520); // Java520
		// String + int + int
		// String		+ int
		// String
		System.out.println(str2 + 5 + 20); // Java520
	}
}

practice

(1) Get a four digit number, ten digit, hundred digit and thousand digit

Key points: make full use of / and%

/Eliminate last digit

%Find the last digit

public class LianXi {

    public static void main(String[] args) {

        //1. Define a four digit number, such as 1234
        int num = 1234;

        //2. Calculate one bit, ten bit, hundred bit and thousand bit through operation
        int ge = num%10;  //Find the last digit 4 directly
        int shi = num/10%10; //First kill the last one on the left, then it becomes 123, and then% to get the last 3
        int bai = num/100%10; //Similarly, first kill the last one on the left, then it becomes 12, and then% to get the last 2
        int qian = num/1000; //12 kill 2 and there's 1 left

        System.out.println(num + "The four digit number is:" + ge);
        System.out.println(num + "The four digit ten digit number is:" + shi);
        System.out.println(num + "The numbers in the four hundreds are:" + bai);
        System.out.println(num + "The number on this four digit thousand is:" + qian);
    }
}

Exercise: judge the running results of the following programs

public static void main(String[] args){
	int a = 1;
	int b = 2;
	int c = 0;
	boolean flag = false;
	if(flag=true){
		c = a++ + b;
	}

	if(flag=false){
		c = ++a - b;
	}
	System.out.println("a = " + a);
	System.out.println("b = " + b);
	System.out.println("c = " + c);
}	

##3, & & and & difference, | and | difference

  • **&&And & * * difference:
    • &&Like the result of &, & & has short circuit effect, false on the left and not executed on the right& Whatever is on the left, it will be executed on the right.
  • **||Difference between and * *:
    • ||As the result of | is the same, it has a short circuit effect. The left side is true and the right side is not executed| Whatever is on the left, it will be executed on the right.

Interview questions

Note that the if statement goes in, but if it does not meet the conditions, it will be output directly

public class LogicExer1{
	public static void main(String[] args){
		int x = 1;
		int y = 1;

		//X = = 2, x + + false x = 2, false on the left
		//Continue on the right
		//++Y = = 2 y = 2 y = = 2 true on the right
		//False & true result false
		if(x++==2 & ++y==2){
			x =7;
		}
		System.out.println("x="+x+",y="+y);//x=2,y=2
	}
}
public class LogicExer2{
	public static void main(String[] args){
		int x = 1,y = 1;

		//x==2,x + + left condition is false, x=2
		//Because of the short circuit and, the right side does not count
		//false && ?  The result is false
		if(x++==2 && ++y==2){
			x =7;
		}
		System.out.println("x="+x+",y="+y);//x=2,y=1
	}
}
public class LogicExer3{
	public static void main(String[] args){
		int x = 1,y = 1;

		//x==1,x + + left is true, x=2
		//Because it's logical and, continue on the right  
		//++y. Y = = 1 y = 2 false on the right
		//Condition true | false, and finally true
		if(x++==1 | ++y==1){
			x =7;
		}
		System.out.println("x="+x+",y="+y);//x=7,y=2
	}
}	
public class LogicExer4{
	public static void main(String[] args){
		int x = 1,y = 1;

		//x==1,x + + left is true, x=2
		//Because it is a short circuit or, the left side is true, and the right side does not look
		//The entire condition is true
		if(x++==1 || ++y==1){
			x =7;
		}
		System.out.println("x="+x+",y="+y);//x=7,y=1

	}
}

Interview questions

class  Test4_2  {
	public static void main (String []  args)  {
		boolean x = true;
		boolean y = false;
		short z = 42;
		
		//If the if(y=true) condition holds, then judge if ((Z + + = = 42) & & (y = = true)) 	 z++;	
		//If not, if ((Z + + = = 42) & & (y = = true)) 	 z++; 	 Don't look
		/*
		if(y = true)
				
		if((z++==42)&&(y==true))	z++;	
		
		if((x=false) || (++z==45))  z++;
		*/
		
		//standard
		//When y=true is assigned, y is modified to true, and if (true) holds
		if(y=true){
			//On the left: z==42,z + + is established, and Z becomes 43
			//&&Short circuit and, if the short circuit condition is not satisfied, continue on the right
			//y==true
			//True & & true, the result is true
			if((z++==42)&&(y==true)){
				//z + + becomes 44
				z++;
			}
		}
		//Left: x=false does not hold
		//Although there is a short circuit or in the middle, it does not meet the short circuit condition. Continue on the right
		//++z. z==45 + + Z becomes 45, and z==45 holds
		if((x=false) || (++z==45)){
			//z + +, become 46
			z++;
		}
		System. out.println("z="+z);//46
	}
}

Conditional operator

  • Conditional operator format:
Conditional expression? Result 1: result 2
  • Conditional operators are evaluated:
    • The result of condition judgment is true, and the overall result of condition operator is result 1, which is assigned to variable.
    • The result of the judgment condition is false, and the overall result of the condition operator is result 2, which is assigned to the variable.
public static void main(String[] args) {
    int i = (1==2 ? 100 : 200);
    System.out.println(i);//200
    int j = (3<=4 ? 500 : 600);
    System.out.println(j);//500
}

Add some exercises

Judge leap year

public class Test09 {

	public static void main(String[] args) {
		int year = 2018;
		boolean result = year%4==0 && year%100!=0 || year%400==0;
		System.out.println(year + (result ? "It's a leap year" : "Not a leap year"));
	}

}

i=0.2; Equal to 0*

The calculation result of the following code is:
int i = 1;
i *= 0.2;  
i++;
System.out.println("i=" + i);//i=1
The operation result of the following code is:
int i = 2;
i *= i++;

int j = 2;
j *= j+1; 

int k = 2;
k *= ++k;

System.out.println("i=" + i);//i=4
System.out.println("j=" + j);//i=6
System.out.println("k=" + k);//i=6
	public static void main(String[] args) {
		int a = 8, b = 3;
		System.out.println(a>>>b);//1
		System.out.println(a>>>b | 2);//2
	}

8;
boolean result = year%40 && year%100!=0 || year%4000;
System.out.println(year + (result? "Is a leap year": "is not a leap year");
}

}

**i*=0.2;  Equal to 0**

The calculation result of the following code is:
int i = 1;
i *= 0.2;
i++;
System.out.println("i=" + i);//i=1





```java
 The operation result of the following code is:
int i = 2;
i *= i++;

int j = 2;
j *= j+1; 

int k = 2;
k *= ++k;

System.out.println("i=" + i);//i=4
System.out.println("j=" + j);//i=6
System.out.println("k=" + k);//i=6
	public static void main(String[] args) {
		int a = 8, b = 3;
		System.out.println(a>>>b);//1
		System.out.println(a>>>b | 2);//2
	}

Posted by Kibeth on Fri, 19 Nov 2021 08:40:57 -0800