Null 与 “” 的区别

说明:很多人有时候对于 null 和 "" 不是很清楚,结合其他人的文章,今天做下解释。

String str1 = null; str引用为空

String str2 = ""; str引用为空串 

说白了就是null没有分配内存空间,而""分配了内存空间,因此str1还不是一个实例化的对象,而str2已经实例化。 

注意因为null不是对象,""是对象。

所以比较的时候必须是

 if(str1==null)
{....}if(str2.equals(""))
{....}

 

 内存地址比较用equals,null用等号比较。 

因此,如果str1=null;

下面的写法错误:
if(str1.equals("")||str1==null)

{

//如果str1没有值,则返回false

}

正确的写法是 :

if(str1==null||str1.equals("")) { //先判断是不是对象,如果是,再判断是不是空字符串 }

 

 

 String name = request.getParameter("name");

  if(filmname==null)

    {
       System.out.println("name ==null");  
  }  
else if (name.equals(""))
  {
   System.out.println("name.equals(\"\")");
  }

 

  控制台输出: name.equals("")

  说明request从表单中<input name="name">标签中获取默认空的值!=null,而是空字符串。

 

//==与EQUEAL得区别如下:

//如下面的代码,运行过后,返回为false; 

public static void main(String[] str)

{

         String a = new String("123");

         String b = new String("123");

         System.out.println(a==b);

   }

 

//这是因为==比较的是两个引用时是不是指向同一个内存地址,而equeals比较的是字面值。上面的new就产生了两个不同的对象,那么其内存地址肯定也就不同了。

 public static void main(String[] str)

{

                   String a = new String("123");

                   String b = new String("123");

                   System.out.println(a.equals(b));

}//返回为true

 

 

posted @ 2014-12-02 19:52  [0]  阅读(345)  评论(0编辑  收藏  举报