目录
java中类似C++中auto的关键字是:var
if判断
判断引用类型相等
在Java中,判断值类型的变量是否相等,可以使用==
运算符。但是,判断引用类型的变量是否相等,==
表示“引用是否相等”,或者说,是否指向同一个对象。例如,下面的两个String类型,它们的内容是相同的,但是,分别指向不同的对象,用==
判断,结果为false
:
public class fack {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO".toLowerCase();
System.out.println(s1);
System.out.println(s2);
if (s1 == s2) {
System.out.println("s1 == s2");
} else {
System.out.println("s1 != s2");
}
}
}
要判断引用类型的变量内容是否相等,必须使用equals()
方法:
执行语句s1.equals(s2)
时,如果变量s1
为null
,会报NullPointerException
public class fack {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO".toLowerCase();
System.out.println(s1);
System.out.println(s2);
if (s1.equals(s2)) {
System.out.println("s1 equals s2");
} else {
System.out.println("s1 not equals s2");
}
}
}
要避免NullPointerException
错误,可以利用短路运算符&&
public class fack
{
public static void main(String[] args) {
String s1 = null;
if (s1 != null && s1.equals("hello")) {
System.out.println("hello");
}
}
}
switch语句
不要忘记break和defaul,但是使用类似模式匹配(Pattern Matching)的方法,保证只有一种路径会被执行,并且不需要break
语句
public class Fack {
public static void main(String[] args) {
String fruit = "apple";
switch (fruit) {
case "apple" -> System.out.println("Selected apple");
case "pear" -> System.out.println("Selected pear");
case "mango" -> {
System.out.println("Selected mango");
System.out.println("Good choice!");
}
default -> System.out.println("No fruit selected");
}
}
}
当需要返回值的时候可以这么写,用yield
返回一个值作为switch
语句的返回值;
public class fack
{
public static void main(String[] args) {
String fruit = "orange";
int opt = switch (fruit) {
case "apple" -> 1;
case "pear", "mango" -> 2;
default -> {
int code = fruit.hashCode();//返回的是“orange”的哈希码
yield code; // switch语句返回值
}
};
System.out.println("opt = " + opt);
}
}