Wed, Jul
0 New Articles

Advanced Integrated RPG: Using Java with RPG

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Create a Java "Hello World" program with RPG.


Editor's note: This article is excerpted from the MC Press book Advanced Integrated RPG.


Welcome to Advanced Integrated RPG (AIR), where RPG and Java work together to provide RPG with all of the capabilities that Java has to offer. This article contains excerpts from my new book that will show you how to start the Java Virtual Machine (JVM) and display "Hello World" in RPG. This is a prerequisite to the upcoming article that will show you how to create PDFs from RPG!

Accessing Java Objects from Within RPG

To create reference variables within RPG for Java objects, you specify the variable as type O (Object) in column 40 of the D specification. Then, use the CLASS keyword to indicate the Java object being referred, entering *JAVA as the first parameter and specifying the Java class as a character string for the second parameter. This character string must fully qualify the object and the Java package that contains it.


Let's begin by creating a reference to a Java String object. The String object is a common object included in the JDK. It is contained in the java.lang package, so the character string to identify the class must be in the Java format of 'java.lang.String'. It's important to note that the reference to the class is case-sensitive.


Figure 5.2 shows the code to declare an RPG variable that refers to a Java String object.


D string          S               O   CLASS(*JAVA:'java.lang.String')

Figure 5.2: RPG object variable for reference to Java String object

Java Object Constructors

The variable declared as an object type is only a reference. In order to use the string object, we first need to create an instance of the object. We do this by using the constructor method of the class. When the object is constructed, the reference variable will identify the location of the memory allocated to the object.


We call the constructor method of the class by specifying the special keyword *CONSTRUCTOR as the method name in EXTPROC. In the Java language, you construct objects by using the new keyword, so we'll name the procedure new_String, using an underscore to represent the separation of the keyword new from the class name that you would code in Java.


Figure 5.4 shows the prototype for the constructor method of the String class.


D new_String      PR                  like(jstring)

D                                     extproc(*JAVA:

D                                     'java.lang.String':

D                                     *CONSTRUCTOR)

D argBytes                   65535A   varying const

Figure 5.4: RPG prototype for constructor method of the String class


When sending information from Java to RPG, you need to convert the Java String back to the array of bytes used in RPG. The Java String class includes the getBytes method to provide this capability. Figure 5.3 shows how you would write the prototype to access the getBytes method.


D String_getBytes...

D                 PR         65535A   varying

D                                     extproc(*JAVA:

D                                     'java.lang.String':

D                                     'getBytes')

Figure 5.3: RPG prototype for getBytes method of the String class

Starting the JVM

Before using any Java code, you need to get the JNI environment pointer. Procedure getJNIEnv (Figure 5.8), which is called by our main procedure, looks for an existing JVM to attach to. If no JVM already exists, the procedure creates one for the job.



P*  getJNIEnv


P getJNIEnv...

P                 B                   EXPORT

D getJNIEnv...

D                 PI              *

D rc              s                   LIKE(jint)

D jvm             s               *   DIM(1)

D env             s               *

D bufLen          s                   LIKE(jsize) INZ(%elem(jvm))

D nVMs            s                   LIKE(jsize)

D initArgs        DS                  LIKEDS(JDK1_1InitArgs)

D attachArgs      DS                  LIKEDS(JDK1_1AttachArgs)

D fd              s             10I 0


  // First, ensure STDIN, STDOUT, and STDERR are open

  fd = IFSopen('/dev/null': O_RDWR);

  if (fd = -1);

    // '/dev/null' does not exist in your IFS

    // You can create it or use another known good file.


    dow ( fd < 2 );

      fd = IFSopen('/dev/null': O_RDWR);



 // Second, attach to existing JVM

  //      OR create new JVM if not already running

  rc = JNI_GetCreatedJavaVMs(jvm:bufLen:nVMs);

  if (rc = 0 and nVMs > 0);

    attachArgs = *ALLX'00';

    JavaVM_P = jvm(1);

    rc = AttachCurrentThread(jvm(1):env:%addr(attachArgs));


    initArgs = *ALLX'00';

    rc = JNI_GetDefaultJavaVMInitArgs(%addr(initArgs));

    if (rc = 0);

      rc = JNI_CreateJavaVM(jvm(1):env:%addr(initArgs));




  if (rc = 0);

    return env;


    return *NULL;



P                 E

Figure 5.8: Getting a pointer to the JNI environment


Prior to working with the JVM, you need to ensure that the first three file descriptors are open by using the open API, which I have prototyped as IFSOpen. This is needed to prevent errors because the JVM expects STDIN, STDOUT, and STDERR to already be open, which may not always be the case on the IBM i. So this is done as part of the procedure.


Here is the prototype for IFSOpen:


DIFSOpen          PR            10I 0 extProc('open')

D argPath                         *   value options(*STRING)

D argFlag                       10I 0 value

D argMode                       10U 0 value options(*nopass)

D argToConv                     10U 0 value options(*nopass)

D argFromConv                   10U 0 value options(*nopass)

Garbage Collection

RPG uses JNI to load the JVM in the native application of RPG. When you program in Java, the JVM normally recognizes when an object is no longer being used and frees the resources that are no longer referenced by the program. But, because RPG uses JNI to run the JVM, only the RPG program knows when a resource is finished being used, so you will want to manually free resources to avoid excessive allocation of unused memory.


The JNI file provides the DeleteLocalRef function, which you can use directly from an RPG program to remove local object references, but the freeLocalRef wrapper procedure shown in Figure 5.11 retrieves the JNI interface pointer for use with DeleteLocalRef.



P*  freeLocalRef(Ref)


P freeLocalRef...

P                 B                   EXPORT

D freeLocalRef...

D                 PI

D  inRefObject                      like(jobject)

D  env            S               * static inz(*null)


  if (env = *NULL);

    env = getJNIEnv();



  JNIENV_p = env;

  DeleteLocalRef(env: inRefObject);


P                 E

Figure 5.11: Making a local reference eligible for deletion in the JVM

Hello World

We now have all of our foundation procedures established. Let's build a Hello World program that creates a Java String object, sets the value to 'Hello World', and retrieves the bytes back into RPG for display (Figure 5.14).




D*  How to Compile:




D*             DBGVIEW(*ALL) INDENT('.')






D*             ACTGRP(AIR05_01)





D airString       S                   like(jString)

D displayBytes    S             52A


  JNIEnv_p = getJNIEnv();

  airString = new_String('Hello World');

  displayBytes = String_getBytes(airString);

  DSPLY displayBytes;


  *inlr = *ON;


Figure 5.14: RPG/Java Hello World program


If you were to run this program, you would see the expected "Hello World" output displayed on your screen. The figure shows the small amount of code that is required to implement Java from RPG:


  • The /COPY QSYSINC/QRPGLESRC,JNI statement includes all the prototypes and data types that are provided by IBM.
  • The /COPY AIRLIB/AIRSRC,SPAIRJAVA statement provides access to the Java String methods and basic Java procedures.
  • The like(jString) usage on the airString variable provides a reference variable for the Java String object.
  • The getJNIEnv procedure ensures that the STDIN, STDOUT, and STDERR streams are open.
  • The getJNIEnv procedure looks for an existing JVM and attaches to it, if one exists. If a JVM does not already exist, the procedure creates a new one.
  • The new_String procedure calls the constructor method of the String class to create a new object and return the reference variable to the String object.
  • The String_getBytes procedure converts the String content back into EBCDIC bytes to be used within RPG.
  • The freeLocalRef procedure manually releases the memory allocated to the object that is referred to by the airString reference variable.

Coming Soon, PDF!

It may not seem like a big deal to be able to display a String on the screen, but this is the first big step toward getting Java started on your IBM i. In the next book excerpt article, I will do something fun with this capability and create a PDF!



Thomas Snyder

Thomas Snyder has a diverse spectrum of programming experience encompassing IBM technologies, open source, Apple, and Microsoft and using these technologies with applications on the server, on the web, or on mobile devices.

Tom has more than 20 years' experience as a software developer in various environments, primarily in RPG, Java, C#, and PHP. He holds certifications in Java from Sun and PHP from Zend. Prior to software development, Tom worked as a hardware engineer at Intel. He is a proud United States Naval Veteran Submariner who served aboard the USS Whale SSN638 submarine.

Tom is the bestselling author of Advanced, Integrated RPG, which covers the latest programming techniques for RPG ILE and Java to use open-source technologies. His latest book, co-written with Vedish Shah, is Extract, Transform, and Load with SQL Server Integration Services.

Originally from and currently residing in Scranton, Pennsylvania, Tom is currently involved in a mobile application startup company, JoltRabbit LLC.

MC Press books written by Thomas Snyder available now on the MC Press Bookstore.

Advanced, Integrated RPG Advanced, Integrated RPG
See how to take advantage of the latest technologies from within existing RPG applications.
List Price $79.95

Now On Sale

Extract, Transform, and Load with SQL Server Integration Services Extract, Transform, and Load with SQL Server Integration Services
Learn how to implement Microsoft’s SQL Server Integration Services for business applications.
List Price $79.95

Now On Sale



Support MC Press Online


Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: