Java中的isEmpty方法、null以及""的區別


public class TestNull {
 
    public static void main(String[] args) {
        String a = new String();
        String b = "";
        String c = null;
        if (a.isEmpty()) {
            System.out.println("String a = new String");
        }
 
        if (b.isEmpty()) {
            System.out.println("String b = \"\"");
        }
 
        if (c == null) {
            System.out.println("String c =null");
        }
 
        if (null == a) {
            System.out.println("String a =null");
        }
 
        if (a == "") {
            System.out.println("a = ''");
        }
    }
}

控制台輸出:

 

分析:

此時a是分配了內存空間,但值為空,是絕對的空,是一種有值(值存在為空而已)。

此時b是分配了內存空間,值為空字符串,是相對的空,是一種有值(值存在為空字串)。

此時c是未分配內存空間,無值,是一種無值(值不存在)。

 

綜上所述:

isEmpty() 分配了內存空間,值為空,是絕對的空,是一種有值(值 = 空)
"" 分配了內存空間,值為空字符串,是相對的空,是一種有值(值 = 空字串)
null 是未分配內存空間,無值,是一種無值(值不存在)

 

例子二: 

	public static void main(String[] args) {
		String a = new String();
		String b = "";
		String c = null;
		if (a.isEmpty()) {
			System.out.println("String a is empty");
		}
		if (b.isEmpty()) {
			System.out.println("String b is empty");
		}
		if (c == null) {
			System.out.println("String c = null");
		}
		if (null == a) {
			// 編譯器直接就提示了Dead code,a指向了一個新對象,肯定不是null了
			System.out.println("String a =null");
		}
		if (a == "") {
			System.out.println("a = ''");
		}
		if (a.equals("")) {
			//由於a是字符串,字符串的比較需要用equals,不能直接用 ==
			System.out.println("a = ''");
		}
		/*if (c.isEmpty()) {
			// 這里會報空指針,即null不能使用此方法
			System.out.println("c == null   and   c.isEmpty");
		}*/
		
		List<String> list = new ArrayList<>();
		//list.add("");
		if (list.isEmpty()) {
			System.out.println("list is empty");
		}
		System.out.println(list.size());
	}
/*Output:
String a is empty
String b is empty
String c = null
equals:a = ''
list is empty
0
*/

end
原文鏈接:https://blog.csdn.net/peng86788/article/details/80885814


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM