Friday, February 26, 2021

Binding variable for instanceof operator

We know that instanceof operator tests a variable for a particular type. This is generally used when we have a variable of a super type and we want to check if its of a specific subtype before casting and invoking specific methods or attributes of that subtype

Here is the sample of instanceof usage

    public int getSizeOfString(Object o) {
        if (o instanceof String) {
            String s = (String) o;
            return s.length();
        } else {
            return 1;
        }
    }

We check if o is of type String. If so, we cast it to String, assign it to the variable s and then proceed to return the length of the string. Otherwise we return 1 as the default size.

Binding variable for instanceof operator introduced in Java 15, makes this casting and assignment to the local variable much more concise and less error prone. 

Below is this code using binding variable with instanceof operator

    public int getSizeOfString(Object o) {
        if (o instanceof String s) {
            return s.length();
        } else {
            return 1;
        }
    }

In the above code, s is the binding variable used with the instanceof operator. If Object o is of type String, it is cast to String and assigned to s as part of the single line statement. We can proceed to use s as a String variable holding the object assigned inside of the if block. 

As you can see, not only does this make the code concise, it also eliminates the possibility for errors due to wrong manual casting.

We will explore more scenarios of using binding variable with instanceof operator in the next few posts. 

A complete sample for binding variable usage

Scoping of binding variables

Binding variable scope with NOT (!) condition

Using binding variable in the expression of if statement


Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/02/Language-Features/Instanceof-Binding-Variable/Usage

No comments:

Post a Comment