1.5, JAVA First knowledge of JAVA operators

1 operator

1.1 Overview

Operators are used 连接 表达式for 操作数and perform operations on operands.
For example, the expression num1+num2, its operands are num1 and num2, and the operator is "+".
In the Java language, operators can be divided into five types:
算术运算符、赋值运算符、关系运算符、逻辑运算符、位运算符。
according to the different operands, operators are divided into 单目运算符, 双目运算符and 三目运算符.
Unary operators have only one operand, binary operators have two operands, and ternary operators have three operands.
Bitwise operators involve operations on binary bits, and are not widely used in java programs.

1.2 Operator Cheat Sheet

insert image description here

Operations of basic data types and String

Concept:
String type: String
String is not a basic data type, but a reference data type
Use a pair of "" to represent a string, which can contain 0, 1 or more characters.
The declaration method is similar to that of primitive data types. For example: String str = "Chuangyan Education";

运算规则 1、任意八种基本数据类型的数据与 String 类型只能进行连接“+”运算,且结果 一定也是 String 类型

运算规则 1、任意八种基本数据类型的数据与 String 类型只能进行连接“+”运算,且结果
一定也是 String 类型
System.out.println("" + 1 + 2);//12
int num = 10;
boolean b1 = true;
String s1 = "abc";
String s2 = s1 + num + b1;
System.out.println(s2);//abc10true
//String s3 = num + b1 + s1;//编译不通过,因为 int 类型不能与 boolean 运算
String s4 = num + (b1 + s1);//编译通过
2String 类型不能通过强制类型()转换,转为其他的类型
String str = "123";
int num = (int)str;//错误的
int num = Integer.parseInt(str);//正确的,后面才能讲到,借助包装类的方法才能转

Example 2: Two usages of "+" sign

The first type: if both sides of + are numbers, + means addition.
The second type: if at least one of the sides of + is a string, + means splicing

public class ArithmeticTest2 {
    
    
public static void main(String[] args) {
    
    
// 字符串类型的变量基本使用
// 数据类型 变量名称 = 数据值;
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
} 
}

2. The String type cannot be converted to other types through mandatory type () conversion

String str = "123";
int num = (int)str;//错误的
int num = Integer.parseInt(str);//正确的,后面才能讲到,借助包装类的方法才能转

1.3 Exercise: Test increment and decrement

Create package: cn.tedu.basic
Create class: TestOperator.java

package cn.tedu.basic;
/**本类用于测试取余运算符*/
public class TestOperator {
    
    
	//0.创建程序的入口函数main
	public static void main(String[] args) {
    
    
		//1.测试除法与取余数
		System.out.println(25 / 10);//2
		System.out.println(25 % 10);//5
		
         /**
         * 在使用%运算符的时候如果被除数小于除数。
         * 那么,打印的结果就是被除数
         * */
        System.out.println(2%3);
        System.out.println(5%6);

     /*
     * 在除数中如果,被除数小于除数。那么,打印的结果是0
     * */
        System.out.println(5/6);

		//2.练习1:获取一个两位数59的十位与个位
		int x = 59;
		System.out.println(x/10);//打印十位,5
		System.out.println(x%10);//打印个位,9
		
		//3.练习2:获取一个三位数159的百位、十位与个位
		int y = 159;
		System.out.println(y / 100);//打印百位
		System.out.println(y / 10 % 10);//打印十位
		System.out.println(y % 10);//打印个位
		
		//4.测试自增自减运算符
		/** 前缀式:符号在前:++a --a ,先改变变量本身的值,再使用,比如打印
		 *  后缀式:符号在后:   a++ a--,先使用,再改变变量本身的值
		 *  ++: 相当于给变量本身的值+1
		 *  --: 相当于给变量本身的值-1
		 * */
		System.out.println("我是一个无情的分界线");
		
		
		int a = 1;
		System.out.println(++a);//2
		System.out.println(a);//2
		
		int b = 1;
		System.out.println(b++);//1
		System.out.println(b);//2
		
		int c = 1;
		System.out.println(--c);//0,符号在前,先自减,再打印
		System.out.println(c);//0,上面已经自减过了
		
		int d = 1;
		System.out.println(d--);//1,符号在后,先打印,再自减
		System.out.println(d);//0,打印过后,自减成0
		
		//之前的代码会对后面的代码产生影响,c的值是0
		System.out.println(c);//0
		System.out.println(--c-c-c--);//1,-1-(-1)-(-1)=1
		System.out.println(c);//-2,经历了两次自减,所以0-2=-2
		
	}
}

+= -= *= /= %= usage of

//举例说明+= -= *= /= %= 
int m1 = 10;
m1 += 5; //类似于 m1 = m1 + 5 的操作,但不等同于。
System.out.println(m1);//15

//练习 1:开发中,如何实现一个变量+2 的操作呢?
// += 的操作不会改变变量本身的数据类型。其他拓展的运算符也如此。
//写法 1:推荐
short s1 = 10;
s1 += 2; //编译通过,因为在得到 int 类型的结果后,JVM 自动完成一步
强制类型转换,将 int 类型强转成 short
System.out.println(s1);//12
//写法 2:
short s2 = 10;
//s2 = s2 + 2;//编译报错,因为将 int 类型的结果赋值给 short 类型的
变量 s 时,可能损失精度
s2 = (short)(s2 + 2);
System.out.println(s2);

两种方式的区别:

s = s+2; //① 编译报错
s += 2; //② 正常执行
//①和②有什么区别?

s = s + 2和s += 2的作用都是增加2。
      不过使用起来还是有区别的,如果s是int类型,这两者效果完全相同,但如果s是byteshort类型,第一种编译则会报错,因为byte类型或short类型的s和int类型的2相加,其结果是需要int类型来接收,所以byte s = s + 2或者short s = s + 2是不符合规则的,而第二种则不会报错,因为+=不会改变本身变量的数据类型。

关系运算符

比较运算符的结果都是 boolean 型,也就是要么是 true,要么是 false。 
    • > < >= <= :只适用于基本数据类型(除 boolean 类型之外)
      == != :适用于基本数据类型和引用数据类型
    • 比较运算符“==”不能误写成“=

逻辑运算符

&&&:表示"且"关系,当符号左右两边布尔值都是 true 时,结果才能为 true。否则,为 false。 
– ||| :表示"或"关系,当符号两边布尔值有一边为 true 时,结果为true。当两边都为 false 时,结果为 false! :表示"非"关系,当变量布尔值为 true 时,结果为 false。当变量布尔值为 false 时,结果为 true。 – ^ :当符号左右两边布尔值不同时,结果为 true。当两边布尔值相同时,结果为 false

Differentiate between "&" and "&&":
– The same point: if the left side of the symbol is true, both perform the operation on the right side of the symbol
– Difference: &: if the left side of the symbol is false, continue to perform the operation on the right side of the symbol
&&: if the left side of the symbol is false, do not continue Perform the operation on the right side of the symbol
– Suggestion: In development, it is recommended to use &&

==Distinguish between "|" and "||": ==
- the same point: if the left side of the symbol is false, both perform the operation on the right side of the symbol
- difference: | : if the left side of the symbol is true, continue to execute the right side of the symbol The operation of
|| : If the left side of the symbol is true, the operation on the right side of the symbol will not continue to be performed
—suggestion: in development, it is recommended to use ||

1.4 Exercise: Testing Logical Operators

Create package: cn.tedu.basic
Create class: TestOperator2.java

package cn.tedu.basic;
/**本类用于测试逻辑运算符*/
public class TestOperator2 {
    
    
	public static void main(String[] args) {
    
    
		/**与:全真才真*/
		System.out.println("测试单与:");
		System.out.println(true & true);
		System.out.println(true & false);
		System.out.println(false & true);
		System.out.println(false & false);
		System.out.println("测试双与:");
		System.out.println(true && true);
		System.out.println(true && false);
		System.out.println(false && true);
		System.out.println(false && false);
		/**或:全假才假*/
		System.out.println("测试单或:");
		System.out.println(true | true);
		System.out.println(true | false);
		System.out.println(false | true);
		System.out.println(false | false);
		System.out.println("测试双或:");
		System.out.println(true || true);
		System.out.println(true || false);
		System.out.println(false || true);
		System.out.println(false || false);
	}
}

bitwise operator

Shift left: <<
Operation rule: Within a certain range, every bit of data shifted to the left is equivalent to original data*2. (both positive and negative numbers are applicable)

3<<4 is like 3 2 to the power of 4 => 3 16 => 48Please add a picture description

-3<<4 is like -3 2 to the power of 4 => -3 16 => -48

Please add a picture description

(2) Shift right: >>

Operation rule: within a certain range, every time the data is moved to the right, it is equivalent to the original data/2. (Both positive and
negative numbers are applicable)
[Note] If it cannot be divisible, round down.

69>>4 is similar to 69/2 4 times = 69/16 =4
Please add a picture description

-69>>4 is like -69/2 4 times = -69/16 = -5

Please add a picture description

(3) Unsigned right shift: >>>
Operation rules: After shifting to the right, the vacant bits on the left are directly filled with 0. (both positive and negative numbers are applicable)
69>>>4 is similar to 69/2 4 times = 69/16 =4

Please add a picture description

-69>>>4 Result: 268435451Please add a picture description

Ternary operator

Conditional operator format:
(条件表达式)? 表达式 1:表达式 2
Description: The conditional expression is the result of boolean type, select expression 1 or expression 2 according to the value of boolean

Please add a picture description

1.5 Exercise: find the maximum value of two numbers

Create package: cn.tedu.basic
Create class: TestMaxNum.java

package cn.tedu.basic;

import java.util.Scanner;

/**需求:接收用户输入的两个整数,并比较输出这两个数的最大值*/
public class TestMaxNum {
    
    
	public static void main(String[] args) {
    
    
		//1.提示用户输入
		System.out.println("请输入您要比较的第一个整数:");
		//2.接收用户输入的整数,并把这个值交给变量a来保存
		int a = new Scanner(System.in).nextInt();
		System.out.println("请输入您要比较的第二个整数:");
		int b = new Scanner(System.in).nextInt();
		
		//3.比较接收两个数,使用三元运算符
		/**1 ? 2 : 3
		 * 1是表达式,若1的结果为true,结果取2位置,若1的结果为false,结果取3位置
		 * */
		//4.定义变量max来保存比较的最大值
		int max = a > b ? a : b;
		
		//5.打印最大值
		System.out.println("两个数的最大值是:"+max);	
		/**思考题:如何判断3个数的最大值? int max = a>b?(a>c?a:c):(b>c?b:c);*/
	}
}

1.6 Exercise: Finding leap years in average years

Create package: cn.tedu.basic
Create class: TestYear.java

//需求:接收用户输入的年份,判断是平年还是闰年
package cn.tedu.basic;

import java.util.Scanner;

/**
 * 需求:接收用户输入的年份,判断是平年还是闰年
 * 如果年份是闰年,需要满足下面两个条件之一:
 * 条件1:能被4整除,并且不能被100整除
 * 条件2:能被400整除
 * */
public class Test3_Year {
    
    
	public static void main(String[] args) {
    
    
		//1.提示并接收用户输入的年份
		System.out.println("请输入您要判断的年份:");
		int year = new Scanner(System.in).nextInt();
		
		//2.定义一个变量用来保存结果
		String result = "平年";//默认值是平年,假设每年都是平年
		
		//3.判断用户输入的年份是否满足闰年的条件
		/**解决方案1*/
		/**条件1:能被4整除,并且不能被100整除*/
//		if(year % 4 == 0) {//能被4整除
//			if(year %100 != 0) {//不能被100整除
//				result = "闰年";//符合闰年的条件1,修改结果为闰年
//			}
//		}
//		/**条件2:能被400整除*/
//		if(year % 400 == 0) {//能被400整除
//			result = "闰年";//符合闰年的条件2,修改结果为闰年
//		}
		/**解决方案2*/
		/**判断结构 if(判断条件){满足判断条件以后执行的代码} */
		//if(条件1  || 条件2){是闰年 }
		//if((小条件1  && 小条件2) || 条件2){ 是闰年 }
		//if((能被4整除  && 不能被100整除) || 能被400整除){ 是闰年 }
		if((year % 4 == 0 && year %100 != 0) || year % 400 == 0){
    
    
			result = "闰年";//符合闰年的条件,修改结果为闰年
		}
		System.out.println(year+"年是"+result);
	}
	
}

2 Expansion Supplements:

2.1 Summary 1: The self-increment and self-decrement operators of arithmetic operators
a is the operand, ++ is the self-increment operator, - - is the self-decrement operator, and the self-increment and self-decrement operators can be placed in front of the variable. It can also be placed behind the variable, for example: a++, ++a, a- -, - -a, etc.
Auto-increment (++): Add 1 to the value of the variable
with a prefix (such as ++a) and a suffix (such as a++). The prefix type is to add 1 before use; the suffix type is to use and then add 1.
Self-decrement (- -): Decrease the value of the variable by 1.
Prefix type (such as - -a) and suffix type (such as a- -). The prefix type is to subtract 1 before using it; the suffix type is to use it first and then subtract 1.

2.2 Summary 2: Logical operators
Logical operators connect two relational expressions or Boolean variables to solve the combination judgment problem of multiple relational expressions
Note that the operation results returned by logical operators are of Boolean type
. Usually, we use 0 to represent false , use 1 to represent true
and: to represent the relationship
& single and: 1 & 2, the result wants to be true, and both 1 and 2 must be true
&& double and (short-circuit and): 1 && 2, when 1 is false, 2 will be short-circuited to improve the efficiency of the program
Or: Indicates the relationship of OR|
Single OR: 1 | 2, the result wants to be true, and only one of 1 and 2 is required to be true
||Double OR (short-circuit or): 1| | 2, when 1 is true, 2 will be short-circuited to improve program efficiency

2.3 Summary 3: Priority control
When an expression contains multiple operators, it is necessary to consider the priority of the operators. Operators with higher priority participate in the operation first, and operators with lower priority participate in the operation later. In actual development, you don’t need to memorize the priority of operators, and don’t deliberately use the priority of operators. Use parentheses to assist in priority management where the priority is unclear.

priority Operator description Java operators
1 brackets ()、[]、{}
2 sign +、-
3 unit operator ++、–、~、!
4 multiplication, division, remainder *、/、%
5 addition, subtraction +、-
6 shift operator <<、>>、>>>
7 relational operator <、<=、>=、>、instanceof
8 Equivalence operator ==、!=
9 bitwise AND &
10 bitwise XOR ^
11 bitwise or /
12 Conditions and &&
13 condition or //
14 ternary operator ? :
15 assignment operator <、<=、>=、>、instanceof
16 bitwise assignment operator &=、/=、<<=、>>=、>>>=
  1. Do not rely too much on the priority of operations to control the execution order of expressions, as this is
    too readable, try to use () to control the execution order of expressions.
  2. Don't make an expression too complicated. If an expression is too complicated, divide
    it into several steps to complete. For example: (num1 + num2) * 2 > num3 &&
    num2 > num3 ? num3 : num1 + num2;

Guess you like

Origin blog.csdn.net/weixin_58276266/article/details/131459991