Skip to main content

Java Keywords (Part XXIV): native

Java keyword list abstract continue for new switch assert default goto * package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const * float native super while Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers. This is the last chapter of the Java Keyword series. This is probably the keyword I have used the least. In my 20 year career as a software developer, I have used this keyword once, and that was to make some addition to legacy code. The keyword native is a method modifier . Basically, it is a keyword that can only be applied to methods. According to the Java Language Specification (JLS), A method that is native is implemented i...

Java Keywords (Part XIV): Using the instanceof Operator

We are up to 38 keywords covered in previous articles! That's 79% keywords covered. We have only 10 keywords to cover and I will be covering 1 of those in this article. We are almost done with all the basic keywords. This article will illustrate the use of the keyword instanceof. I suggest you start with Java Keywords (Part I) before proceeding further, if you have not read any of the previous articles in the Java Keyword series. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page. The series was written with natural progression in mind. Therefore, some of the keywords already covered may be used in code examples illustrated here.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

What is the instanceof operator?

This operator performs a comparison operation of an object against a "Type" to determine if a particular object is of that type. As expected, the result of the comparison is a Boolean value. For example:

boolean result = obj instanceof MyClass;
If the variable obj is an instance of the class MyClass, the above snippet will return true. Otherwise, it will return false. Simple enough, right?

Drawbacks of instanceof Operator

This operator returns true if the object being evaluated is an instance of the class to the right of the operator or of any class in the hierarchy chain. Consider this example:

public class Shape {...}

public class Polygon extends Shape {...}

public class Square extends Polygon {...}
If an object of type Square is evaluated using instanceof...
  
public static void main (String[] args) {
	Polygon square = new Square();

	if (square instanceof Shape) {
		System.out.println("I'm a shape"); // This will print out...
	}
		
	if (square instanceof Polygon) {
		System.out.println("I'm a polygon"); // and this...
	}
	
	if (square instanceof Square) {
		System.out.println("I'm a square"); // also this...
	}
	
	if (square.getClass().isAssignableFrom(Polygon.class)) {
		System.out.println("I am assignable from Polygon"); // This won't...
	} else {
		System.out.println("I'm a polygon; just not assignable from it."); // but this will.
	}
}
It will return true for comparisons against Shape, Polygon, and Square, even though the object is not a direct instance of that class.

OUTPUT:

I'm a shape
I'm a polygon
I'm a square
I'm a polygon; just not assignable from it.
For these reasons, you should prefer using over instanceof. That said, as long as you understand the expected behavior of this operation, you should be fine using it. I hope I did a good enough job explaining the ins and outs of it for you to make a good decision when it comes time to use it. If not, let me know in the comments below.

New way for using instanceof operator

Since Java 14 and according to Oracle,
Pattern matching involves testing whether an object has a particular structure, then extracting data from that object if there's a match.
This was already part of Java. For instance, you could evaluate an object to determine whether or not the object is an instance of a particular class, then use typecasting to "convert" the object into an instance of the class it was evaluated against. However, it is simpler to do now. Before, you could do something like this:

if (obj instanceof Square) {
	Square s = (Square) obj; // This is called "typecasting"
    s.someMethodOfSquare();
    ...
}
Now, you can simply do something like this:

if (obj instanceof Square s) {
    s.someMethodOfSquare();
    ...
}
This new way of using instanceof is known as Pattern Matching.

Next up, Part XV: The many uses of the this keyword

Comments

Popular posts from this blog

Implementing Interfaces with Java Records

If you have not read my article on Java records and do not know about this topic, please read my blog titled " Customizing Java Records " first and then come back to this one. Now that you know how to customize Java records, implementing an interface using Java records should be very easy to understand. If you don't know about interfaces in Java, you can read more on my article about interfaces. The recipe for implementing an interface is simply an expansion of what you learned in my previous blog on how to customize a Java record. Following our Rectangle example, let's create an interface with the same two methods we used before. public interface Shape { double area(); double perimeter(); } Now, let's further customize the previous example by doing two things: Add implements Shape at the end of the record declaration (after the record constructor), and Add @Override to the existing methods to ensure these methods com...

Customizing Java Records

If you have not read my article on Java records and do not know about this topic, please read my blog titled " Java Keywords Addendum: The Java Record " first and then come back to this one. What is a customization of a record? A customization of a record is simply the addition of code inside the body of the class. Before proceeding further, let's recap important aspects of a Java Record: Java records are immutable Because of item 1 above, you cannot add new fields unless defined in the record constructor Java records already override: Object#equals(Object) and Object#hashCode() , and then override Object#toString() You could redefine overridden methods as part of your customization if you would like. For example, if you want a fancier implementation of the Object#toString() method, you could do so. Let's look at our first customization example. Using the example from my previous blog, public record Student(...

Object-Oriented Programming Basics: What is in a Class?

EDITORIAL NOTE : This article was published briefly back in 2016 and quickly set back to draft because I wasn't happy with its contents. It is a shame that it was taking me three years to revisit this topic and work on a new and improved version. At least, I'm hoping it will be to the liking you the reader. Keep in mind that the opening paragraph will still read as if I just wrote it for my (former) students at Texas Wesleyan. I started working on lecture on the topic of Object-Oriented (OO) Programming by gathering some material, old and new, when I realized this might be good and simple post for my second attempt at blogging. To be completely honest, in the 8 hours I spent collecting information and preparing material for this week's lecture, I realized I still made some of the mistakes I am about to blog about. I am actually hoping I can write a series of postings regarding Object-Oriented Programming (OOP). But to do so, I must start from the very beginning. ...