June 19, 2023

Java -- all those words

People have called Java the COBOL of the late 20th century. I certainly agree, and the clutter of words is most of what earns it that reputation. Consider this:
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
First note that we can't just call "println", but must full qualify it as "System.out.println". This is ugly and unfortunate, but it is Java through and through. However that is not what I want to talk about here.

What I do want to talk about is "public static void". Again this crazy verbosity is busy earning Java it's unsavory reputation, but what does all this mean? These words are just the tip of the iceberg and it is our purpose to talk about all of it right here.

void - This is easy (and exactly like void in the C language), it means this function does not return anything.

static - This is Java's weird way of saying that this is a class method. In other words you can call "main()" without first doing "new" to instantiate an object upon which you want to call main. Hopefully you understand the concept of a class method and can just be amused by the strange way that Java declares them.

public - You might like to think that a method (like main) could be either private or public, in which case there would be little to say. You might rightly complain that methods are not public by default (or even private by default), but in Java you don't get to be succinct and rely on default behavior for common cases. The Java designers decided to be as verbose as possible and whenever there was a choice, to thrust on you to necessity to declare everything.

There are actually 4 possible "permission" qualifiers. "public" is the most permissive and means that a method (or attribute) can be accessed from anywhere. "private" is the least permissive and means that the thing can be accessed only from the class within which it is being defined. The other sorts of access that may be considered are access from the package and access from subclasses. "protected" means that it can be accessed from both the containing package and from any subclasses (but not the world in general). With no qualifying word at all, you get access from the class and package, but not from subclasses or the world at large. Note that you always get access from the class.

"final" - This creates a constant. It may or may not be static. A class may be marked as final, indicating it cannot be extended.

It is said that the order in which these words are given can influence what they mean. I don't claim to have given a comprehensive reference guide to all the games that can go on here.


Have any comments? Questions? Drop me a line!

Adventures in Computing / tom@mmto.org