java - Java字符串的默认值: null vs ""

标签 java string

Java 字符串的默认值为“null”。但是,当我实例化该字符串时,它似乎是一个空字符串。有人可以解释一下吗?

class Stuff
{
    String a;
    String b = new String();
}

class Demo
{
    public static void main( String[] args )
    {
       Stuff s = new Stuff();
       System.out.println( s.a );
       System.out.println( s.b );

       if( s.b.equals( "" ) )
       {
            System.out.println( "true" );
       }
    }
}

最佳答案

String()构造函数 Javaodc 说,

Initializes a newly created String object so that it represents an empty character sequence. Note that use of this constructor is unnecessary since Strings are immutable.

这与您观察到的行为相符。

关于java - Java字符串的默认值: null vs "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294700/

相关文章:

Java:尝试运行字符串函数时出现字符串索引越界错误

php - PHP中的字符串是字符数组吗?

java - HikariCP 准备语句空指针异常

java.lang.ClassNotFoundException : org. apache.juli.logging.LogFactory

java - 如何在 Java 8 Stream Filter 中基于子文档过滤 Mongo 文档

java - 字符串比较没有返回正确的答案

php - 正则表达式在字符上拆分字符串,内部字符串除外

sql - T-SQL 如何将逗号分隔的数字字符串转换为整数

java - 移动带有自定义标题栏的 JFrame

java - 将 HttpServletResponse 转换为 json