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 XXIII): transient

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.

Before getting on how to use transient, you must understand why you need to use it. And for that, you must understand the concept of serialization in Java. Serialization is simply the mechanism provided by the language to turn an instance of an object into a byte stream, so that it can be sent over the wire. Remember, objects encapsulate data. So serialization is basically creating a byte array to transmit the object's data. But this is not all. With serialization, the recipient of the serialized object will be able to recreate the serialized object on the other side. This is known as Deserialization.

What's involved in Serialization?

To serialize an object, you must first tag the class as "serializable" by implementing the Serializable interface. If you examine this interface, you will notice that the interface does not contain any methods or any declared constants inside of it. This it is what is referred to as a marker interface. It's sole purpose is to tell the JVM that objects of this type can be serialized. In Java, for example, the class String is serializable.

According to the Serializable interface documentation, classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:


private void writeObject(java.io.ObjectOutputStream out) throws IOException

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

private void readObjectNoData() throws ObjectStreamException;
So, following these guidelines, the following is a simple example of making a "serializable" class:

public class Person implements Serializable {

    private String name; // Objects must be serializable as well (String class is serializable)
    private int age;
    private int id;
    
    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        // Some code here
    }

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        // Some code here
    }

    private void readObjectNoData() throws ObjectStreamException {
        // Some code here
    }
    
    // Constructor and other methods omitted
}
Serialization is a bit of a complex topic. Learn more by reading the links I provided above. For now, I hope you have a very basic understanding of what the serialization process is. The only remaining question is, what does any of this has to do with the keyword transient?

Using the keyword transient

The sole purpose of this keyword is to mark the fields we DO NOT wish to send over in the byte stream when the object is serialized. You may be asking yourself, "why do I want to do that?" "What is the point?" Suppose the id variable in the code example above contains an automatically generated value from a database. In this case, it might not be desirable to send over the value in the byte stream. Or perhaps you do not want the recipient of the data to see certain values for privacy reasons. This is where the keyword is used. Tagging a field with the keyword transient excludes those fields when the byte stream is created.

public class Person implements Serializable {

    private String name; // Objects must be serializable as well (String class is serializable)
    private int age;
    private transient int id; // This value will not be sent in the byte stream
    
    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        // Some code here
    }

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        // Some code here
    }

    private void readObjectNoData() throws ObjectStreamException {
        // Some code here
    }
    
    // Constructor and other methods omitted
}
And, that is it for this keyword. I hope you found this information useful. See you next time! Next up, Part XXIV: native

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. ...