我对 instanceof 感到困惑。我的理解是 instanceof 是检查对象类型。字符串是对象,但在下面的程序中显示不匹配。请解释一下。
public class MyTest
{
static String s;
public static void main(String args[])
{
String str = null;
if(s instanceof String)
{
System.out.println("I am true String");
}
else
{
System.out.println("I am false String");
}
if(str instanceof String)
{
System.out.println("I am true String");
}
else
{
System.out.println("I am false String");
}
}
}
The output is
I am false String
I am false String
提前致谢。
最佳答案
instanceof
运算符不测试变量的声明类型;它测试变量引用的对象(如果有)的类。但是,s
和 str
在您的代码中都是 null
并且 null
永远不是任何类的实例。如果您将 s
和/或 str
设置为实际字符串,则输出将相应地更改。
关于java - 与 String 和实例混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22241798/