Java

Beans

Java is a programming language. What makes it so popular is the fact that it's based on "Write once, run anywhere", which means just what it says: It is not optimized for any particular type of computer, meaning it can be run on any system that supports Java. Compiled Java programs have a .class extension. (See the official Java site below for a compiler.)

Another thing that makes Java so popular is, it's supported by the major Web browsers, so you can do applets on the World Wide Web with them, which usually take the form of little pictures that jump a bit.

As far as programming format goes, Java is a lot like C++. It's just a bit sleeker.

Here's the official Java page on Sun's server!

java.sun.com

The official Java "Hello World" program on that website looks like this (sans comments):

class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

The first line indicates that this is a class called HelloWorldApp. (For an explanation of classes, see my writeup Introduction To Object-Oriented Programming.) Because this class is called HelloWorldApp, you must put this program code into a file called HelloWorldApp.java or you'll get an error when you try to compile the code. Sun's own verdict on why you need to create a class reads as follows:

"In the Java language, each method (function) and variable exists within a class or an object (an instance of a class). The Java language does not support global functions or variables. Thus, the skeleton of any Java program is a class definition."

(For further details, see http://java.sun.com/docs/books/tutorial/getStarted/application/.) The fact that Java doesn't support global functions or variables is a good first reason to hate Java. This kind of forced object-building is restrictive. Say what you will about how it makes things more logical and organized, but when you want to start hacking, the last thing you want to do is start worrying about what class this variable or that function is going to get pigeon-holed into.

Anyway, now that we've got our class started, we can create the main program function. In Java, just as in C, the main program function really is called main. Note that in Java, the term method is preferred over "function". Recall that a method is basically just a function that exists as a property of an object; Since, as just mentioned, all functions in Java must belong to an object, all functions in Java are also methods. If this sounds too confusing to bother with, just use the terms "function" and "method" interchangeably, which is what old-school programmers who hate Java (like myself) do, partly because the distinction seems unimportant and partly because we like the way it annoys the hell out of Java developers.

The second line of the program creates the main method. The first part of this line, the word "public", is the access modifier for the method. The "public" access modifier means that this method can be called by any object. Don't worry about this one too much right now.

The next word in this line is "static". Don't worry about this one right now, either.

void is the first part of this line that will be familiar to C programmers. Yes, this is where you indicate what type of value this function is supposed to return; Since it's void, that means that the main function is not supposed to return anything.

Finally, we come to the name of the method itself, "main". After that come the arguments to the method, which there's only one of in this case, a string variable called args that contains the command-line parameters for the program (if any were given). We don't really care about command-line parameters for this program, but we pass them to the main function anyway, just to keep the Java syntax happy.

After all this defining, the pain is finally over and we can get some work done. A curly bracket ({) begins the main function (just as it would in C), and the code of the function begins. In this case, it's a call to the System.out.println function, a function built into Java which acts like C's printf. Now knowing this, that line should be fairly self-apparent.

And finally the program closes with two closing curly brackets; The first closes the main function, the second closes the HelloWorldApp class. And so our first Java application is complete, and ready to be compiled and run.

Here's a simple Java program that demonstrates how to make your own functions in Java! Note that because this program creates a class called DemoFunction, you must put it in a file called DemoFunction.java, or you'll get an error.

public class DemoFunction {

public static void main(String args[]) {

funcname();
funcname();

}

public static void funcname() {

System.out.println("This will get printed twice.");

}}

One other things that I feel I ought to mention is the way Java handles exceptions. This is a concept that comes up fairly often in Java programming, and the terminology is a bit different than what programmers of C might be used to. For starters, let's explain the key terms associated with exceptions in Java.

First of all, an exception is basically just a fancy term for an error. More specifically, it's an unexpected error that occurs when a program runs. In other words, an exception doesn't show up when you compile your program; It's a run-time error, meaning it pops up when the program is running. The Java environment doesn't like exceptions, and tends to get really whiny if they happen. For this reason, managing your exceptions is a good idea.

When an exception happens, the exception is thrown, which means that the exception is passed on to an exception handler, if possible. In Java, you can specify that a function or method may be likely to create a particular type of exception by adding "throws [exceptiontype]" after the name of the function. This tells the Java system to anticipate that the function may create an exception of that type. Note that Java recognizes a specific set of exception types, although there are quite a few of them. To be thrown, an exception must be categorized under Java's "Throwable" class.

So what do you do when an exception is thrown? Not surprisingly, you catch it. To catch an exception means to deal with it. A catch routine in Java is a routine that only runs when a specific type of exception happens. It is not necessary to have specified that a function might throw a particular type of exception to use a catch routine. In other words, you can use "catch" without having to use "throws"; As long as the catch routine is there, it'll work if an exception is generated. Having the throws clause just helps by making it clear that an exception may be expected from a routine.

There are only 6 types of exceptions which MUST be given a "throws" clause in Java. Others can be handled by a catch routine without using the throws clause. These 6 exception types are:

ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterrupedException
NoSuchMethodException

The final key exception-handling term to know is try. When you try something in Java, you're telling the Java environment that what you're doing is expected to create an exception. A try routine is a (usually small) block of code which will pass on any exceptions it creates to a catch routine.

Now, here comes a rule that's good to remember: You MUST have a "try" statement in order to use a "catch" statement, and the inverse is also true: You MUST have a "catch" statement in order to use a "try" statement. (Actually, the latter isn't completely true: You can also use a try statement with a "finally" statement, but don't worry about that right now. Technically however, Java requires you to use either a "catch" or a "finally" statement with every "try" statement.)

That's probably a lot to process right now, so let's try to make some sense of all this by making a small program that deliberately creates and deals with an exception. One kind of exception that's pretty easy to create is ArrayIndexOutOfBoundsException. This is what happens when you try to write outside the bounds of an array. For example, suppose you have an array with three elements in it, and you try to write to the fourth or fifth elements of that array. Since those elements don't exist, they fall outside the bounds of the array, and so attempting to use those elements would create an ArrayIndexOutOfBoundsException. Knowing this, we could make a program that looks kind of like this:

class ShowHowToUseExceptions {

  static int[] OverflowingArray = new int[2];

  public static void main(String args[]) {

    try { OverflowingArray[5] = 5; }

    //Remember, you need to have a "try" statement to use a "catch" statement.
    catch (ArrayIndexOutOfBoundsException oops) {
      System.out.println("Hey idiot, your program made the following exception:\n" + oops);
      }

  }

}

As usual, since this class is called "ShowHowToUseExceptions", you'll need to put it into a text file called "ShowHowToUseExceptions.java" or the Java compiler will cry.

The line that starts with "static int" creates an integer array called OverflowingArray. The [2] at the end specifies that this array will have only 2 elements in it.

In the main routine of this class, we have a try routine which tries to change the fifth element of the array. Since that element doesn't exist, this line will generate an ArrayIndexOutOfBoundsException.

After the try routine, we have a catch routine all ready to catch the exception. Notice the "oops" after ArrayIndexOutOfBoundsException on that line? This is the name that we give to our exception object. In actualiy, an exception (like almost everything else in the horrible object-oriented world of Java programming) is an object, and exceptions are no exception. In the arguments to our catch routine, we're actually passing an ArrayIndexOutOfBoundsException object to the catch statement, and we're calling this object "oops".

Once inside the catch routine, we use our new object, "oops", to create a small message telling the user what exception their program made. And that's it. Sure, we made a serious error, but we caught it and dealt with it using the exception-handling commands available in Java, although hopefully in your programs, you'll use a more productive strategy to deal with your exceptions than simply insulting the user.

Well, that's enough Java for now. Remember, kids, too much Java is never healthy for you, so after you partake of it, do some good strong assembly language (or better yet, machine language) coding for a few 24-hour intervals to purge your systems. Stay smart, and stay safe!

Java and "Write once, run anywhere" are probably both trademarks of Sun, so don't use them for yourself, eh.

Back to the main page