Java 与字符串和实例混淆
我对instanceof感到困惑。我的理解是instanceof是检查对象类型。字符串是对象,但在以下程序中它显示不匹配。请给我解释一下Java 与字符串和实例混淆,java,scjp,Java,Scjp,我对instanceof感到困惑。我的理解是instanceof是检查对象类型。字符串是对象,但在以下程序中它显示不匹配。请给我解释一下 public class MyTest { static String s; public static void main(String args[]) { String str = null; if(s instanceof String) { System.
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
设置为实际字符串,则输出将相应更改。
instanceof运算符将对象与指定类型进行比较。您可以使用它来测试对象是类的实例、子类的实例还是实现特定接口的类的实例
检查是否正在创建该类的新实例
String str = new String();
s
和str
为空。它们是虚无缥缈的。Ted Hopp-->非常感谢您的解释。Nambi Narayanan-->非常感谢您。我会像这样尝试的。