Jump to content

It's a keyword, so you can't use it as a name for a variable or function like class or void.

What it does: it's a comparison operator, like ==, !=, < and so on, but it doesn't compare the value of something, but rather the type, so it checks if the type of a variable is some class or interface. So the following two are identical:

String obj = 'A';

System.out.println(obj.getClass().getSimpleName() == 'String');
System.out.println(obj instanceof String);

 

Link to post
Share on other sites

54 minutes ago, Sakuriru said:

They're not though 😞

 

First, Java uses single quotes for char type not String, and second, you can't compare string literals like this in Java, you need to use .equals instead

Got me, I don't actually use Java, only many similar languages. There are also namespaces, so just because the className of an Object is equal to "String" doesn't mean it has to be of type java.lang.string. But I think it still answered the question.

Link to post
Share on other sites

On 6/8/2022 at 1:52 PM, Sakuriru said:

First, Java uses single quotes for char type not String, and second, you can't compare string literals like this in Java, you need to use .equals instead

You can compare strings with == and in a lot of cases it will work.  It's unlikely to in the current example though.  Look up the string internal cache table in Java.

 

String myString = "Hello world";

if( myString == "Hello world" ) {

   // Extremely likely to be true.

}

 

Whatever one is missing is that "instanceof" does NOT, repeat NOT match what class the type is of.  It matches if the variable given can be considered as an instance of X.

 

class Gizmo implements Gadget

...

class Whizzido implements Gadget

...

class FancyDuffer extends Gizmo 

 

( aGiz instance of Gadget )  is True

( aWhiz instance of Gadget ) is True

( aFancy instance of Gadget ) is True

( aGiz instance of Gizmo )  is True

( aWhiz instance of Whizzido ) is True

( aFancy instance of FancyDuffer) is True

 

Note that:

(aFancy instance of Gizmo) is true.  The reasoning is that FancyDuffer extends Gizmo so all of it's public methods are inherited or overridden but cannot be deleted, it can be said to meet the "Is-a" test.  

 

While inheritence is often taught for this purpose (many things that are of one basic type), it is not done that way in the real world and is considered bad practice in many situations.  You should use Interfaces instead as then you are not bound into a heirarchy.  Anything you can do with inheritence, can be achieved with interface composition instead.

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×