一、字符串类型:String
String类型变量的使用
- String属于引用数据类型,翻译为字符串
- 声明String类型变量时,使用一对""
class StringTest{
public static void main(String[] args){
String s1 = "Hello World!";
System.out.println(s1);
String s2 = "a";
String s3 = ""; // " "内放多少都字符都可以
char c = ‘ ’; //但定义char型变量,引号内无东西不通过
}
}
- String可以和八中基本数据类型变量做运算,且运算只能连接运算
- 运算结果仍然是String类型
class StringTest{
public static void main(String[] args){
int number = 1001;
String numberStr = "学号:";
String info = numberStr + number; // 连接运算
boolean b1 = true;
String info1 = info + b1;
System.out.println(info1); //info1仍然是String类型
//如何判段是相加还是连接运算(只要前面出现String后面的+都为连接)
char c = ' a';
int num = 10;
String str = "hello";
System.out.println(c + num + str); //107hello
System.out.println(c + str + num); //ahello10
System.out.println(c +( str + num)); //a10hello
System.out.println((c + num) + str); //107hello
System.out.println( str + num +c ); //hello10a
}
}
二、运算符
- 算术运算符
注:取余运算结果的符号与被余数相同
- 赋值运算符
//开发中,实现变量+2的操作方法:
int num = 10 ;
num = num + 2;//方法一
num += 2; //方法二(推荐)
short s1 = 10;
s1 = s1 + 2; //编译失败
s1 += 2 ;// 不会改变变量本身的数据类型
- 比较运算符(关系运算符)
- 逻辑运算符
- 位运算符
- 三元运算符
- 条件表达式的结果为boolean类型
- 表达式一和表达式二统一会一个类型
class SanYunTest{
public static void main(String[] args){
//获取两个数中较大值
int m = 12;
int n = 5;
int max = (m > n)? m:n;
System.out.println( max );
}
}
- 如果既可以使用三元运算符又可以使用if-else语句,优先使用三元运算符