check the instance of static String variable
Hi Guyz,
A small doubt.
class Sample
{
static String s;
publicstaticvoid main(String[] args)
{
System.out.println(sinstanceof Object);
}
}
I expected the output of the above program to be 'true'.But it just printed the opposite.
If i give any value to this string object s, it is printing 'true'.
Want to get an explanation.
Thanks in Advance,
Regards,
Pradhip.
[770 byte] By [
Pradhipa] at [2007-11-27 0:49:19]

Hi, Without setting a value, s is null so it's not an instance.Jack
Then what is s?
class Sample
{
static String s;
public static void main(String[] args)
{
make(s);
}
public static void make(String s)
{
System.out.println("Hello String");
}
public static void make(Object s)
{
System.out.println("Hello Object");
}
}
This will print 'Hello String'.
instanceof used with null will always return false.
> Then what is s?
s is a static reference of referential type String. Nothing else.
> This will print 'Hello String'.
Yes. Because it will pick the method with the most specific argument type that's still suitable for the reference given. Since you can put null into a String reference and String is more specific than Object, the String method is called.
This has nothing to do with instanceof.
--> Since you can put null into a String reference and String is more specific than Object, the String method is called.
I can't understand the difference between 'null' in the String reference used in the method and the 'null' used with the instanceof.
Basically its a string reference, where it is accepted as one and it is printing 'Hello String' , why can't it be accepted with instanceof.
Method overloading, u declare s as a string, so it will call the method with the parameter of string, if u declare object it will call parameter of object
> --> Since you can put null into a String reference
> and String is more specific than Object, the String
> method is called.
>
> I can't understand the difference between 'null' in
> the String reference used in the method and the
> 'null' used with the instanceof.
>
> Basically its a string reference, where it is
> accepted as one and it is printing 'Hello String' ,
> why can't it be accepted with instanceof.
because instanceof checks is something is an instance of some type, at runtime- it deals with objects themselves, not the references to objects. since 'null' - by definition - isn't an instance of anything, it's the absence of an instance, instanceof evaluates to false. methods, however, deal with references to objects, regardless of whether they point to anything or not. a null reference is still a valid reference, but null is not a valid instance, by definition
think about the terms being used for a second: how can 'null' be an instance of anything? there's nothing there
