string的null或空值的判断处理笔者在开发过程中,常常碰到过下面这些错误的用法:
1,错误用法一:
if (name == "") {
//do something
}
2,错误用法二:
if (name.equals("")) {
//do something
}
3,错误用法三:
if (!name.equals("")) {
//do something
}
我们来解说一下:
上述错误用法1是初学者最容易犯,也最不容易被发现的错误,因为它们的语法本身没问题,java编译器编译时不报错。但这种条件可能在运行时导致程序出现bug,永远也不会为true,也就是时说,if块里的语句永远也不会被执行。
上述用法二,用法三 的写法,是包括很多java熟手也很容易犯的错误,为什么是错误的呢?也许你会感到纳闷。
对,它们的写法本身没错,但是,少了一个null判断的条件,试想,如果name=null的情况下,会发生什么后果呢?后果是,你的程序将抛出nullpointerexception异常,系统将被挂起,不再提供正常服务。
当然,如果之前已经对name作了null判断的情况例外。
正确的写法应该先加上name != null的条件,如例:
if (name != null && !name.equals("")) {
//do something
}
或者
if (!"".equals(name)) {//将""写在前头,这样,不管name是否为null,都不会出错。
//do something
}
下面,我们举一个简单的例子:
testnullorempty.java
public class test {
public static void main (string args[]){
string value = null;
testnullorempty(value);
value = "";
testnullorempty(value);
value = " ";
testnullorempty(value);
value = "hello me";
testnullorempty(value);
}
static void testnullorempty(string value){
if(value == null){
system.out.println("value is null");
} else if ("".equals(value)){
system.out.println("value is blank but not null");
} else {
system.out.println("value is \"" + value + "\"");
}
if (value == "") { //ng 错误的写法
//别用这种写法
}
}
}
编译执行:
c:\>javac testnullorempty.java
c:\>java testnullorempty
value is null.
value is blank but not null.
value is " "
value is "hello me!"
比较string地址相等
package com;
public class a
{
/**
* @param args
*/
public static void main(string[] args)
{
string a = "hello";
string b = "he";
string c = a.substring(0, 2);
system.out.println(b.equals(c));//true
system.out.println(b==c);//false
string d = new string("hello");
system.out.println(d.equals(a));//true
system.out.println(d==a);//false
string e = new stringbuilder("hello").tostring();
system.out.println(e.equals(a));//true
system.out.println(e==a);//false
system.out.println(e.equals(d));//true
system.out.println(e==d);//false
string f = "hello";
system.out.println(f.equals(a));//true
system.out.println(f==a);//true
system.out.println(f=="hello");//true
system.out.println(f=="hell"+"o");//true
string g = b+"llo";
system.out.println(g==f);//false
string h = "he"+"llo";
system.out.println(h==f);//true
}
}
总结:
1.new出来的string是重新分配内存,字符串不共享,new出来的多个之间也不共享。
2.通过字符串函数操作拼接或者截取到的字符串跟静态字符串变量也是不共享的。
3.通过加号得到的字符串有两种情况。
a "he"+"llo"是静态字符串,是共享的
b string a = "he"; a+"llo"不是静态字符串,是不共享的
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!