the minimum you need to know about java on openvms
DESCRIPTION
Promotional version containing first chapters.Up until this point, most Java programming books attempt to make the reader believe that Java is the way-of-the-future and that all other languages are soon to become obsolete. Not so with this book. The author presents Java with all of its warts while continually comparing it to C++ and sometimes C. He admits not being a fan of Java and assumes you are only interested in learning it because your superiors are forcing a Java project upon your OpenVMS system (this is probably more true than not).TRANSCRIPT
About Java on OpenVMSVolume 1
By Roland Hughes
Logikal Solutions
The Minimum You Need to Know
Copyright © 2005 by Roland Hughes
All rights reserved
ISBN 0-9770866-1-5
This book was published by Logikal Solutions for the author. Neither Logikal Solutions
nor the author shall be held responsible for any damage, claim, or expense incurred by a
user of this book and its accompanying CD-ROM as a result of its use or reliance upon the
contents contained in either the book or the CD-ROM.
These trademarks belong to the following companies:CDD Oracle CorporationCMS Hewlett Packard CorporationDEC Digital Equipment CorporationDEC BASIC Hewlett Packard CorporationDEC COBOL Hewlett Packard CorporationDEC C Hewlett Packard CorporationDECSET Hewlett Packard CorporationFMS Hewlett Packard CorporationHP Hewlett Packard Corporation
IBM International Business Machines, Inc.LSE Hewlett Packard CorporationOpenVMS Hewlett Packard CorporationORACLE Oracle CorporationPurify Pure Software, Inc.RMS Hewlett Packard CorporationRDB Oracle CorporationWindows Microsoft CorporationWordPerfect Correl CorporationUNIX The Open Group
All other trademarks inadvertently missing from this list are trademarks of their respective owners. A besteffort was made to appropriately capitalize all trademarks which were known at the time of this writing.Neither the publisher nor the author can attest to the accuracy of this information. Use of a term in this bookshould not be regarded as affecting the validity of any trademark or service mark.
Acknowledgments
I would like to dedicate this book to you, the reader. You have chosen to work with
the greatest operating system ever created even if it is no longer in vogue. You have
endured the demeaning salaries and attitudes presented to you by what passes for
management these days. You have stayed in the trenches and fought the good fight.
There is one person I would like to honor at this point. Not because he has anything
at all to do with the subject matter, but he, like OpenVMS, managed to touch an awful lot
of lives during his brief stay on this planet. That person would be Mr. Peter Jennings.
We never met in this life, yet his voice found its way in on many an evening. Whenever
tragedy struck somewhere in the world it was his newscast I found myself turning to, for
not just the story, but the story behind the story. Some times you learned more from the
side show spot than the actual newscast put on by other networks. In many ways I find
myself identifying OpenVMS with those same broadcasts. It is the OS behind the big
accomplishment. The story behind the story.
Source Code License
Any person owning a copy of this book may use the source code from this book and
accompanying CD-ROM freely when developing software for their personal use, their
companies use, or their client’s use. Such persons may include the source code either
modified or unmodified provided that the source delivered makes reference to the original
author and is delivered as part of a fully functional application. It is expressly forbidden
for anyone to post this software on any bulletin board system, internet Web site, or other
electronic distribution medium without the express written consent of the author. It is
also expressly forbidden to sell this source as part of a library or shareware distribution
of source.
Users of the source code contained within this book and on the accompanying CD-
ROM agree to hold harmless both the author and the publisher for any errors, omissions,
losses, or other financial consequences which result from the use of said source. This
software is provided “as is” with no warranty of any kind expressed or implied.
Table of Contents
Introduction.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I-1I.1 Why Java?.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I-1I.2 Approach of This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I-3I.3 Prerequisites for This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I-4I.4 Obtaining and Installing Java.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I-4I.5 Major Pitfalls of Java on OpenVMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I-7
Chapter 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1Basics of Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1
1.1 A Little Bit of History and Concept. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11.2 Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-51.3 Everything is a Class (almost). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-71.4 Reference not Pointer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-81.5 The Sandbox.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-81.6 Garbage Collection.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-91.7 No Include Files or Preprocessor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-101.8 Constructors and Finalizers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-111.9 Arithmetic Operators.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-111.10 Relational Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-121.11 Boolean Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-121.12 Bitwise Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-131.13 Assignment Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-131.14 Comments.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-131.15 Abstract Classes and Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-141.16 Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-141.17 Polymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-171.18 Source Code Organization and Style. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-171.19 Modifiers for Data Types and Methods.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-181.20 Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-211.21 Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-221.22 Threads.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-231.23 Exceptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-261.24 JAVA$CLASSPATH. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-281.25 A Little Lecture on Strings and References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-281.26 Java Follow Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-301.27 Exercises.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-32
Chapter 2Using RTL and SYS Calls.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1
2.1 Goal of This Chapter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12.2 Order of Development with JNI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12.3 Creating Linker Option Files for JNI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22.4 LibGetLogical. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-82.5 Programming Assignment 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-182.6 VMSLogical. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-192.7 Programming Assignment 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-242.8 VMSDate. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-242.9 Programming Assignment 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-402.10 VMSSpawn. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-402.11 Programming Assignment 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-44
2.12 Words of Warning About LIB$SPAWN(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-442.13 RTL and SYS Followup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-452.14 Exercises.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-46
Chapter 3Accessing RMS Indexed Files.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1
3.1 The Choices We Make. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13.2 Building What We Need. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23.3 The Native Interface Code.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-293.4 One More Indexed File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-483.5 RMS Followup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-503.6 Programming Assignments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-513.7 Exercises.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
Chapter 4Interfacing With FMS.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1
4.1 Why Use FMS?.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14.2 Our Fms Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-24.3 FMS Follow Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20
Chapter 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1Building Java Via MMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1
5.1 The philosophy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15.2 Logical Name Table Modifications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-35.3 Build Command File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-35.4 The Infrastructure MMS Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-65.5 Running Our New Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-185.6 Programming Assignment.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-195.7 Exercises.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20
Chapter 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1Mega Zillionare Application - RMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1
6.1 What to Expect.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16.2 String Dates in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16.3 Importing Data.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-36.4 Bulk Reporting Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-66.5 Creating Our Stats File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-106.6 Programming Assignment 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-136.7 The Most Report.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-146.7 Programming Assignment 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-196.8 The Due Report. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-196.9 Programming Assignment 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-236.10 The Browse Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-236.12 The Entry Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-326.13 The Menu. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-386.14 Programming Assignment 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-42
Chapter 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1Using the Buffers Directly - RMS2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1
7.1 The Intention. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-17.2 How Hurt Are You?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-17.3 Programming Assignment One. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-27.4 Upgrade Before Continuing.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-27.5 Our New Java Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-37.6 Programming Assignment Two.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14
7.7 The Support and Open Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-147.8 Reading Records.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-207.9 Programming Assignment Three. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-257.10 Updates and Deletes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-267.11 Programming Assignment Four. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-277.12 Writing a Record. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-277.13 Follow Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-28
Chapter 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1RDB Via JDBC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1
8.1 Setting Things Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-18.2 A Sample Java Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-68.3 Programming Assignment One. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-108.4 Design Considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-118.5 Some Serious Flaws. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-128.6 Our Main Program.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-158.7 Our Prompt Routine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-188.8 The Import Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-198.9 Stats Creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-228.10 The Due Report. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-268.11 The Dump Report.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-298.12 Our Browse Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-328.13 Programming Assignment Two.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-408.14 The Maintenance Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-408.15 Programming Assignment Three. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-478.16 Programming Assignment Four. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-478.17 RDB Follow Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-488.18 JAR Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-488.19 Java Follow Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-50
Chapter 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-1Ruminations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-19.1 Vendor Management Systems and the End of Consulting Firms. . . . . . . . . . . . . . . . . . 9-19.2 The Tech Farm.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-49.3 Return of the 30 Year System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-79.4 Do You Really Want to Work in IT?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-139.5 Solve the Whole Problem.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-189.6 The Mythical Business Analyst.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-249.7 The Much Maligned LF/CR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-29
Answers to Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-32
Page left blank intentionally.
Introduction
I.1 Why Java?
That’s a very good question. It’s a question I’ve asked myself every time I’ve had to
touch the language. If you grew up during the days of the languages we covered in the
first book of this set, it is a question you will ask yourself over and over again. There is
no good answer — none what-so-ever.
Considering I’m about to write an entire book on areas of the language not normally
covered, that opening paragraph probably shocks you. Sadly, it’s the truth. What is even
more sad is that management makes its decisions based upon four-color glossies, and
there are a lot of four-color glossies for Java products these days. The honest answer is
“Because of the four-color glossies”.
What inevitably happens in this market is management keeps trying to find “cheaper
resources”. This leads them to fish lower and lower in the skill pond. Many of you reading
this are working in mainframe or midrange shops with an awful lot of PC hackers floating
around. If you were paying attention, you watched it happen.
It started with someone from Mahogany Row reading a bathroom length article in the
weekly trade press. There it spouted that if you weren’t on the Web you wouldn’t be in
business for long. These articles all occurred prior to the Dot-Com flame out, which lead
to the nickname DOT-BOMB.
A rash of static Web pages went up. These were followed by the ability to actually
send email. Along the way, somebody said “Hey! Wouldn’t it be nice if customers could
actually place orders using this?” Coding up those kind of Web pages by hand was a lot
of work. The skill and IQ level of college students had been “dumbed down” to the level
of Visual Basic and other “visual” products. None of the current crop of “visual” tools
worked well on the Web, but never fear, a rash of “visual” type tools using Java soon
appeared. This allowed what is currently passing for college graduates to become
employed creating Web sites and since they were recent graduates, they were cheaper
than skilled professionals.
Once the Dot-Com flame out happened, Mahogany Row sat back and smiled. They
were able to pick up a lot of Web and Java programmers for less money than they paid the
box stackers in the warehouse. A mass proliferation of little Web applications sprang up
all around your company. The wheel was re-invented at least a dozen times per quarter.
Graphics got added to Web pages until the internal network was slow pulling the pages
up. Nobody even thought about the poor Schmoe dialed in with a 14.4 modem, or worse,
a 56K modem that only got a 14.4 connection from their ISP. You couldn’t even walk in
the machine room because everybody working on Web pages had to have their own server.
Right around that time is when someone said “Hey! Wouldn’t it be nice if customers could
actually place orders using this?”
I-2 Introduction
So, another rash of Java oriented commercial products hit the market. This time they
were “middleware”. Every vendor was hawking them and hawking N-tier systems design.
At about this point, alert readers began to realize that Java is some of the most expensive
“freeware” they could ever work with.
When you come up through the ranks working on OpenVMS, you cannot begin to
understand why anyone wants an N-tier design. You’ve always had a cluster to work
with. You’ve designed systems to use ACMS servers on every node in the cluster,
consequently, you’ve never had to deal with load balancing because QTI did it for you.
You’ve used RDB for your database because it was cluster aware. With DTM wrapping
your transactions in its protective cloak, you’ve never had to worry about transaction
recovery because all transactions were guaranteed to complete. With nodes of your cluster
scattered across multiple states, you never even had to worry about fail over. As long as
at least one node stayed up you were golden. Yes, the node would be gasping for breath
being run so hard, but it would run. Let me put it to you in terms that will make sense:
N-tier is what you do when you don’t have a good platform to work with.
The concept of N-tier is pretty much “The Swarm Principle”. If you mass together
enough of an inferior force, you can overrun a superior force. Anyone who has ever
watched TV has probably seen at least one commercial or movie where some hapless
Schmoe is being attacked by bees, hornets, wasps etc. The principle works good from a
military standpoint, but only if you are on the attack. From a defensive standpoint, once
the superior force decides to attack, if you don’t counter attack, you’ve lost before the first
shot was fired.
Sadly, businesses who went looking to boost sales, discovered the failings of The
Swarm Principle. They found out that if they had actually gotten all of the sales that tried
to get through they wouldn’t need to boost at all. Without an operating system that had
both clustering and a distributed transaction manager built into its core, many sales were
lost when these replicated nodes and services went down. They weren’t stolen by
competitors or identity thieves, the node which was supposed to process them grabbed the
message, then promptly jumped off a cliff. When the customer didn’t get a response
within a reasonable amount of time, they logged into a different vendor’s site to place their
order.
Many of the companies which have made this discovery are beginning to move more
and more of their Web back onto the OpenVMS cluster. Some are reconfiguring PC based
Web servers to do nothing more than serve up pages and build messages for the OpenVMS
cluster to process. Others are moving the Web server itself back onto OpenVMS to get a
completely stable and robust platform for order processing and customer service.
To answer the question “Why Java?” is to understand why you, as a seasoned
developer with other languages on this platform, are being asked to learn Java. The
answer is two fold. Management wants to convert all of the core business systems to Java
in order to get some use out of the Web developers they have on staff when they are not
developing Web pages. While they know Java, they have expressed little to no interest
in learning the applications of the core business systems. The second fold is that once the
Introduction I-3
Web servers move back onto the cluster, you, the core systems developer, are going to have
to design and develop Web services from a systems, rather than a stand alone Web page
perspective. The PC based Web page writers simply aren’t capable of this.
I.2 Approach of This Book
You may have guessed from the opening section of this book, that it won’t be like any
other book you pick up on Java. Virtually every book on Java which I have either bought
or read starts you off with a handful of stand alone classes, then immediately drops you
into Web page development. In “Volume 1", we won’t even cover Web page creation or
development. At some point, I may write a “Volume 2" which covers that portion of Java
from the OpenVMS perspective, but it is not currently in my plans.
We are going to cover the ugly side of Java which only gets a casual mention in most
other books, JNI (Java Native Interface). As an application developer porting a core
business system from one of the languages we previously covered to Java, you will face
JNI on a regular basis. It is my hope that the source code provided both in this book and
on the CD will jump start your application porting. You should be able to either use
directly, or steal heavily from the source this book provides.
The native interface is a back door provided in the Java language to make it more
usable. Using this back door typically requires more skill than most people using GUI
development tools possess. You have to program in C or C++. Most Java developers wait
for some serious chip-head to produce a new VM (Virtual Machine) which allows them to
access the hardware and operating system features directly from Java. Others buy a
middleware set of classes and saddle their company with a never ending support contract.
My assumption in this book is that you don’t have the luxury of waiting for a new
OpenVMS friendly VM and don’t want the never ending support contract which comes
from yet another third party product, you need to start porting today. In fact, creating a
VM which is OpenVMS specific is actually a violation of the Java license. HP could create
a complete set of OpenVMS specific classes which gives Java developers complete access
to the beauty of OpenVMS, but I wouldn’t hold my breath waiting for that to happen.
Once we get through the obligatory basics of Java, we will jump straight into the JNI.
Our first venture into the JNI will be accessing Run Time Library and System Service
calls from Java. Once that is done we will write JNI code to access the RMS indexed files
used in our Mega Zillionare application. After that we will once again employ JNI to
access FMS. Once all of the steps are taken, we will develop the RMS indexed file version
of our application in Java. Finally, we will move on to the same application using RDB.
There won’t be as many chapters in this book because we are covering only one language
and moving at a much faster pace. I had to lay a lot of ground work in the first book.
Now, I can make you jog, if not run.
I-4 Introduction
I.3 Prerequisites for This Book
It is assumed that you have in your possession a copy of “The Minimum You Need to
Know to Be an OpenVMS Application Developer” ISBN 0-9770866-0-7. (Hereafter
referred to as “Book One".) It is also assumed that you have read that book and are at
least somewhat comfortable with development on the OpenVMS platform. I will not be
spending much, if any, time discussing the concepts covered in that book. You are
expected to either know them, or look them up in that book.
You may wish to get your own Alpha machine and Hobbyist license. This will let you
break things any way you want. While you could shop around on Ebay and hope against
hope you bid on a machine which was correctly configured, I would highly recommend you
contact Island Computers (www.islandco.com) to get a machine correctly configured. Then
all you have to do is install your Hobbyist media and licenses. Many of you may be quite
comfortable assembling PC’s from scratch, but you have to be a little more selective with
the hardware you get for an Alpha.
I.4 Obtaining and Installing Java
Hopefully, you are all corporate employees with systems managers keeping your
OpenVMS machines properly configured. In a commercial environment software and
service contracts lead to CD’s showing up in the mail with the latest ECO’s and software
upgrades. I believe ECO stands for Engineering Change Order, but have used ECO for
so long I cannot say for certain. This is the term used to describe all fixes and
enhancements. When you wish to install the latest version of Java for OpenVMS you need
to be at the current ECO level for it.
While it is true that Java does ship with OpenVMS, the version on my machine did
not have the javah tool. This could have been a bone headed move on my part during the
install of the products, or it simply might not have been included with the Hobbyist media.
In either case, the version which was installed was 1.1.8-5 and the current version was
1.4.2.
Do not skip the step of downloading and applying all of the ECO’s. Lots of people try
to do this and it hurts them. I obtained my Java stuff from the following link:
http://h18012.www1.hp.com/java/download/ovms/1.4.2/sdk1.4.2_patches.html
While you could go to www.hp.com and look for Java stuff, I recommend you start off
at www.openvms.org when researching Java for your machine. The site is a valuable
resource for any OpenVMS developer, and its links are usually pretty current.
Be careful when you start to download ECO’s and install them in the correct order.
Some of them are 40+MEG in size (assuming you are running 7.3-1 which is the current
Hobbyist version of OpenVMS). You may need a download manager or a very forgiving
ISP. The other option is to contact HP directly and purchase the CD’s containing ECO’s
Introduction I-5
and Java for your machine. From a simplicity standpoint, that last option is the best, but
it depends on the depth of your pockets for this adventure. The instructions for applying
the ECO’s are pretty straight forward. They appear on the Web site where you download
the needed files.
Another thing you will want to download and install from HP is the Mozilla Web
browser and email package. You will want the browser so you can open the Java
documentation. Once Java is installed, the Java documentation is found in
SYS$COMMON:[JAVA$1xx.DOCS]INDEX.HTML where xx = your version. Please note
that you will need to enable DECWindows on your system console, or have an X-windows
terminal emulator in order to run the browser. You cannot run the browser from a
standard VT character cell interface.
If you wish to be an enterprising little geek, you can enable NFS services on your
Alpha machine, obtain an NFS client for your Windows machine, and map the
documentation directory into your local machine. This will let you open the HTML files
from your PC browser. Telling you how to set that up is currently beyond the scope of this
book. There are also very few “free” NFS drivers/clients available for the Windows XP
platform at this time. If you are connecting to your OpenVMS machine from Linux, you
may have an easier time of it.
Once you have downloaded either directly to your OpenVMS box or FTP’ed it from
your PC you can run the installation process. Here is the session from my machine:
$ set def dkb200:[scratch]
$ run dkb200:[eco]DEC-AXPVMS-JAVA142-V0104-24P2-1.PCSI_SFX_AXPEXE
UnZipSFX 5.40 of 28 November 1998, by Info-ZIP ([email protected]).
inflating: DEC-AXPVMS-JAVA142-V0104-24P2-1.PCSI
$ product install *
The following product has been selected:
DEC AXPVMS JAVA142 V1.4-24P2 Layered Product
Do you want to continue? [YES]
Information has been saved to allow you to uninstall the following patches:
RECOVERY DATA SET 001 created 9-JUL-2005 17:13:10.69
-------------------------------------- --------------------------------------
PATCH APPLIED TO
-------------------------------------- --------------------------------------
DEC AXPVMS VMS731_PTHREAD V4.0 DEC AXPVMS VMS V7.3-1
-------------------------------------- --------------------------------------
RECOVERY DATA SET 002 created 9-JUL-2005 17:12:05.81
-------------------------------------- --------------------------------------
PATCH APPLIED TO
-------------------------------------- --------------------------------------
DEC AXPVMS VMS731_DCL V5.0 DEC AXPVMS VMS V7.3-1
-------------------------------------- --------------------------------------
RECOVERY DATA SET 003 created 9-JUL-2005 17:11:09.67
-------------------------------------- --------------------------------------
PATCH APPLIED TO
-------------------------------------- --------------------------------------
DEC AXPVMS VMS731_TDF V5.0 DEC AXPVMS VMS V7.3-1
-------------------------------------- --------------------------------------
I-6 Introduction
RECOVERY DATA SET 004 created 9-JUL-2005 17:09:47.54
-------------------------------------- --------------------------------------
PATCH APPLIED TO
-------------------------------------- --------------------------------------
DEC AXPVMS VMS731_ACRTL V4.0 DEC AXPVMS VMS V7.3-1
-------------------------------------- --------------------------------------
* If you continue, recovery data for the patches listed above will be deleted.
* The deletion of recovery data does not affect the installation status of
* patches applied to products that are not participating in this operation.
* However, continuing with this operation prevents you from uninstalling
* these patches at a future time by use of the PRODUCT UNDO PATCH command.
Do you want to continue? [NO] yes
Configuration phase starting ...
You will be asked to choose options, if any, for each selected product and for
any products that may be installed to satisfy software dependency requirements.
DEC AXPVMS JAVA142 V1.4-24P2: JAVA for OpenVMS Alpha
Copyright 2003 - 2005 Hewlett-Packard Development Company, L.P.
Do you want the defaults for all options? [YES]
Do you want to review the options? [NO]
Execution phase starting ...
The following product will be installed to destination:
DEC AXPVMS JAVA142 V1.4-24P2 DISK$SYS:[VMS$COMMON.]
Portion done: 0%...10%...20%...30%...40%...50%...60%...70%...90%...100%
The following product has been installed:
DEC AXPVMS JAVA142 V1.4-24P2 Layered Product
DEC AXPVMS JAVA142 V1.4-24P2: JAVA for OpenVMS Alpha
Consult SYS$COMMON:[JAVA$142.DOCS] for the Release Notes for this product.
$DIR SYS$COMMON:[000000]
Directory SYS$COMMON:[000000]
JAVA$142.DIR;1 1/18 9-JUL-2005 17:22:26.42
JAVA.DIR;1 1/18 17-NOV-2004 11:11:08.18
Each version of Java now has its own directory in SYS$COMMON. Long ago things
were kind of scattered. You may wish to add the following line to your LOGIN.COM file
or to SYLOGIN.COM if you own the system:
$ @sys$common:[java$142.com]java$142_setup
Introduction I-7
I.5 Major Pitfalls of Java on OpenVMS
I highly recommend that you poke around on www.openvms.org and find the
downloads for ODS-5 prior to doing any development with Java. There is a procedure for
converting your disk drives to ODS-5 (from ODS-2) listed with the download. Without
trying to get too technical, using ODS-5 (which you would need if you installed MySQL
when we covered it in our previous book) allows for mixed case file names and a more
peaceful existence with opensource software.
Java is a case sensitive language. Most of you will say “So what, wasn’t C?” Yes and
no. C was case sensitive within the language, but converted all of its entry points to upper
case. Some of you may remember my debugging tip about the debugger not being able to
find your function names when you tried to set a break point typing in lower case.
Java is case sensitive outside of the compiler. When you declare a class it is
customary to used mixed case names. When Java attempts to run your P-compiled class
from within the VM (Virtual Machine), it looks for a file name matching the class name
in exact case. You can either break tradition and work completely in upper case, or you
must get used to putting quotes around your file names when using the tools. This pitfall
exists on all stable and mature platforms where Java is ported. It isn’t a problem on the
lesser platforms.
Another major pitfall with Java is that it is an semi-interpreted language. Most call
it an interpreted language, but I do not. You P-compile Java source code into a syntax the
VM understands. The VM then interprets the P-compiled code at run time. While many
will lament about the performance penalty of interpreting code, I won’t bother. My issue
with the VM is that you can’t use it from within the safety and security of an ACMS
application.
Yes, you can set up a C program or function to call Java on OpenVMS, but once you
do that, you are running inside of the VM, not the controlled and secure environment of
ACMS. At least that is my opinion. Should the Java VM die spastically without
communicating its death back to the caller, your server will sit idle waiting for a response
until it has reached the configured time out parameter. Then, and only then, will ACMS
kill off the task and start a new server to handle the message/task queue entry which was
being processed by the previously existing server. Admittedly, it is a small beef. We face
the same problem when we are accessing a relational database other than RDB.
I-8 Introduction
Page left blank intentionally.
Chapter 1
Basics of Java
1.1 A Little Bit of History and Concept
Don’t worry, I’m not going to bore you to tears re-hashing the same history lesson
every other Java book feels compelled to provide. Not my style. You can read about that
for free on-line, or you can buy one of the oh-so-numerous books on Java which will burn
an entire chapter covering the history.
First, let me ask for a show of hands, or whatever limbs you happen to possess, “How
many of you consider yourself descent, good or seasoned C++ developers?” A very special
form of Hell waits for you while learning Java. “How many of you consider yourself
comfortable or good with pointers in either C or C++?” Ah, one or more chemical
dependancies are in your future learning this language. Choose your poison now!
This may not come as a surprise to you, but I’m not the biggest fan of this language.
Having spent way too many years coding in C and C++ on viciously underpowered
platforms tweaking cycles out of loops, I got really good with those languages. (Okay, I’m
a lot better with C than C++, at least according to the purists.) This language offended
me in many ways. While I am somewhat functional with the language, I am by no means
an expert, and avoid it when possible. (I’m still trying to figure out how I got talked into
writing this book. It sure wasn’t the publisher, because I’m self published!)
I think the biggest source of problems I and most other C/C++ programmers have with
this language are rooted in the syntax and where the language came from. Java was not
originally developed to be a Web language. That happened when marketing got involved.
Java was originally developed to be an embedded systems language. The kind of system
which exists in your microwave, VCR and later model automobiles.
This concept wasn’t too bad at the time it was developed. Having done some near
embedded development myself in the early days of pen computing under DOS (don’t ask!),
I can tell you that state of RTOS (Real Time Operating Systems) for embedded use was
not good. Most shops had a collection of routines they kept using and tweaking with each
new project, but commercial RTOS were way too expensive and not much cleaner. Almost
everybody was hacking in assembler, with only the high end shops using C. (Ironically,
that’s pretty much the way it was when I last looked at the embedded market as well.)
In truth, the concept was phenomenal. Rather than bread boarding together a CPU,
some RAM, an EPROM and some IO devices; there were going to be these prepackaged
chips containing all of that along with a VM which understood Java. These single chip
machines were going to be built in volume and used for everything because they would be
cheap enough.
That really was a nice idea. It may even happen at some point. I just don’t see it
happening as long as there are enough grizzled old timers still working. Too many of
them know how to hook together a 4-bit or 8-bit CPU, some RAM and some IO along with
many years worth of hand tuned assembler. When they get done, it has a production cost
1-2 Basics of Java
measured in cents, not dollars. Higher end appliances, like cell phones and PDA’s are
probably already using the once planned embedded Java. I just don’t see it working its
way into your VCR or DVD player any time soon. Just how many brains do consumers
who leave the clock flashing 12:00 really need their VCR to have?
When Java was being created, the creators wanted it to be quickly adopted. At least,
that is the reason I’ve always been given when I asked why they used the syntax of C++.
My personal opinion is that they would have gotten far more support from seasoned C/C++
developers if they had invented a completely new language syntax, or used something like
FORTRAN.
The reason for this belief is mind set. When you pull up a screen of code and it looks
like either FORTRAN, BASIC or COBOL you immediately go into the mind set for that
language. Every seasoned developer does it. You don’t even know you do it. When you
pull a Java source file up in your favorite text editor, you immediately go into C++ mind
set, then are constantly frustrated by what is missing.
Had there not been a rash of GUI pick and point tools developed early on for Java, I
think the language would have died on the vine. That’s my personal opinion. I will back
that up with a test you can perform at your company. Ask someone that calls themselves
a Java programmer at your company to develop an application without using any GUI
development tools. Tell them to hand code everything in a text editor. No drag and drop
components. Make it something small, like our Mega Zillionare sample application. What
you will find is that most of the Java programmers are really GUI tool users who happen
to know enough of the Java language to tweak things here and there.
Each and every time I need to discuss the syntax of Java with someone I have to vent
my frustration so communication can occur in a productive manner. Remember when I
said the C++ programmers had a very special Hell waiting for them, well here it is: You
will be completely consumed by the belief that Sun had a bunch of developers sitting
around who were physically incapable of learning C++, so they wrote a compiler which
handled as much as those developers could understand and tried to do the rest for them.
I know that some very learned people worked on the language and that they are
considered way smarter than me. That’s okay. I’m not the only C++ developer I’ve met
who has the exact same feeling. I’ve even seen it expressed in far more politically correct
terms throughout the years in geek magazines. Early on in its existence I even read some
interviews with the author of the language where it was stated they wanted to remove bad
stuff out of C++. During the evolution of Java, a lot of the bad stuff got added back in
because you simply couldn’t live without it. Let’s spend part of our history and concept
time discussing the bad stuff.
Remember back in the first book when talking about C++ and I told you I couldn’t
remember what the default protection was in a class? That was not completely honest.
I do have lucid moments from time to time where that knowledge randomly surfaces. If
you never knew it, then I suggest you don’t bother learning it. The reason I suggest that,
and the reason I don’t remember on a regular basis, is I have had to work with Java upon
Basics of Java 1-3
occasion. The default protection method is different under Java. It is best you never learn
what the default protection method is, and always code; public, private or protected.
Java was created back when “goto-less” programming was all of the rage. Java even
went so far as to reserve the “goto” phrase as a keyword so other VM writers couldn’t add
it. There is one thing you can always say about a “goto”. Code a big enough and complex
enough program with lots of iterative changes handed out by the users, and you will need
it. The very quiet replacement for this bad thing was the labeled “break” and “continue”
statements. Java got rid of the “goto” keyword and replaced it with two synonyms for
“goto”. (When making that last statement in a bar around programmers whose religion
is Java, it is advisable to wear machine washable clothing. It is good for at least one
thrown drink and usually a fist fight.)
One of the biggest sources of bugs in code written by C and C++ developers is pointer
usage. Many developers learning the language simply don’t understand the concept. This
leads them to use uninitialized pointers and write over random sections of memory. The
other problem is that they allocate a big chunk of memory and forget to free it. If you are
working on a robust operating system, this last little bit isn’t a problem for your
application. Once your process is exited the operating system will clean up the allocation
you forgot to free. On lesser platforms it’s a real problem. Even after your process exits,
that memory is still allocated.
Java sought to solve both of these problems. The first solution was pretty drastic.
They removed pointers completely from the language. The second solution was built in
garbage collection. We discussed garbage collection some in the first book when talking
about relational databases cleaning up deleted rows in its tables. This garbage collection
has to do with the freeing of unused items in memory, much like C++ does when objects
go out of scope. Java went a whole lot farther. It provides no “delete” operator. When
working with C++ you have both “new” and “delete” to give a programmer nearly complete
control over object life time. Java, only lets you control when an object is created. It has
to go out of scope, then wait for garbage collection, to actually be deleted. (Some
developers refer to this as “going out to the curb” since that is where garbage pick up
occurs for suburban residents.)
Another bad thing that went away was multiple inheritance. Right here is pretty
much where I get that foul taste in the back of my throat that just won’t go away. It is
also the point which leads me to the opinion about a bunch of developers that couldn’t
learn C++.
Let me describe multiple inheritance in plain speak. Multiple inheritance is a concept
in C++ (and most other OOP languages) which lets you create a shiny new object by
inheriting all of the inheritable properties of more than one other object. These objects
don’t have to have any relation what-so-ever. They can be at different levels in their own
inheritance trees. How anyone managed to write a compiler specification for that I’ll
never really understand.
1-4 Basics of Java
Don’t go letting your eyes glaze over just now. This was the most powerful tool C++
gave us. It allowed you to solve unbelievably complex problems. I don’t want to give you
a contrived example, and we aren’t covering C++ in depth in this book. Being able to
combine multiple unrelated objects into a single new object definition was a tool which
was indispensable with C++. Java learned its lesson by leaving it out. The later
definitions of the language added it back in, but they don’t call it multiple inheritance,
they call it “interfaces”.
Oh, what a horrible choice of names “interfaces” was. This is a completely different
definition of “interfaces” than most C++ programmers use. With respect to Java an
interface is a collection of constants and abstract methods. They are not classes. An
interface doesn’t declare any usable data items. When you choose to implement an
interface within a class you must provide all of the methods declared in the interface and
they must be at the same protection level as declared in the interface. When you declare
your class you can inherit from only one other class, but you can implement many
interfaces. When C++ programmers talk about interfaces to classes they are talking about
the externally available list of methods and members. In C++, every class has an
interface. With Java, only a class that “implements” an interface has an interface. (The
keyword is implements not implement.)
If your eyes glazed over reading that last paragraph, it’s okay. There is a reason I
didn’t talk much about interfaces when we discussed C++ in the last book. I didn’t want
to get you far enough into the language of C++ to make your journey through Java
painful.
Java was originally intended to be pure OOP (Object Oriented Programming).
Everything, short of the most basic data types, is a class. You can’t even have a stand
alone “main()” function as you can with C++. The philosophy behind C++ was you could
use it as a better C until you got comfortable enough with OOP to start doing more with
OOP. With Java, you have to do a running cannon ball into the pool of OOP. There
simply is no other way.
Nearly every book on Java you buy will show you how to write applets in Java. In
order to run the applet you will need to write some HTML and use a browser. This book
will not bother with applets or browsers. The concept in this book is how to convert your
existing core business applications to use Java, yet still preserve your investment in the
most stable platform on earth. You will also want to preserver your investment in
character cell terminal emulators and character cell terminal emulators cannot run a
browser.
Basics of Java 1-5
1.2 Data Types
Java supports a limited set of core data types. The distinction between a core data
type and other data types is the lack of class. Core data types are understood directly by
the compiler without using any library functions. All other data types are class definitions
and require the run time libraries. There are only 3 groups of core data types: numeric,
boolean, and character. Do not leap to the conclusion that character is how you deal with
string values in Java. While that is true for many 3GL’s, it is not true for Java. To deal
with string data types, you have to use the String class.
During the course of the first book I mentioned several times the problems of porting
data from one hardware platform to another. Some machines are Big Endian and others
are Little Endian. Additionally, many machines developed their own proprietary numeric
data types for handling floating point values. Java solved that problem with the VM.
Every data type has the exact same byte order no matter what machine the VM was
implemented on. This means that if you create a flat data file using raw numeric values
on one machine, it can be read by Java on another machine. All bets are off with indexed
files that are native to a specific platform. The Java language itself doesn’t provide any
indexed file support.
One of the biggest selling points for most GUI development environments is that they
give you some form of indexed file library along with database access. The catch was any
machine you wanted to use this data on had to have the database engine, or at least the
GUI development environment installed. As I said, Java is some of the most expensive
“freeware” you can get. If you surf around on the Web you can usually find some B-tree
indexed file systems written completely in Java. Good luck finding free versions of them
though, since most developers have bad habits like eating and living indoors.
There are six core numeric data types supported by Java.
byte tiny signed integer 8-bits
short short signed integer 16-bits
int signed integer 32-bits
long long signed integer 64-bits
float floating point number 32-bits
double double precision float 64-bits
Remember that there are eight bits to a byte on most machines these days, then look
at the following C code.
1-6 Basics of Java
TEST_SIZES.C
#include <stdio>
#include <stdlib>
int main (int *argc, char **argv)
{
printf( "Size of long %d\n", sizeof(long));
printf( "Size of double %d\n", sizeof(double));
printf( "Size of short %d\n", sizeof(short));
printf( "Size of int %d\n", sizeof(int));
return 1;
}
$ run test_sizes
Size of long 4
Size of double 8
Size of short 2
Size of int 4
When working with C a long is 32-bits. The long data type in Java corresponds to the
quadword data type I spent so much time harping about during the first book. Get this
difference down.
Since the core numeric types can be restrictive to some developers, some additional
numeric classes were added to the language. These classes are BigDecimal and
BigInteger. They can be used to create numbers of arbitrary width and precision. We
won’t be messing with them in this book. Just remember they are there in case you need
to create some 128-bit floating point values.
With respect to floating point data types, Java stole some pages from the FORTRAN
specifications. It has specific values for NAN (Not a Number), Negative Infinity and
Positive Infinity. You get NAN results when performing illegal operations, such as
dividing by zero or multiplying by infinity. Since division by zero happens a lot in the
business world, this is a good thing.
Boolean is a data type most of us think we should know, but we don’t. Under most
languages boolean values are simply integers that use either positive/negative or 1/0 to
indicate true/false. Under Java there is a specific boolean data type which can have only
true or false as its value. If you forget to initialize your boolean it is initialized to false.
Keep in mind that Java provides a default initialization for all class data members,
but not locally scoped variables. We will discuss more on this later, or you can open the
previous book and skim through the scope discussion for the C/C++ chapter.
The character data type is the one which trips up most developers coming from other
languages. When we covered BASIC, FORTRAN, COBOL and C/C++ in the previous book
a character was always 8-bits wide and held an ASCII value. With the exception of the
currency symbol, the representation of these characters was standard across platforms for
the first 127 values. The last 128 characters were a free-for-all dependant upon the active
Basics of Java 1-7
code set on the machine and what a developer chose to load for them. (We did not cover
loading different values in the last 128 characters. That is something usually only done
by PC developers to draw graphics.)
The creators of Java decided they wanted it to be an international language, not follow
existing trends. As a result the character values used by Java are 16-bits wide and are
Unicode characters. For the most part, Unicode kept the first 127 the same as ASCII,
simply because of the installed base. I won’t go into the ins and outs of Unicode. Those
of you wanting to know more about Unicode can visit http://www.unicode.org.
1.3 Everything is a Class (almost)
Since the creator(s) of Java wanted it to be a pure OOP language, almost everything
is a class. The previous section covering the core data types is just about the only thing
which isn’t a class, but can only be used from within a class. Your application has to have
one primary class with a “main()” method declared in it in order to run.
The first class you need to get familiar with is String. Technically the full name of the
class is “java.lang.String”, but since it is the core API you can declare instances of it just
using String. When you place a quoted string in your source listing the compiler doesn’t
just create an array of characters, it creates a String object (instance of a String class) to
contain those characters. Those characters will magically be flagged for deletion whenever
they go out of scope.
Let me go into this just a little further.
String mantra = “I am a real programmer”;
mantra = mantra + “, I studied logic without a language.”;
After these statements execute there are actually three string instances and one
StringBuffer instance in memory. At some point in time Java will get around to garbage
collecting the temporary StringBuffer object that was used to concatenate the two quoted
strings together. In order to understand why that is, you need to know one thing about
String objects; they can’t be changed. Oh, we add, subtract, change and otherwise
mutilate strings in our code, or so it appears. Behind the scenes Java keeps making new
ones. A StringBuffer class is the dynamic class of string which allows for string
manipulation. Once it has been manipulated the result is given to a String object and will
stay as it is until the garbage collector tosses it back on the heap.
I know that the above example was a lot to swallow this early on, but we shall
endeavor to persevere. The next section will help sweep it up for you.
1-8 Basics of Java
1.4 Reference not Pointer
When we covered C++ we talked about passing objects by reference. Where a
reference was a very special kind of pointer which made the object appear as if it were
local to the receiving method (function). Java takes references to a new level. Everything
which isn’t a core data type is a reference. In the previous example, where the syntax
made it look like we declared a String object named mantra, we actually declare a String
object of unknown name and mantra was a reference to that String object. This is a
difficult concept for many developers.
To understand how we end up in this situation you have to remember Java runs under
a VM (Virtual Machine). When we talk about compiling Java we talk about generating
a P-compiled file which the Virtual Machine understands. When we talk about compiling
our previously covered languages we talk about generating binary OP codes understood
directly by the CPU. As programmers we tend to think our program is doing what we
coded. When speaking in terms of Java, this is not true. The VM is doing what we ask.
The P-compiled translation generated something along the following lines:
Hello VM. Go create me a String object having the value of “I am a real programmer”.
When I refer to that object in the future I am going to call it mantra. Feel free to delete
it when you don’t think I need it any more.
The key phrase in this conversation is “when I refer to that object”. There in lies the
fundamental principle of Java. Your “program” doesn’t own anything, it never has, and
it never will. It is a slave begging for favors and services from its master, the VM. When
the VM decides you no longer need something, it takes it away without telling you.
1.5 The Sandbox
This master-slave relationship lead to a concept you will hear talked about quite a bit
by Java developers, the sandbox. With version 1.0 of Java the sandbox was introduced.
Code which was downloaded rather than written locally would run in a sandbox. What
that code could and could not do was controlled by the SecurityManager object. The
abilities allowed by the sandbox change based upon settings you or your system manager
tweak in the VM and by new releases of Java.
I’m bringing up the sandbox here, because as application developers, it is useful for
you to envision all code as running in a sandbox. That’s really the concept behind the VM.
One sandbox may have more toys than another sandbox, but it is really just a sandbox.
Those of you reading this who own cats feel free to conjure up a humorous image of the
Java sandbox and what is going on there.
Basics of Java 1-9
1.6 Garbage Collection
I need to discuss just a little bit about garbage collection before moving on to more
interesting topics. At various places already I have mentioned garbage collection. This
is automated memory reclamation. For lack of a better description, each little sandbox
keeps a list of objects it no longer needs. When the garbage collector makes its rounds it
looks at each sandbox and starts deleting items off that list, returning memory to the VM
pool.
Since Java was originally designed for embedded systems which are traditionally
underpowered, performance was of paramount concern. Besides wanting to eliminate
pointers, the creators wanted to remove the burden of freeing memory allocations from the
application developer. They placed that burden on the systems developer coding up the
VM. A lot of heated arguments happened about where and when to do garbage collection.
Ultimately, it was decided to have the VM launch a task at priority zero so it only got time
when the system was idle.
Developers from days gone by on OpenVMS remember fondly the NULL process. You
used to be able to see it when you typed in the command:
$MONITOR PROCESS/TOPCPU
Alas, the NULL process is now hidden away from casual observers. This used to be
a good guide in determining why your system seemed sluggish. If the NULL process was
getting a lot of time you knew the problem was disk IO. Either you had a “hot spindle” or
you had a pair of big jobs beating each other up trying to lock the same records. (A “hot
spindle” is a term used to describe a disk performing massive amounts of IO.)
When your OpenVMS box is running at 80% capacity or less, this method of clean up
works well. The 80% is a number I learned back on the VAX hardware. I don’t know what
the number is for Alpha hardware or Itanium hardware. I assume it is now closer to 90%.
Regardless of where that magic percentage threshold is, or what platform you are on,
when you exceed it, all of those clean up tasks hooked into the idle process won’t get any
time.
What this means in terms of Java is that garbage collection will not occur.
Applications will continue running on the machine, although they will seem sluggish, but
memory resources will no longer free up. That means that even when your application
finishes, the sandbox it ran in won’t go away because the garbage collector never got any
time to come around and take out the trash. If one or more of the processes binding up the
CPU doesn’t complete, you will eventually exhaust all virtual memory and things will
start crashing.
Those of you coming from Windows and Unix type environments will envision this as
a complete system crash. Nothing could be further from the truth on OpenVMS.
Remember back in the first book where I made you look at UAF (User Authorization File)
entries? Every process runs under a user ID. Each user ID process has an amount
1-10 Basics of Java
available to them determined by the entries in the UAF for that user. If you are starting
and stopping a lot of Java programs under a standard user account when the garbage
collector is barred from doing its job, you will most likely be the process which crashes.
Look on the bright side though. When your process goes away, it will free up some CPU
cycles so the garbage collector can finally clean up after you.
1.7 No Include Files or Preprocessor
One of the most abused concepts in the C language was the preprocessor. Developers
did nasty things with macros that would collide with other macros creating a complete
debacle for the hapless coder trying to make two commercial libraries work together. C++
tried to help alleviate the problem by adding namespaces to its language definition.
The creators of Java decided, when it came to header files, that dog won’t hunt. They
don’t exist in the language. But it didn’t take long for that idea to create its own little
train wreck. Without some method of inclusion from external sources, you couldn’t use
libraries together without cutting and pasting large amounts of code into your source file.
Enter the “import” statement. This isn’t like the #include directive you find in C, even
if it does look a lot like it. The import statement allows you to bring in either specific class
definitions from packages, or entire packages.
What’s a package you ask? A package is a group of classes that get compiled into a
package. (Nice Webster, eh?) At the top of each class source file you want to be part of a
package you stick in the statement “package some.package.name;” Once you have
compiled all of the classes for the package, and built the package, you can then reference
it in your application source file by coding “import some.package.name.SepcificClass;” to
get only one class or “import some.package.name.*;” to get the entire package.
While it may seem easier to just import the entire package, don’t. These aren’t header
files and Java isn’t polite like C. When working with C you could include every header file
you though you might need and as long as they didn’t declare any global data, they had
no impact on your executable size. With Java, your P-compiled little class suddenly
becomes an 8000-lb. Gorilla when it loads.
Notice the format of the package name with all of the dots in it. This is one part of
Java that seems to be tied completely to the Web. The convention for naming packages
is to invert your domain name and add some stuff. If you happen to be a company or
person with a registered domain name, this works out well. For those of us working
internally, we have to cobble up a domain name on our internal network. The cobbled up
domain name I put on my internal network is logikal.com. Packages I declare in this book
will be com.logikal.something.
Basics of Java 1-11
1.8 Constructors and Finalizers
Since we have a prerequisite that you have already read the previous book, you are
already familiar with the concept of constructors and destructors from the section on C++.
The constructor is tasked with allocating storage for the object and its core data items. It
does not allocate storage for data items which themselves are classes. The constructors
for those objects are tasked with that. If you don’t bother to code a constructor for your
class the compiler will generate a default constructor for you. Unless your classes are
simple, you may not like what it does.
If you code any constructor in your class definition, the compiler will not generate a
default constructor for you. This means that if you code a constructor which accepts
parameters to populate data items with, you will also have to code a version which accepts
no parameters if you want that functionality.
Your constructor has the same name as the class with no return value. You can
overload your constructors just like you can overload methods.
Remember when we discussed C++ in the last book we talked about a destructor being
the same name as the class but having a “~” in front of it? Java decided to go its own way
here. Destructors in Java are called finalizers. They are actually a method named
finalize() which accepts no parameters, but can flag exceptions it might throw. (We will
talk about exceptions much later.)
Always declare your finalize method as a protected void method. This stops someone
from being either malicious or stupid. If it isn’t protected it could be called from
anywhere. A finalizer method is something people don’t code much. The reason is they
don’t do much. The compiler generates the code to flag all of the items for garbage
collection. The only things you wish to do in a finalizer is close files and release external
resources. A case in point would be the two classes we declare for accessing RMS indexed
files in the previous book. The only thing they did was call the close() method.
1.9 Arithmetic Operators
It will come as no surprise to you that Java supports most of the arithmetic operators
from C. Here is a quick and dirty table for you. Precedence is in descending order with
one being the highest.
Operator Description Precedence
++,-- auto-increment, auto-decrement 1
+,- unary plus, unary minus 1
*,/ multiplication, division 2
% modulus (remainder) 2
+,- addition, subtraction 3
1-12 Basics of Java
Some of you may remember the little saying I imparted to you in the last book.
Please Praise Powers Parenthesis
My Dear Multiplication Division
Aunt Sally Addition Subtraction
It still works here. I’ve yet to find a place where it didn’t work. Since modulus is
really a division it occurs at the same level. Java does not give us the “**” operator that
BASIC did for raising a number to a power. You have to use the power() function of the
math package.
1.10 Relational Operators
We get the same set of relational operators with Java that we had in C/C++.
Operator Description Precedence
>, <, >=, <= greater than, less than,
greater than or equal,
less than or equal 5
== equality 6
!= inequality 6
?: conditional operator 13
Once again I must caution you to never use the conditional operator. It is short hand
for if-then-else. The item placed in front of the “?” is tested for truth. When it is true, the
value immediately after the “?” is the result. When it is false, the value following the “:”
is the result. As in C/C++ this is a very confusing operator for most people to read. My
personal opinion is that programmers use it for job security. Using it eliminates a large
pool of people which could otherwise maintain the code.
1.11 Boolean Operators
Java has the same set of boolean operators as C/C++ as well.
Operator Description Precedence
! Not 1
& Boolean AND 7
^ XOR (Exclusive OR) 8
| Boolean OR 9
&& Conditional AND 10
|| Conditional OR 11
These boolean operators don’t work like their C/C++ counterparts. You can only use
them on variables of the boolean data type or expressions that return a boolean data type.
To add insult to injury, some of the bitwise operators are exactly the same as the boolean
Basics of Java 1-13
operators.
1.12 Bitwise Operators
Operator Description Precedence
~ not 1
<<, >> left shift, right shift 4
>>> right shift as unsigned 4
& bitwise AND 7
^ bitwise XOR 8
| bitwise OR 9
One thing worthy of note here is the >>> operator. You don’t find this in many
languages. The reason for its existence is that Java doesn’t have unsigned data types. If
you right shift a signed numeric that has a negative value the sign bit keeps walking
down. This operator stops that from happening.
1.13 Assignment Operators
As in C/C++ there is an entire family of assignment operators. We all know about the
“=”, but what most people forget is that you can prefix the equal sign with every one of the
arithmetic or bitwise operators. Only one at a time, of course, but that creates a great big
list of assignment operators.
1.14 Comments
Java supports the same comments as C/C++. This means you can use either /* */ to
enclose a comment or // to create a single comment running to end of source line. There
is also one very special comment indicator you will see. The compiler accepts it like a
comment, but another utility uses it to generate documentation.
/** This is a javadoc comment line */
The comment starts with /** and must end with */. It can span multiple lines as with
a regular comment of /* */ type. When you feed a source file through the javadoc utility,
it scans the source looking for these special comments to create HTML formatted
documentation files.
While this is a nice idea, most developers, myself included, don’t write descriptive
enough comments to be used for documentation. There have been various utilities in the
C programming world for quite some time which used the same or similar comment syntax
to generate documentation. Granted they didn’t generate HTML documentation for Web
usage. The Web didn’t exist when those tools came out.
1-14 Basics of Java
1.15 Abstract Classes and Methods
The world of OOP likes to let the original developer impose rules on those to come.
The biggest one of these rules is enforced by the keyword “abstract”. When you put the
keyword “abstract” on a class, it can contain only constants and abstract methods. No data
variables or implementation code can exist for it. Every class which inherits from this
abstract class will be forced by the compiler or the run time environment to provide an
implementation for each abstract method. The catch, however, is that the implementation
doesn’t actually have to do anything. You can make it a dummy method.
1.16 Inheritance
You receive a letter in the mail from a law firm reading “After conducting a thorough
investigation of all sources we have determined you really are the sole beneficiary of
Howard Hughes’ estate totaling...” Oops! Not exactly the definition used by OOP. We
discussed inheritance in Book One. The syntax and rules are somewhat different with
Java.
Java only allows you to inherit from one class at a time. This is not to say that you can
only go down one level in classes. Our theoretical RMS classes from Book One could be
implemented in Java because each level only inherited from one other class. You can
continue chaining down until you lose your place, but you cannot inherit from more than
one class at a time. For most of you, this won’t be too bad. Only developers doing heavy
up front design tend to design applications or systems needing multiple inheritance.
Developers new to both C++ and Java tend to avoid designing their own inheritance,
and that is fine. There is more than one way to skin a rabbit. Many times, during my
early days in C++, rather than creating a shiny new class inheriting from several other
classes, I simply created a class which had objects of other classes inside of it. Depending
upon what you have to work with and what you are trying to do, this can be a valid
approach.
Let me try to clarify the previous statement by looking back upon our C++ application
from Book One. We kept the C++ version (both RMS Indexed and RDB) very close to the
C version to make jumping the hurdle easier for those readers who had neither worked
with C or C++. The C++ OOP purists probably have a contract out on me now for showing
you an example like that.
If we wanted to be a little more OOPish we would have created several C++ classes.
The first class would have been an FMS class containing methods for each FMS function
call, all of the needed workspace and FMS initialization. The RMS version already did
have a single class for each file we were working with. Then we would have made the
entire application a class, embedding objects in it for the FMS class and each file class.
This would have been far more OOPish than what I did.
Basics of Java 1-15
The elite purists would have developed an FMS class, a generic RMS indexed file class,
then inherited from those classes while creating a single application class. All procedural
type functionality would have been completely concealed inside of class methods and most
of the data for the class made private.
Don’t shake your head or laugh. I’ve seen it done. Upon rare occasion I’ve been forced
to do it when working with 3 party C++ application frame works. You will run into manyrd
in the Java world who do development just like that. Damn the maintenance
programmer, code speed ahead! Part of this mentality is forced upon you by Java itself.
Every application has to be a class with a main() method. Every applet has to be a class
with a specific list of methods provided as well.
The syntax in Java for one class to inherit from another is quite different.
public static class MyClass extends MyBaseClass
The keyword “extends” tells the compiler to inherit from the single class name
following. The class MyBaseClass could also have a class inheritance buried in its
definition. I really don’t know how far back the limit is. I do know that mentally, most
developers cannot grasp more than two levels back. GUI tools with class browsers remove
that burden from the developer. You can nest as deep as you want and just keep clicking
away to find the method you think you need.
You do need to be aware of two other keywords when inheriting: this and super. These
keywords will be familiar to those of you who have done a lot of C++ coding, at least the
“this” keyword will be. Use the “this” keyword inside of class methods when referencing
class members to indicate you want the class members from this class. You use “super”
when you want the members from a parent class.
At first blush it may seem really stupid to code methods inside of a class, yet access
the class members via “this”. It all goes back to the OOP philosophy of planning for
inheritance. If one of your data members was unfortunately named “x” or “y” or some
other common variable name, the poor Schmoe who inherited from your class to make a
better class, who happened to use the same member names would be in a lot of trouble.
Perhaps they didn’t use those same names, but chose to declare local method variables x
and y. Without the keywords this and super, they would have no method of informing
Java that they wanted the variables from outside of local scope.
Be very careful when designing classes expecting to use this and super. These
variables cannot be used inside of static methods. The compiler will spit up if you try to
declare your classes in the same source file where a static main will be referencing them.
Let me give you an example which works to clear up my above explanation.
1-16 Basics of Java
DummyClass.java
public class DummyClass {
public int x;
public void printBoth() {
int x;
x = 22;
this.x = 7;
System.out.println( "local x is " + x);
System.out.println( "class member x is " + this.x);
} // end printBoth method
} // end definition of DummyClass
TestScope.java
public class TestScope {
public static void main(String args[]) {
DummyClass h = new DummyClass();
h.printBoth();
}
} // end class TestScope
$ javac DummyClass.java
$ javac -classpath [] TestScope.java
$ java "TestScope"
local x is 22
class member x is 7
Admittedly we haven’t covered a lot of the Java language yet, but you should be able
to muddle through these simple source files. In order to be able to show you how to use
“this” I had to declare my classes in two separate source files.
Our first highlighted line shows you the class member declaration of variable x. The
second highlighted line shows you the local method declaration of a variable using the
same name. The rules of scope only let the method printBoth() look at the local x variable
unless we use the “this” keyword to force it to look outside of local scope.
When compiling my second class source file I had to use the -classpath command line
option to tell the compiler where it could find my class definition. This was required since
I didn’t put the class definition into the default Java path or a JAR that Java knew about.
(Eventually we will get to covering JAR files so don’t worry if you are unfamiliar with the
term.)
In order to run the class I had to put the name in quotes so the Java environment
would be able to deal with the fact the class file name wasn’t an exact case match. As you
can see from the output the local x value was 22 and the class member x value was 7.
Basics of Java 1-17
1.17 Polymorphism
This big word is used to impress people who know nothing about it. I cannot
remember how many meetings I sat through in the early days of C++ where sales reps for
C++ development products took it upon themselves to say this word as many times as
possible with MBA’s in the room. It was even more entertaining listening to these same
people, whose eyes glazed over as soon as their attention was diverted from the four color
glossy overheads, try to use it in sentences for budget approval. To understand just how
entertaining it was you would have to rent one of the old Star Trek movies. I don’t
remember the title, but it was the one where they came back to the past to find whales.
One of the sub-plots in it had Spock trying to learn how to use profanity, sputtering
phrases like “I will the Hell”.
Polymorphism isn’t new. The word is relatively new and cumbersome, but the concept
isn’t new. A polymorphic function cares little to nothing about the data passed into it.
From the earliest days of BASIC we had the PRINT statement. It didn’t care what kind
of native data type(s) you passed into it, simply found a way to print them. COBOL
programmers had the DISPLAY statement which will print anything that isn’t a raw
binary format. Assembler programmers on the VAX platform had SYS$FAO(). All of
these are polymorphic functions, and none of those languages are considered OOP
languages.
1.18 Source Code Organization and Style
It was a truly sad day when the Java documentation and examples started to surface.
All of those C/C++ developers who placed the opening curly brace for scope definition on
the same line as the method or class name, that were cast out of the C/C++ world for doing
that, apparently went to work on the Java project. This makes for some truly unreadable
code. It is also one more significant reason to put your opening curly brace on the line
below when working with C/C++ so you can tell at a glance what language you are
working with.
Source files for Java must occur in this order:
Packages (If any)
Imports (If any)
Class statements
The first class must be the same name as the source file. The class MyClass must be
in a source file named MyClass.java. While you can declare multiple classes in the same
source file, do not declare multiple public classes in the same source file. This is begging
for disaster, even if your compiler version will let you do it. You can have any number of
private or embedded classes in this source file. Remember back in Book One when we
were talking about nesting record definitions inside of record definitions vs. group
definitions? You can do the same thing with class definitions, only these definitions are
declared externally.
1-18 Basics of Java
1.19 Modifiers for Data Types and Methods
There are two groups of modifiers for data types and methods. You will always hear
this referred to as “data type” instead of “class”. In many situations you can use these
modifiers on the built-in data types. The first group effects storage and lifetime. The
second group effects access.
Storage and Lifetime
abstract, final, native, static, synchronized, transient, volatile
Access
private, protected, public and the unnamed default
We have already covered abstract earlier in this text. This is in a large part equivalent
to the C++ keyword “virtual”. It flags classes and methods stating that there is absolutely
no implementation for them. You must provide the implementation when inheriting from
this class. Abstract classes can contain only constants and methods which are flagged as
abstract.
Final is a poorly chosen name. It means constant. You must initialize any variable
at the time of declaration when declaring it final and that is the last value it will ever
have.
Native is a modifier we are going to beat to death with this book. It flags a method as
being written in C. Write this day down. That is the only time you will ever read native
being described that way. Every book I have ever looked at uses the politically correct
phrasing of “implemented in other languages, such as C”. That phrase scores pretty high
on the Bullshit Meter. Other than the javah tool to create headers for use with C, I don’t
know of any tool released with Java which will let you generate headers for COBOL,
BASIC, or FORTRAN. If you ever find one, and it has been ported to OpenVMS, please
feel free to email me. When people want to salvage code from these languages for use with
Java the standard answer is “write a bogus wrapper function in C to call your function
written in (insert language here).”
Static has some really nice politically correct descriptions published everywhere
around the net and in print. These descriptions tend to rate very high on my Bullshit
Meter as well. This is how Java tells the world (and the VM) that no matter how this
declaration looks, it really is global. When you declare a data item static in a class, only
one copy exists across all instances of that class.
Declaring data items as static inside of a class definition is something the sober don’t
do unless they have consumed a sufficient quantity of nicotine. The reason is you need to
tell Java just how to initialize the static variable with a special “static { }” area in the class
definition. You cannot initialize it in the class constructor because there is only one copy
of it everywhere. If you try initializing it in the class constructor it will be wiped out every
time a new object is created. The classic example of static data items is reference
counting.
Basics of Java 1-19
TestStatic.java
public class TestStatic {
public static int theCount;
public TestStatic() {
// every time an object is created we
// bump the counter
theCount++;
} // end testStatic constructor
protected void finalize() {
// wouldn't be a very usefull counter
// if we didn't drop it every time we
// killed off an object.
theCount--;
} // end finalize method
static { theCount = 0; }
} // end class TestStatic
In the above class definition you see how we declared our static variable. In the class
constructor we increment it. In order to be an actual reference counter instead of just a
creation counter, we have to decrement the count when an object goes away.
The very last highlighted line is critical for us to discuss. I, didn’t need this. Most of
the time you won’t. By the time you do need it, you won’t remember how to do it. Java’s
default value initialization tends to make people sloppy, this is the one thing I really hate
bout Java. As long as you are always declaring numeric static items you want initialized
to zero, you will never need that last line. Java does this for you. The first time you need
to declare a static String item with a value other than null you will be fine since you will
find the way to get the value in during declaration. If you were lucky enough to be a C++
programmer before you learned Java you will remember that C++ forced you to provide
a value at the moment of declaration. If we needed to start with the value 8 we could do
as follows:
TestStatic.java
public class TestStatic {
public static int theCount = 8;
public TestStatic() {
// every time an object is created we
// bump the counter
theCount++;
} // end testStatic constructor
protected void finalize() {
// wouldn't be a very usefull counter
// if we didn't drop it every time we
// killed off an object.
1-20 Basics of Java
theCount--;
} // end finalize method
} // end class TestStatic
Most of the books I have seen on Java over the years tend to show the first method of
initialization because that one is Java’s own. The second method, highlighted above,
shows the way you would declare each and every static class member when working with
C++. The method also works for Java. I humbly advise you always use this last method
and always provide a value.
Synchronized applies only to methods in a class. If you are unfortunate enough to
have to use threads in Java you will live and breath the synchronized keyword. This
restricts method execution to only one thread at a time. Usually you are doing a lot of
complex math or other such thing which creates a lot of temporary variables that are not
thread safe. Putting synchronized on a method doesn’t also make it static. In most
threaded applications you will find synchronized used in lock step with static on member
methods.
Transient is probably one of the more politically incorrect qualifier names you will find
in Java. Programmers coming from other 3GL languages are used to referring to stale,
left over data drifting through their application as tramp or transient data. When you
speak of the transient modifier for Java it means “do not save”. By itself the modifier is
of little use. It only takes effect when you are serializing data. (Serializing is the ability
of an object to store itself on disk in some special form that can later be read back in, not
necessarily by the same application.)
Volatile basically means all bets are off. Since most Java developers are OOP purists
they typically only put this qualifier on a variable written to by multiple threads. Much
of the original intention was to indicate that this variable or region of memory would be
changed by external hardware or the operating system.
The accessibility options are kind of strange for developers coming from C++, primarily
because of the “default” access. Members and methods declared private do not get
inherited by other classes, they are only visible in the class which declared them. This
part, at least, is consistent with C++.
Protected members and methods get inherited by any class using the class as a base.
Oddly enough, any class in the same package has access to them. I know we haven’t really
discussed packages in any significant detail yet, but you are aware that a package is a
group of things stuffed into the same container. In a way you could look at a package as
a library, but that will cause a lot of confusion when you try to decipher what these access
modifiers control.
Public is a free-for-all. Anything can access it from anywhere as long as they provide
a path to it. Public members and methods get inherited. They can be access anywhere
from inside or outside of the VM. This is why the main class in every java source file
needs to be declared public. So you can invoke it from the command line.
Basics of Java 1-21
The default access is the one which causes a lot of hardship. When you are working
within the same package or directory it is just like public. Many developers initially
confuse it with public access, but it is not. Classes which are not part of your class cannot
inherit default protection members or methods.
1.20 Packages
I know, this access stuff is a lot to chew and swallow in one setting. It is even harder
if you don’t have a feel for what a package is. Most books I have read on Java really gloss
over packages. Most are written by people who have worked with the language for many
years and find packages as natural as object libraries on a linker command line. Let me
try and paint a mental picture for you about packages.
When we covered RMS indexed files in Book One, I spent quite a bit of time covering
indexed files with multi-typed records, even though we didn’t create any files of that type.
I did this for several reasons. The first of which was that you will encounter them if you
work on OpenVMS long enough. The second reason was to explain why they came into
being. Packages are another one of those things which make absolutely no sense unless
you understand the why behind it.
Had Java never made it to the internet, it probably never would have had packages.
They would have made do with something very similar to the object libraries all 3GL
languages have. In an embedded environment which doesn’t connect to the outside world
there is simply no reason for their existence. Many of you reading this book will have
spent much of your careers writing applications which for all intents and purposes were
stand alone. Yes, they got data from other systems in some prescribed message or file
format, perhaps even shared a database, but they didn’t share execution.
Place yourself in a language designer’s shoes for a little while. Management dropped
on your desk a napkin from lunch. On it was scribbled the following requirements.
Design a language which can run anywhere on the internet, invoke routines from
anywhere on the internet and never have a naming collision. The manager said “Make
it work” and walked off.
Imagine for a moment, just how many bank Web sites would have a Java class named
Amortize on their page. Just how are you going to stop a collision even within one bank
when the Amortize class created by the car loan group is for 5 years and the home loan
group is for 30 years? You could make them hard code TCP/IP addresses, but that
probably wouldn’t work either.
Thankfully, the internet already had significant problems with addresses and created
DNS (Dynamic Name Services.) This is what allows you to key www.hp.com in your
browser window and actually get to whatever IP address the site is using today. Well,
using even that address still wouldn’t help the bank running all of their Web sites on one
server needing multiple Amortize classes.
1-22 Basics of Java
Why not just extend the DNS concept though? Don’t actually change the DNS servers,
but use the concept inside of your Java language. In my simplistic verbiage, this is what
gave us packages. A way to group classes together so we wouldn’t have naming collisions
from other locations on the Web.
Once you have come to the conclusion that you need packages, how do they function?
Are they just a big pit you toss everything into, like an object library, or should they have
dynamic functionality? At first blush 3GL developers would say they should be treated
like an object library. This would be a bad thing though. Have you ever worked with C
and tried to get object libraries from 3 different vendors to play nice together? I have. On
the PC platform it really sucked. Besides the header file name collisions, each object
library was always compiled with different alignment and optimization parameters. I
stayed up late many nights getting things like that to play well together.
Hence, came the design decision that classes inside of packages could use each other.
Classes from other packages could import functionality from your package. You could
control the level of functionality they were able to import by a series of access control
keywords. In my humble opinion, this is how packages came to be. I’m sure that there
is an official story somewhere in the archives of Java documentation, but this is the story
I like, so it is the one I’m telling.
1.21 Interfaces
Interfaces were Java’s way of admitting leaving out multiple inheritance wasn’t such
a good idea. While you will see interfaces used widely, they should really be called
something like “Napoleonic Rules”. Other than a list of rules and constants for the next
Schmoe to actually code, interfaces buy you nothing. No code can exist in an interface,
just abstract methods and constants.
public interface MyRules {
void sayplease();
}
An interface can “extend” other interfaces, but cannot extend a class. A class uses the
interface by telling the compiler it “implements” the interface. You can “implement” any
number of interfaces.
public class MyClass implements MyRules {
public void sayplease() {
......
}
}
The beautiful part about multiple inheritance with C++ is you could put most of the
implementation issues in the classes you inherited from. The shiny new class only had to
actually implement method overrides when it needed a method to do something different.
Basics of Java 1-23
Imagine, if you will, a pair of interfaces with 15 methods each. Imagine you have to
create a class which needs to implement both of those interfaces. The compiler is going
to force you to provide the code for every one of those interfaces. There may very well be
only two that your application will ever use, but somebody mandated you use those
interfaces, or you needed the constants provided by them. It is a sorry state, but one we
must endure when working with Java.
1.22 Threads
I’m going to touch briefly on threads so you have some exposure to the topic. On the
OpenVMS or any robust platform, I highly advise you avoid threads completely. Threads
are what you get when an operating system wasn’t designed to be a robust multiprocessing
system from the ground up. OpenVMS was designed from the ground up to be a robust
multiprocessing system. Unix and DOS were not. The GUI versions of DOS were task
switchers. I have severe doubts about the version of Windows XP Pro I have on one
machine in this office as well. Those doubts are fostered by giving the machine the
Microsoft salute (<CTRL><ALT><DEL>). The button at the bottom reads “Task list” and
when you click it you get a list of images not accompanied by process Ids.
What is strange is that Unix and the C language started out on a DEC PDP machine.
I do not know of an OS from DEC for that hardware which did not do multiprocessing
correctly (RSTS/E, RSX-11, RT-11). There should have been an inkling, then again, Unix
was originally designed to be a single tasking system which allowed a few users on for
maintenance. It’s real purpose was to run switching software. When you don’t need
much, threads work, so does task switching. When you need robustness you need an OS
which was designed from the ground up to be multiprocessing.
Threads are completely different from multiprocessing, though people tend to talk
about them as if they were multiprocessing. The images conjured up with threads tend
to be either cloth or yarn. Many threads woven together making something of substance.
Not every thread starts in the same place, nor does it contact many of the other threads.
Some threads are joined to the ends or middles of other threads, relying on them for points
of reference in the greater whole.
Multiprocessing, at least from the way in which you see and use it on OpenVMS is
completely different. For purposes of visualization, every process starts at the same point.
Processes can create as many processes as the user name in the UAF will allow. When
you spawn a sub-process, it has its own life, but carries with it luggage stating it cannot
outlive its parent. If the parent, or creating, process dies spastically OpenVMS knows
about all of the sub-processes it created so it forces them into ritual suicide.
In the very early days of C programming there were some fine magazines available
for subscription. Magazines like “The C Gazette” and “Programmer’s Journal” to name
just two, made you proud to be a programmer. Excellent writing, in-depth articles, and
almost no hawking of products by the writers. These were the good days. I don’t expect
to ever see them again. One theme which kept coming up in the articles over the years
1-24 Basics of Java
were tools and techniques for finding and eliminating “dangling threads”. The definition
of a “dangling thread” most often offered up was a thread created by a parent thread and
the parent thread no longer existed. Due to the way threads were implemented, the OS
had no easy or direct method of killing that thread off. It would sit out there consuming
resources until it found a way to end itself, or your box became so bogged down you had
to reboot.
Back in Book One I exposed you to the following command:
$ SHOW SYSTEM
If you have an account with OPER priv, or better yet, the privs of God, issuing that
command gives you a list of processes on the machine, no matter who created them. Most
importantly, it gives you the PID for each process. If the only thing you wish to find is
associated with an interactive user, you can use:
$ SHOW USERS/FULL/NODE
The /NODE qualifier is only needed if you are on a cluster and wish to restrict the
output to only those users on your current node. Once again, you will get the PID
associated with the process.
Let me provide you with an actual example of what I’m talking about. In order to do
this I need two terminal sessions. One to issue control commands from and one to kill off.
Here is the info of my control session:
$ show term
Terminal: _TNA6: Device_Type: VT400_Series Owner: _TNA6:
Username: HUGHES
Remote Port Info: Host: 192.168.0.22 Port: 3106
Input: 9600 LFfill: 0 Width: 132 Parity: None
Output: 9600 CRfill: 0 Page: 32
Terminal Characteristics:
Interactive Echo Type_ahead No Escape
Hostsync TTsync Lowercase Tab
Wrap Scope No Remote Eightbit
Broadcast No Readsync No Form Fulldup
No Modem No Local_echo No Autobaud Hangup
No Brdcstmbx No DMA No Altypeahd Set_speed
No Commsync Line Editing Insert editing No Fallback
No Dialup No Secure server No Disconnect No Pasthru
No Syspassword No SIXEL Graphics Soft Characters Printer port
Numeric Keypad ANSI_CRT No Regis No Block_mode
Advanced_video Edit_mode DEC_CRT DEC_CRT2
DEC_CRT3 DEC_CRT4 No DEC_CRT5 No Ansi_Color
VMS Style Input
It is very important to remember your terminal when doing things like this. Those
who don’t remember the terminal they are working from when trying this will issue a
STOP/ID on the wrong process and suddenly find they aren’t logged in anymore. After
logging in as myself in another session my system looks as follows:
Basics of Java 1-25
$ show users/full/node
OpenVMS User Processes at 12-JUL-2005 11:43:44.23
Total number of users = 1, number of processes = 2
Username Process Name PID Terminal
HUGHES _TNA6: 000003E7 TNA6: (Host: 192.168.0.22 Port: 3106)
HUGHES _TNA7: 00000851 TNA7: (Host: 192.168.0.22 Port: 3558)
Keep in mind the terminal ID for my control window. This helps me get the correct
PID.
$ set host 0
Welcome to OpenVMS (TM) Alpha Operating System, Version V7.3-1
Username: guest
Password:
*****************************************************
* *
* WELCOME.TXT *
* *
* Welcome to the Alpha node LGKL1 run by Logikal *
* Solutions. *
*****************************************************
Last interactive login on Friday, 21-JAN-2005 14:38:08.49
You have 12 new Mail messages.
Your password has expired; you must set a new password to log in
New password:
Verification:
Password found in system dictionary; please choose another string
Please try again or press <CTRL/Y> to abort login
New password:
Verification:
$ show users/full/node
OpenVMS User Processes at 12-JUL-2005 11:46:24.92
Total number of users = 2, number of processes = 3
Username Process Name PID Terminal
GUEST GUEST 00000856 RTA1: (1025::HUGHES)
HUGHES _TNA6: 000003E7 TNA6: (Host: 192.168.0.22 Port: 3106)
HUGHES _TNA7: 00000851 TNA7: (Host: 192.168.0.22 Port: 3558)
$ stop/id=851
$ show users/full/node
OpenVMS User Processes at 12-JUL-2005 11:47:41.66
Total number of users = 1, number of processes = 1
Username Process Name PID Terminal
HUGHES _TNA6: 000003E7 TNA6: (Host: 192.168.0.22 Port: 3106)
In order to simply create another process for the terminal I used the SET HOST
command we talked about in Book One. Yes, I could have done a spawn of some program,
but the example works well for what we wish to show.
1-26 Basics of Java
After logging in as GUEST, and finding out the password had expired, my system
showed three users. Notice that the GUEST user was assigned its own PID. Since the
process was using the same terminal as the process which created it, a funky RTA
terminal number was assigned.
Back in my control session, I stop the PID for the parent process. OpenVMS forced the
GUEST process to commit ritual suicide when its creating process went away. This is
multiprocessing done correctly. It provides for the most robust and secure system. You
can do similar things on IBM’s OS/390 which now has some kind of OZ name. They did
multiprocessing correctly as well.
Please, don’t take just my word for it. Conduct experiments yourself. Take a look at
the history of a product once called DECThreads. This product/library/package got written
in the later years of DEC when Unix developers wanted to start porting their software to
OpenVMS. It seems that just about every package used threads in some manner or other.
Trying to bend those packages into environments which had robust multiprocessing
capabilities was a complete redesign. In response to that need DECThreads got written.
It doesn’t “port” thread software to robust multiprocessing. It implements threads under
the protection of a robust multiprocessing OS.
The above example is a pretty perfect example for you to try on other platforms. There
used to be a utility on most Unix boxes which would basically provide the same
functionality as SET HOST 0 does under OpenVMS. This would allow you to log in as
somebody else without killing of your original process. If somebody did kill off your
original thread, the thread for the new user became disconnected from the terminal,
drifting aimlessly in the breeze of the cyber world.
When writing Java on OpenVMS, don’t use the thread portion of Java. In later
chapters we will be coding tools which will let you use LIB$SPAWN(). You are familiar
with LIB$SPAWN() from Book One. One thing you probably haven’t done though is log
into another session and use the SHOW USERS/FULL command to see what happens
when you go into one of the menu options.
The only piece of the Thread package which you should consider using is the sleep()
method. Java buried this function in that package. Since we don’t want to write all of the
code to set this up ourselves, and it is a stand alone feature (Doesn’t require you to use any
other part of the Thread package) it is safe to use. This method will also allow you to catch
an interruption exception like the WAIT statement in BASIC.
1.23 Exceptions
What are exceptions you ask? This is a term Java borrowed from C++ for error
handling. On the surface it looks very much like the error handling in C++. You enclose
a block of code with a “try” and follow it by a “catch”. That is pretty much where the
similarity ends though.
Basics of Java 1-27
Under Java, exceptions are a class. Remember, everything is a class in Java except
the most basic of native data types. All exceptions are derived from the Throwable class.
When you declare a class method which could potentially throw an exception you must
identify the exceptions it throws in the declaration.
Throwable has two sub-classes: Error and Exception. Classes derived from Error
typically have Error as their suffix while classes derived from Exception are given
Exception as a suffix. The Error class is typically used for hard systems type errors such
as running out of memory while the Exception class is typically used for things a program
could recover from. There is a lot of documentation available on-line and usually bundled
with most distributions about all of the different exceptions and errors.
Because these are classes and not specific numeric values, exception handling can be
pretty tricky. The list of caught exceptions is processed sequentially when an exception
is thrown. If you derive your own exception from the class IOException, but catch
IOException first in the catch list, that path will always be taken. Most compilers today
will flag this as a compilation error, but older implementations may not.
The fly in the ointment for new developers is the finally clause. This is not the all-
else-fails portion of exception handling. The finally clause will be executed for a try block
no matter how the try block completes. This concept is tough for developers coming from
BASIC to follow. Even if you branch out of a try block with Java’s version of the GOTO
statement (continue label, break label or simply a return statement) the finally block will
be executed. If you have an exception get thrown in your try block, the finally block will
be executed whether the exception is caught or not.
What happens if the thrown exception isn’t caught? Java executes the finally clause
for your try block, passes the exception up to the next calling/enclosing block, and repeats
the process of trying to catch the exception. The finally clause is executed for each block
of code the exception bubbles up through un-caught until Java is forced to abend your
process or the exception is finally caught.
All exceptions have the following methods available to them since they are all derived
from the Throwable class:
getMessage() to obtain the text of the error message
printSatackTrace() to print a stack trace showing where this occurred
toString() to show the exception name along with the getMessage() result
The throws clause on a method definition is more than just an ornament. Any
exception which is not derived (inherited) from the Error class or the RuntimeException
class must be either caught in the method which throws it or be listed in the throws clause
of the method. The compiler isn’t forward looking enough to see if the caller is catching
the exceptions, but it is forward looking enough to enforce this rule within the compilation
of the method. If you throw an exception in your method and don’t catch it, you will
receive an error message stating the exception must be listed in the throws clause of the
method.
1-28 Basics of Java
I know, if you don’t come from an OOP background that last paragraph is a lot to
digest. Error handling, with any language, is something programmers migrate towards
slowly. Yes, we are all taught in college that we should test our applications with a 4 or
5 year old at the keyboard because they will enter complete garbage. The reality is that
first we make it work, and as time allows, we make it work well. In the old days of BASIC
programming when every line had a line number and the stack dump would give you the
complete information including the line number, this worked well. You coded up your
program, then added error handling at the end as your testing generated stack dumps.
While it was time consuming, it did work.
Purists will state that you need to create your own exception class for any abnormality
which could arise, and catch it in your program. Purists usually don’t have to get 40 hours
of work done by tomorrow morning. The old trick of having your methods return
numerical values which your application tests still works in Java. Most developers new
to Java will use try-catch-finally blocks inside of their methods, then return a value from
the method indicating success or failure just like we have done with every 3GL since the
dawn of time.
1.24 JAVA$CLASSPATH
Most developers coming from the lesser platforms will be familiar with a symbol called
“classpath” if they do any Java development on those platforms. Most of the Java
commands also add a switch “-classpath” for you to specify the path to look for class, JAR
and ZIP files when Java goes looking for classes to dynamically load.
Symbols are somewhat limited in their use. OpenVMS provides an additional logical
for the Java environment known as JAVA$CLASSPATH. You can define this logical
anywhere in your LNM$FILE_DEV search list. The first definition found will be the
definition used by Java in your process. This logical can be a comma separated multi-
value logical. The Java environment will translate as many iterations as it needs to find
what it seeks. As with all multi-pathed logicals, you are responsible for making sure what
you want to execute isn’t hidden by an item of the same name found earlier in the search
path.
1.25 A Little Lecture on Strings and References
Those of you who paid attention to our discussion about references under C++ are
going to bleed pretty profusely when trying to learn Java. When you passed a String class
via reference under C++, the called function got to manipulate the actual object. When
you hear about everything being a reference in Java it is quite natural to assume you are
manipulating things just like in C++. DON’T ASSUME!
Basics of Java 1-29
TestString.javaimport java.util.Arrays;
public class TestString
{
public static void main(String[] args)
{
String aString = "abc";
System.out.println("|" + aString + "|");
rightPadString( aString, 8);
System.out.println( "After padding |" + aString + "|");
aString = rightPadStr( aString, 12);
System.out.println( "After second padding |" + aString + "|");
//
// How do we create a dynamic string of stuff like we did with BASIC?
//
int i = 24;
char c[] = new char[i];
Arrays.fill( c, '*');
String s = new String( c);
System.out.println( "Our dynamic string of characters " + s);
} // end main method
private static void rightPadString( String s, int i) {
while (s.length() < i) {
s += " ";
} // end while loop
System.out.println( "String before returning from pad |" + s + "|");
} // end rightPadString method
private static String rightPadStr( String s, int i) {
while (s.length() < i) {
s += " ";
} // end while loop
System.out.println( "String before returning from pad |" + s + "|");
return s;
} // end rightPadStr method
} // end TestString class
$ javac "TestString.java"
$ java "TestString"
|abc|
String before returning from pad |abc |
After padding |abc|
String before returning from pad |abc |
After second padding |abc |
Our dynamic string of characters ************************
It is a tiny little example program, but it provides quite a bit to rant and rave about.
The first highlighted line is a method call which attempts to pad a string on the right until
it is a designated number of spaces long. Those coming from C++ and used to how passing
a reference works in that language would attempt to code this method in exactly this
manner. The line highlighted below it is how you actually have to code the method.
1-30 Basics of Java
Take a look at the output. We pass in “abc” and the string created inside of the
method looks as we expect. When we get back to our main method we see the original
string was not altered. In other words, the reference was passed by value. (It’s OK if you
feel you need a drink at this point.) When we start working with the Java Native
Interface (JNI) the definition of “reference” will get even muddier.
Why do I bother showing you how to pad a string? When we get to the report portion
of our application you will learn that Java was never meant to be a business language.
Java, prior to version 1.5.x didn’t provide any means what-so-ever to create a nice
columnar report. The NumberFormat class gives you back a string without any leading
or trailing spaces. It took Java over a decade to catch up to the 1970's.
My last little example in this program is how to create an arbitrary string of
characters. I tossed this in because I had just read yet another missive about how easy
Java makes strings. They were lamenting about the days of C and having to use sprintf()
to create strings, then overwriting the destination buffer because it was too small. Even
with that potential disaster, sprintf() provided a lot more functionality than Java. BASIC
provides the best string handling with a distinguished nod to COBOL’s UNSTRING verb.
Creating a right sided histogram of stars to generate a simple chart was trivial with the
STRING$() function of BASIC. Getting an arbitrary string of spaces to blank something
out was even less effort with SPACE$(). COBOL gave you the key word SPACES and it
did everything for you. Java didn’t bother to look at what came before and that is its
biggest downfall.
One thing you should never call Java is “efficient”. It wastes system resources like
dual quad carburetors waste gas. Just take a look at what had to be done to create the
string of asterisks. First we had to dynamically create a character array. Then we had
to use a method of the Arrays class (which is different from the Array class) to fill the
array with our desired character. If we wanted it in string form we had to either use the
toString() method hidden away with our array, or we had to dynamically obtain yet
another string. Either method left a StringBuffer object laying around waiting for garbage
collection. It doesn’t sound like a lot until you remember that garbage collection generally
runs at “system idle” time as defined by the VM implementor. Now, think forward to a
method which has to create hundreds or thousands of these things for output before it
returns. The return would be the first opportunity for the “system idle” process to execute.
1.26 Java Follow Up
Java is a language which currently has an ocean of marketing hype behind it.
Languages which achieve this level of hype usually stay in vogue for 10-15 years. As a
result of these two truths, you, as an OpenVMS developer, are going to be forced to write
applications in Java. It won’t be because Java as a language is buying you much over the
3GLs you are already skilled with. There will be a “management decision” which will
drive this change.
Basics of Java 1-31
In the world of “management decisions”, this one will be a train wreck of biblical
proportions, not because Java is a bad language or has any more short comings than any
other language we have covered so far, but because of the premise behind the decision.
Management will have seen for quite some time in the four color glossy weekly trade
magazines Java all over the place. They will make a not too incorrect assumption that
Java is now pretty much the only language being taught in colleges.
What the four color glossies didn’t tell management was the way the language was
being taught. Very few schools teach their students how to sit at an editor and code Java
from scratch. Most of them teach one of the GUI tools. Most of you reading this will have
been to college and will realize that students tend to sleep through most of the boring
lectures. When you actually have to code the stuff is when you learn it. With the pick &
point GUI tools the students code almost nothing, which means they retain close to
nothing.
Think back to the days of your COBOL classes. At least one of the programming
assignments at the end of each chapter was a program with only a handful of lines that
were different from the program covered in the chapter. Were they really testing your
COBOL metal? No. But you actually had to key all of that stuff in before compiling. Then
you had to endure the compiler informing you of your typos. In the end, you learned
COBOL by repetition.
Java developers using pick and point GUI development tools don’t learn the language,
they learn the tool. It is because of this fact there is a massive market for “middleware”
now. Middleware is the crack cocaine laced nicotine cigarette of today’s IT industry. Once
you let your company start using it you have created an addict. The truly shrewd
middleware vendors are/will be making the license part of the maintenance agreement.
As soon as you stop paying for maintenance, your license expires. Laugh all you want at
that statement, then go read the fine print of your maintenance contract.
Even with all of these environmental faults, Java could be a very good language. On
the OpenVMS platform it has some serious hurdles to cross. There is little to know
support in the current release of Java on OpenVMS for accessing System Services, RTL
(Run Time Library) routines or RMS indexed files. There are a few example source files
of how to do this included with the release, but there is no com.hp.sys$rtl package nor is
there a com.hp.rms package that I can find. I have heard that there are middleware
vendors selling products to let Java access RMS files, but haven’t seen any of them.
Expiring license are nothing new. I was once an owner and user of Visual SlickEdit.
As PC editors went it wasn’t bad. Your license never expired, but the installation program
wouldn’t let you install the product after it had aged for a certain number of years. I found
this out during a wipe and re-install after a hardware upgrade. Consequently, when I
have to work on the PC platform I now use EditPlus 2 because it doesn’t play that hokey
expiration game, I also let everyone I meet who discusses editors know about that
situation.
1-32 Basics of Java
Java does have the ability to eliminate a lot of other language development. It cannot
eliminate the C language since you must use C for the JNI. Java cannot currently be used
safely inside of ACMS servers. Yes, you can use javah to create headers allowing C to call
Java and yes, you could call it from inside of a server. However, if you did that, You would
be limiting the effectiveness of ACMS.
Given the current state of IT, we as professional developers, will find ourselves writing
more and more Java applications. Notice the choice of words there. I said applications,
not systems. Java is not a good language for systems development.
1.27 Exercises
1. What are the two functional synonyms Java has added to replace the goto statement?
2. What is garbage collection?
3. What is multiple inheritance?
4. What passes for multiple inheritance in Java?
5. What is the definition of a core data type?
6. How big is the long data type in Java? In C?
7. If you need a numeric data type which doesn’t neatly fit into a core data type, what
two classes can you use?
8. Does Java initialize all class member variables? Local variables?
9. What is the default value for a boolean variable?
10. What does NAN stand for?
11. How big is a character in Java? What type of value is it?
12. What is a reference in Java?
13. Does your program actually own the variables you declare in it?
14. Does Java have an include directive?
15. How do you obtain class definitions which exist outside of your source file?
16. What is a package?
17. What is the format of a package name?
Basics of Java 1-33
18. What is the name of the method Java gives to the destructor?
19. What access clause or keyword must be on the destructor method in Java?
20. Can a class have more than one constructor?
21. What characters represent the conditional operator?
22. What is the syntax of the special comment recognized by javadoc?
23. What is an abstract class?
24. What keyword is used in the Java syntax to indicate one class inherits from another
class?
25. What does the keyword “super” refer to?
26. What command or utility do you use to compile a Java source file?
27. What is a polymorphic function?
28. In what order must the statements appear in your Java source file?
29. What are the two groups of modifiers for data types and methods?
30. What does the native modifier on a method indicate?
31. When is the static section of a class executed? How often is it executed.
32. When does the transient modifier take effect? What does it do?
33. Where are methods and members declared with the “private” keyword visible?
34. Where are “protected” methods and members visible?
35. Why were packages added to Java?
36. What is the fundamental difference between exceptions in C++ and exceptions in
Java?
37. When will the “finally” clause be executed and under what conditions?
38. What happens if an exception is not caught in the current class method?
39. If the method you write could generate an exception which you don’t catch in that
method, what do you need to do?
1-34 Basics of Java
40. What is the purpose of JAVA$CLASSPATH?
You have been reading an excerpt. Please visit http://www.theminimumyouneedtoknow.com to find out more about thisbook series and how to purchase books by this author.
Chapter 2
Using RTL and SYS Calls
2.1 Goal of This Chapter
This book is going to lay the groundwork for you to create all of the tools you need to
make Java a usable language on OpenVMS. While I’m certainly not going to code a
method for each and every SYS$ and RTL function existing on the platform, we are going
to code a package which contains methods for most of the functions used in prior versions
of our application. We barely dented the surface, but their should be enough for you to
begin learning Java by cutting and pasting to add new methods for additional function
calls.
We will create VMS RTL classes for lib$spawn() and lib$set_logical(). In addition we
w ill create a VM SD ate class w hich w ill contain the m ethods for
lib$init_date_time_context(), lib$free_date_time_context(), lib$format_date_time(), and
lib$convert_date_string(). The reason we will be splitting the date stuff out into its own
class is I want the class destructor (finalizer in Java speak) to always clean up the date
time context. Due to the nature of lib$do_command() never returning, I won’t be showing
you how to call that funcion.
We won’t be covering calling lib$cvt_dx_dx() in this chapter. The only time you would
need it is if you are reading a file created by older BASIC or COBOL programs. When we
cover interfacing with RMS Indexed files, we will call it there.
It is my hope that you find the journey through this chapter worth your while. I think
it will be much more useful to a seasoned developer than all of the canned 15 line example
snippets you find in other books.
2.2 Order of Development with JNI
When you will be writing Java classes which use the Java Native Interface
development must proceed in the following order:
• Code the Java class
• Create a directory tree if working with packages
• Run javah against the class file to create a header file
• Code your C/C++ program or module
• Create a linker options file for the C module
• Link a shareable image out of your object and options file
• Define a logical which points to your shareable image
After looking at the above list, most of you are probably beginning to understand why
most books on Java choose to talk about creating generic applets and Web pages. The
hack at it - try it - hack at it - try it approach works well for Java applets, not requiring
you to think too far ahead. You actually have to do a little bit of design work when using
JNI.