The latest Java basic series courses--Day02-Java basic grammar

Author Homepage: Programming Compass

About the author: High-quality creator in the Java field, CSDN blog expert
, CSDN content partner, invited author of Nuggets, Alibaba Cloud blog expert, 51CTO invited author, many years of architect design experience, resident lecturer of Tencent classroom

Main content: Java project, Python project, front-end project, artificial intelligence and big data, resume template, learning materials, interview question bank, technical mutual assistance

Favorites, likes, don't get lost, it's good to follow the author

Get the source code at the end of the article

​# day02——data type, operator

2. Data type conversion

2.1 Automatic type conversion

Dear students, let's learn the knowledge of type conversion next. Why learn type conversion? Because in our actual development, the value of a certain type of variable may be assigned to another type of variable; there may also be cases where data of multiple data types are operated together.

In the above cases, type conversion will actually be involved. The form of type conversion is generally divided into two types, one is automatic type conversion , and the other is mandatory type conversion . Here first learn automatic type conversion

  • What is automatic type conversion?
答:自动类型转换指的是,数据范围小的变量可以直接赋值给数据范围大的变量
	byte a = 12; 
	int b = a; //这里就发生了自动类型转换(把byte类型转换int类型)
  • What is the principle of automatic type conversion?
答:自动类型转换其本质就是在较小数据类型数据前面,补了若干个字节

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Q8Zj7wiJ-1689742236586)(assets/1660837214161.png)]

In addition to the conversion between byte and int, other types can also be converted, and the conversion sequence is shown in the figure below

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-iCH6AolD-1689742236588)(assets/1660837456261.png)]

Let's demonstrate the various forms of automatic type conversion through code.

public class TypeConversionDemo1 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:理解自动类型转换机制。
        byte a = 12;
        int b = a; // 发生了自动类型转换了
        System.out.println(a);
        System.out.println(b);

        int c = 100; // 4
        double d = c;// 8 发生了自动类型转换了
        System.out.println(d);

        char ch = 'a'; // 'a' 97 => 00000000 01100001
        int i = ch; // 发生了自动类型转换了 =>  00000000 00000000  00000000 01100001
        System.out.println(i);
    }
}
  • Automatic Type Conversion of Expressions

There is another form of automatic type conversion, which is the automatic type conversion of expressions. The so-called expression refers to the formula in which several variables or several data participate in the operation together.

If variables or data of different types are operated together in the same expression, what data type is the operation result in this case? The following two operation rules need to be followed:

1.多种数据类型参与运算,其结果以大的数据类型为准
2.byte,short,char 三种类型数据在和其他类型数据运算时,都会转换为int类型再运算

Next, let's look at the code demo and try it yourself

public class TypeConversionDemo2 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握表达式的自动类型转换机制。
        byte a = 10;
        int b = 20;
        long c = 30;
        long rs = a + b + c;
        System.out.println(rs);

        double rs2 = a + b + 1.0;
        System.out.println(rs2);
		
        byte i = 10;
        short j = 30;
        int rs3 = i + j;
        System.out.println(rs3);

        // 面试笔试题: 即使两个byte运算,结果也会提升为int
        byte b1 = 110;
        byte b2 = 80;
        int b3 = b1 + b2;
        System.out.println(b3);
    }
}

2.2 Mandatory type conversion

We learned about automatic type conversion earlier, and we know that data with a small data type can be directly assigned to a variable with a large data range. Conversely, can data with a large data range be directly assigned to variables with a small data range? The answer is that it will report an error.

Because data with a large data range is assigned to a variable with a small data range, it may not be able to hold it; it is like pouring a large bucket of water into a small bucket, and there is a risk of overflow.

  • What is cast

But it is also possible for you to forcibly assign data with a large range to a variable with a small range, and you need to use mandatory type conversion here. The following is the format of the mandatory type conversion

目标数据类型  变量名  =  (目标数据类型)被转换的数据;

The following is a code demonstration of the forced type conversion

public class TypeConversionDemo3 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握强制类型转换。
        int a = 20;
        byte b = (byte) a;  // ALT + ENTER 强制类型转换。
        System.out.println(a);
        System.out.println(b);

        int i = 1500;
        byte j = (byte) i;
        System.out.println(j);

        double d = 99.5;
        int m = (int) d; // 强制类型转换
        System.out.println(m); // 丢掉小数部分,保留整数部分
    }
}
  • The principle of mandatory type conversion

    The principle of mandatory type conversion is to forcibly cut off the first few bytes, but there is a risk of data loss .

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-1JvRKiUv-1689742236590)(assets/1660840481803.png)]

At this point, we are done learning about data types and data type conversion. You can know when automatic type conversion will occur and how to perform mandatory type conversion.

3. Operators

Next, explain to the students a piece of content that is used a lot in development, called operators.

We all know that computers are used to process data, and the calculation of data is indispensable for processing data. Operators must be used to calculate data.

An operator is a symbol that participates in an operation. There are many kinds of operators provided by Java, which can be divided into the following types of arithmetic

  • basic arithmetic operators
  • Increment and decrement operators
  • assignment operator
  • relational operator
  • Logical Operators
  • ternary operator

3.1 Arithmetic operators

Start learning from the most basic arithmetic operators. There are arithmetic operators + - * / % , which *means multiplication, /division, and %remainder

We need to pay attention to the following points

/: 两个整数相除,结果也是一个整数
%: 表示两个数相除,取余数

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-n4Ni3yjt-1689742236591)(assets/1660841349983.png)]

What we need to pay attention to is: +in addition to being used for addition operations, symbols can also be used as connectors. +Symbols and string operations are used as connectors, and the result is still a string .

The following code demonstrates the operation effect of various arithmetic operators

public class OperatorDemo1 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握基本的算术运算符的使用。
        int a = 10;
        int b = 2;
        System.out.println(a + b);
        System.out.println(a - b);
        System.out.println(a * b); // 20
        System.out.println(a / b); // 5
        System.out.println(5 / 2); // 2.5 ==> 2
        System.out.println(5.0 / 2); // 2.5
        int i = 5;
        int j = 2;
        System.out.println(1.0 * i / j); // 2.5

        System.out.println(a % b); // 0
        System.out.println(3 % 2); // 1

        System.out.println("---------------------------------------");

        // 目标2:掌握使用+符号做连接符的情况。
        int a2 = 5;
        System.out.println("abc" + a2); // "abc5"
        System.out.println(a2 + 5); //  10
        System.out.println("itheima" + a2 + 'a'); // "itheima5a"
        System.out.println(a2 + 'a' + "itheima"); // 102itheima
    }
}

3.2 Increment and decrement operators

Next, learn one of the more commonly used operators: ++and--

++Read as self-increment, --read as self-decrement; the operation rules are as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-HHgJdLmg-1689742236593)(assets/1660841701880.png)]

What we need to pay attention to is that auto-increment and auto-decrement can only operate on variables, not literal values. There are two cases of specific use, as follows:

1.单独使用:++或者--放在变量前面没有区别
	   int a =10; 
	    a++;  //11
		--a;  //10
		System.out.println(a); //10

2.混合使用:++或者--放在变量或者前面运算规则稍有不通过
	//++在后:先做其他事情,再做自增和自减
	int a = 10;
	int b = a++; //等价于 int b = a; a++; 

	//++在前:先自增或者自减,再做其他运输
	int x = 10;
	int y = --x; //等价于x--; int y = x;  

The following code demonstrates the usage of ++and--

public class OperatorDemo2 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握自增自减运算符的使用。
        int a = 10;
        // a++; // a = a + 1
        ++a;
        System.out.println(a);

        // a--; // a = a - 1
        --a;
        System.out.println(a);

        // 自增自减只能操作变量不能操作字面量的,会报错!
      	//System.out.println(2++);

        System.out.println("--------------------------------------");

        int i = 10;
        int rs = ++i; // 先加后用
        System.out.println(rs);
        System.out.println(i);

        int j = 10;
        int rs2 = j++; // 先用后加
        System.out.println(rs2);
        System.out.println(j);
    }
}

3.3 Assignment Operators

Next, we learn about assignment operators. The basic assignment operator is actually =a number, which means to assign the data on the right to the variable on the left.

int a = 10; //将数据10赋值给左边的变量a

In addition to the basic assignment operators, we mainly learn about the extended assignment operators here. have+= -= *= /= %=

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-3tEtoRcl-1689742236594)(assets/1660872631676.png)]

Let's +=take a look at its operation rules as an example. Other operators can be analyzed in the same way.

int a = 10;
//+=解析:在a原来记录值10的基础上累加5,将结果重新赋值给a; 
a+=5; 
//最终打印a的值为15
System.out.println(a); 

Let me show you through an example of the first red envelope

public class OperatorDemo3 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握扩展赋值运算符的使用。
        // +=
        // 需求:收红包
        double a = 9.5;
        double b = 520;
        a += b;  // a = (double)(a + b);
        System.out.println(a);

        // -= 需求:发红包
        double i = 600;
        double j = 520;
        i -= j;  // i = (double)(i - j);
        System.out.println(i);

        int m = 10;
        int n = 5;
        // m *= n; // 等价形式: m = (int)(m * n)
        // m /= n; // 等价形式: m = (int)(m / n)
        m %= n;    // 等价形式: m = (int)(m % n)
        System.out.println(m);
    }
}

After learning the basic use of the extended assignment operator, let's look at an interview question

问题1:下面的代码否有问题?
    byte x = 10;
    byte y = 30;
	x = x + y;  //这句代码有问题,因为两个byte类型数据相加,会提升为int类型;
	
问题2:下面的代码是否有问题?
	byte x = 10;
	byte y = 30;
	x+=3; //这句代码没有问题,因为这里有隐含的强制类型转换
		  //x+=3; 等价于 byte x = (byte)(x+y);

The assignment operator is finished here, let’s summarize it a bit

1.基本赋值运算符:
	=符号含义: 把右边的值赋值给左边的变量
	
2.扩展赋值运算符:
	+= -= *= /= %=符号含义:将右边的数据和左边的变量相加、相减、相乘、相除、取余数后,将结果重新赋值给左边的变量。

3.4 Relational Operators

Next, let's learn a very simple operator that is used a lot in actual code, called relational operator. Relational operators (also called comparison operators).

The following figure shows the symbols and functions of each relational operator, and the result of each relational operator is false

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-ENSnhRDP-1689742236596)(assets/1660872844712.png)]

Let's demonstrate the effects of various relational operators through code

public class OperatorDemo4 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握关系运算符的基本使用。
        int a = 10;
        int b = 5;
        boolean rs = a > b;
        System.out.println(rs);

        System.out.println(a >= b); // 要么a大于b,或者a等于b
        System.out.println(2 >= 2); // true
        System.out.println(a < b);
        System.out.println(a <= b); // false
        System.out.println(2 <= 2); // true
        System.out.println(a == b); // false
        System.out.println(5 == 5); // true
        
        // 注意了:判断是否相等一定是用 == ,=是用来赋值的。
        // System.out.println(a = b); 
        System.out.println(a != b); // true
        System.out.println(10 != 10); // false

        System.out.println(false ^ true ^ false);
    }
}

Now we only need to know the operation effect of each relational operator. The actual application of relational operators needs to learn the flow control statement later before it can be actually used.

Relational operators are often used in conditional judgments in programs. According to whether the result of the conditional judgment is true or false, it is determined which operations to perform in the future.

3.5 Logical operators

After learning about relational operators, let's learn about logical operators. Let's take a look at what logical operators are.

Logical operators are used to combine multiple conditions together, and the final result is true or false

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-bDWKWt1G-1689742236597)(assets/1660873470958.png)]

Let's demonstrate the use of logical operators through several cases

//需求1:要求手机必须满足尺寸大于等于6.95,且内存必须大于等于8.
//需求2:要求手机要么满足尺寸大于等于6.95,要么内存必须大于等于8.
public class OperatorDemo5 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握逻辑运算符的使用。
        // 需求:要求手机必须满足尺寸大于等于6.95,且内存必须大于等于8.
        double size = 6.8;
        int storage = 16;
        // 1、& 前后的条件的结果必须都是true ,结果才是true.
        boolean rs = size >= 6.95 & storage >= 8;
        System.out.println(rs);

        // 需求2:要求手机要么满足尺寸大于等于6.95,要么内存必须大于等于8.
        // 2、| 只要多个条件中有一个是true,结果就是true.
        boolean rs2 = size >= 6.95 | storage >= 8;
        System.out.println(rs2);

        // 3、!取反的意思
        System.out.println(!true); // false
        System.out.println(!false); // true
        System.out.println(!(2 > 1)); // false

        // 4、^ 前后条件的结果相同时返回false,不同时返回true.
        System.out.println(true ^ true); // false
        System.out.println(false ^ false); // false
        System.out.println(true ^ false); // true
        System.out.println(false ^ true); // true

        // 5、&& 左边为false,右边不执行。
        int i = 10;
        int j = 20;
        // System.out.println(i > 100 && ++j > 99);
        System.out.println(i > 100 & ++j > 99);
        System.out.println(j);

        // 6、|| 左边是true ,右边就不执行。
        int m = 10;
        int n = 30;
        // System.out.println(m > 3 || ++n > 40);
        System.out.println(m > 3 | ++n > 40);
        System.out.println(n);
    }
}

So far, I have finished learning the rules about logical operators. I will give you an operation expression and you can analyze the result. As for the actual use of logical operators, you need to learn the flow control statements before you can actually use them.

Logical operators are often used in programs to combine several conditional judgments, and determine which operations to perform in the future according to whether the result of the conditional judgment is true or false.

3.6 Ternary Operators

Next, we learn about the last operator today, called the ternary operator.

Let's first understand the format of the ternary operator:

关系表达式?1 :2;

The execution flow of the ternary operation: first calculate the value of the relational expression, if the value of the relational expression is true, return the value 1; if the value of the relational expression is false, then return the value 2;

As shown in the figure below: judge whether the student's grade is >=60, if it is true, the exam is passed; if it is false, the grade is unqualified.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-YIN0BZ0r-1689742236598)(assets/1660875022987.png)]

Next, I will demonstrate it through code, the purpose is to let everyone master the format and execution process of the ternary operator.

public class OperatorDemo6 {
    
    
    public static void main(String[] args) {
    
    
        // 目标:掌握三元运算符的基本使用。
        double score = 58.5;
        String rs = score >= 60 ? "成绩及格" : "成绩不及格";
        System.out.println(rs);

        // 需求2:找出2个整数中的较大值,并输出。
        int a = 99;
        int b = 69;
        int max = a > b ? a : b;
        System.out.println(max);

        // 需求3:找3个整数中的较大值。
        int i = 10;
        int j = 45;
        int k = 34;

        // 找出2个整数中的较大值。
        int temp = i > j ? i : j;
        // 找出temp与k中的较大值。
        int max2 = temp > k ? temp : k;
        System.out.println(max2);
    }
}

3.7 Operation priority

Finally, we will introduce the priority of operators to you. If you want to know the priority of each operator, which ones are counted first and which ones are counted later, you can refer to the following picture

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-abxMcef9-1689742236611)(assets/1660875681298.png)]

From the figure, we find that the && operation has a higher priority than the || operation, so when && and || exist at the same time, the && is calculated first and then the ||;

For example the following code

//这里&&先算 相当于 true || false 结果为true
System.out.println(10 > 3 || 10 > 3 && 10 < 3); // true

Finally, let me tell you that in actual development, we rarely consider the priority of operations, because if you want to calculate some data first, you can actually add it, which is more readable ().

//有括号先算 相当于 true && false 结果为false
System.out.println((10 > 3 || 10 > 3) && 10 < 3); //false

4. Case technology: Obtain the data entered by the user's keyboard

Finally, I will tell you a case technology. This technology is actually a little ahead of the curve because it needs to use the knowledge learned later. But talking here can make our learning experience better. In the previous case, the data involved in the calculation is hard-coded in the program. Next, we want to enter the data with our own keyboard, and then participate in the operation of the program.

The matter of keyboard entry is actually not done by ourselves, but Java itself provides such a function, and we just call it according to its requirements.

When we installed the JDK, in fact, the JDK already contained some code written in Java, we just take the code written in Java and use it directly.

比如:Scanner就是Java提供给我们用于键盘录入数据的类,为了录入不同类型的数据,还提供了不同的功能,每一个功能会有不同的名称,我们只需要调用Scanner提供的功能就可以完成键盘录入数据。

You only need to write the code according to the following steps, and you can enter data by keyboard

【第1步】:在class类上导包:一般不需要我们自己做,idea工具会自动帮助我们 导包的。
	import java.util.Scanner;
	
【第2步】:得到一个用于键盘扫描器对象(照抄代码就行,固定格式)
	//Scanner是键盘扫描器对象(你就把它理解成一个东西),这个东西有录入的功能
	//sc是给这个东西取的名字
	Scanner sc = new Scanner(System.in);

【第3步】:开始调用sc的功能,来接收用户键盘输入的数据。
	//sc这个东西有键盘录入整数的功能,这个功能的名字叫nextInt()
	//.表示表示调用的意思
	int age = sc.nextInt();
	System.out.println("我的年龄是:"+age);

	//sc这个东西还有键盘录入字符串的功能,这个功能的名字叫next
	String name = sc.next();
	System.out.println("我的姓名是:"+name);

The following is a complete code demonstration

public class ScannerDemo1 {
    
    
    public static void main(String[] args) {
    
    
        // 1、导包:一般不需要我们自己做,idea工具会自动帮助我们 导包的。
        // 2、抄写代码:得到一个键盘扫描器对象(东西)
        Scanner sc = new Scanner(System.in);

        // 3、开始 调用sc的功能,来接收用户键盘输入的数据。
        System.out.println("请您输入您的年龄:");
        int age = sc.nextInt(); // 执行到这儿,会开始等待用户输入一个整数,直到用户按了回车键,才会拿到数据。
        System.out.println("您的年龄是:"  + age);

        System.out.println("请您输入您的名字:");
        String name = sc.next(); // 执行到这儿,会开始等待用户输入一个字符串,直到用户按了回车键,才会拿到数据。
        System.out.println(name + "欢迎您进入系统~~");
    }
}

Guess you like

Origin blog.csdn.net/whirlwind526/article/details/131806224