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 XIX): The assert Keyword

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.
The assert keyword enables you to test an assumption about a part of your program. If the assertion is proven to be true, execution of your program will continue. If it's proven to be false, an AssertionError will be thrown. Assertions confirm your assumptions about the behavior of your program, thus increasing confidence that the program is free of errors.

This keyword has been part of the Java language since Java 1.4.2 and yet, very little is known about the correct way to use it. The web is full of misinformation and bad examples on how to correctly use it. With regards to usage, it is meant to be used during development and testing. It is not meant to be used in deployed software. For this reason, the architects of the Java language provided a mechanism to turn assertions on and off. More on this later on.

The simple usage form of the assert keyword is as follows

assert booleanExpression;

Suppose you write a function that produces a String that must be between 8 to 15 characters in length. A valid assertion statement for this requirement will be to check the length of the output of this function:


String result = generateString(...);
int length = result.length();
assert length >= 8 && length <= 15;
// the rest of the code
During development or testing phase, you would want to know that, regardless of input to this function, the output will always comply with this string length requirement. If the requirement is met, the code will continue normal execution. If some input causes the assertion to fail, the developer or tester will notice the error. This will allow debugging of the condition that caused the assertion to fail.

The above scenario is often coded using an if/else flow control structure like the one below:


String result = generateString(...);
int length = result.length();
if (length < 8 || length > 15) {
    throw new Exception("Result string not between 8 and 15 characters in length");
}
// the rest of the code
Logically, this if statement accomplishes the same result: it will throw some exception if the requirement is not met. However, there is a major drawback to this approach. The drawback is that you cannot turn it off for deployed software. So, how developers (usually) turn this check off on production code? One approach I have seen (and one I have to shamefully admit I have done in the past) is to create a boolean flag that is set on some property file.

InputStream input = new FileInputStream("path/to/config.properties");
Properties prop = new Properties();
props.load(input);
boolean isDebug = prop.getProperty("debugFlag");

String result = generateString(...);
int length = result.length();
if (isDebug && (length < 8 || length > 15)) {
    throw new Exception("Result string not between 8 and 15 characters in length");
}
// the rest of the code
Do you see how much boilerplate code is generated to skip this check if in production? Can you see the possibility of this property file value to be accidentally checked in to the code repository? In constrast, the Java Virtual Machine (JVM) disables assertions by default and only turns assertions on if the -enableassertions switch, or its short version -ea, is used to execute the code. If you execute your code inside a development environment (like Eclispe), this switch might be set out of the box in the IDE's VM arguments. So, keep that in mind. The second form of the assert keyword is as follows

assert booleanExpression : expression;

where expression is an expression that has a value. Therefore, you cannot invoke a method that returns void. The purpose of this expression (the value after the colon) is to pass it to the AssertionError constructor in order to provide a more meaningful error message. Using the same example as before:

String result = "Hello";
int length = result.length();
assert length >= 8 && length <= 15 : "string length less than 8 or longer than 15";
// the rest of the code
If executed with assertions enabled, the execution will produce the following assertion error: Exception in thread "main" java.lang.AssertionError: string length less than 8 or longer than 15 You could pass primitive values as well as objects as an expression. For example, you could pass an enum to pass the enum name to the assertion error constructor. The link below shows an example of this.

Required reading

My suggestion is that you go to the Oracle Java website, and read about assertions in Java before you use them.

Next up, Part XX: The strictfp 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. ...