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/