Java instanceof operator

Created By: chatGPT

Java provides a powerful operator known as instanceof that is used to test whether an object is an instance of a specific class or interface. This operator is particularly useful in ensuring type safety in inheritance hierarchies. When using instanceof, it allows you to verify whether an object is of a certain type before performing operations that are specific to that type.
class Animal {
    void makeSound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    void makeSound() {
        System.out.println("Bark");
    }
}

public class TestInstanceOf {
    public static void main(String[] args) {
        Animal myDog = new Dog();

        // Using instanceof to check type
        if (myDog instanceof Dog) {
            System.out.println("myDog is an instance of Dog");
        }

        if (myDog instanceof Animal) {
            System.out.println("myDog is also an instance of Animal");
        }

        // Trying with a different type
        // String str = "Hello";
        // if (str instanceof Animal) {
        //     System.out.println("This won’t print");
        // }
    }
}
The instanceof operator returns true or false based on the evaluation. It's a binary operator that evaluates the reference type of the object on its left side against the class or interface on its right side. Keep in mind that if the object is null, instanceof will always return false.
Animal myAnimal = null;

if (myAnimal instanceof Animal) {
    System.out.println("This won't print");
} else {
    System.out.println("myAnimal is null, so instanceof returns false");
}
In the context of a class hierarchy, the instanceof operator allows you to safely cast types in polymorphic scenarios. It's a good practice to use it before performing a type cast, to avoid ClassCastException at runtime.
if (myDog instanceof Dog) {
    Dog dog = (Dog) myDog; // Safe cast
    dog.makeSound();
} else {
    System.out.println("myDog is not a Dog");
}
Introduction And SetupVariablesData TypesIntFloatDoubleCharBooleanStringByteShortLongArrayListMethodVoidReturnParametersArgumentsControl FlowIf StatementElse StatementElse If StatementSwitch StatementCaseBreakContinueFor LoopWhile LoopDo While LoopEnhanced For LoopFunctionsStatic MethodInstance MethodConstructorOverloadingOverridingAccess ModifiersPrivateProtectedPackage PrivateOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsTernary OperatorInstanceof OperatorArrayListSetMapHashmapHashtableQueStackCommentsSingle Line CommentMulti Line CommentSyntaxSemicolonsCurly BracesParenthesesData EncapsulationInheritancePolymorphismAbstract ClassInterfaceException HandlingTry BlockCatch BlockFinally BlockThrowThrowsChecked ExceptionUnchecked ExceptionSyntax ErrorsRuntime ErrorsLogic ErrorsEvent HandlingListenersAction EventsMouse EventsKeyboard EventsWindow EventsFocus EventsKey ListenerMouse ListenerAction ListenerThreadingSynchronizationVolatile KeywordConcurrencyJava Memory Model