Your first Java program


Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame

Bruce Eckel's Thinking in Java Contents | Prev | Next

Finally, here’s the program. [15] It prints out information about the system that it’s running on using various methods of the System object from the Java standard library. Note that an additional style of comment is introduced here: the ‘ //’, which is a comment until the end of the line:

// Property.java
import java.util.*;
public class Property {
  public static void main(String[] args) {
    System.out.println(new Date());
    Properties p = System.getProperties();
    System.out.println("--- Memory Usage:");
    Runtime rt = Runtime.getRuntime();
    System.out.println("Total Memory = "
                       + rt.totalMemory()
                       + " Free Memory = "
                       + rt.freeMemory());

At the beginning of each program file, you must place the import statement to bring in any extra classes you’ll need for the code in that file. Note that it is “extra.” That’s because there’s a certain library of classes that are automatically brought into every Java file: java.lang. Start up your Web browser and look at the documentation from Sun. (If you haven’t downloaded it from java.sun.com or otherwise installed the Java documentation, do so now). If you look at the packages.html file, you’ll see a list of all the different class libraries that come with Java. Select java.lang. Under “Class Index” you’ll see a list of all the classes that are part of that library. Since java.lang is implicitly included in every Java code file, these classes are automatically available. In the list, you’ll see System and Runtime, which are used in Property.java. There’s no Date class listed in java.lang, which means you must import another library to use that. If you don’t know the library where a particular class is, or if you want to see all of the classes, you can select “Class Hierarchy” in the Java documentation. In a Web browser, this takes awhile to construct, but you can find every single class that comes with Java. Then you can use the browser’s “find” function to find Date. When you do you’ll see it listed as java.util.Date, which lets you know that it’s in the util library and that you must import java.util.* in order to use Date.

If you look at the documentation starting from the packages.html file (which I’ve set in my Web browser as the default starting page), select java.lang and then System. You’ll see that the System class has several fields, and if you select out you’ll discover that it’s a static PrintStream object. Since it’s static you don’t need to create anything. The out object is always there and you can just use it. What you can do with this out object is determined by the type it is: a PrintStream. Conveniently, PrintStream is shown in the description as a hyperlink, so if you click on that you’ll see a list of all the methods you can call for PrintStream. There are quite a few and these will be covered later in the book. For now all we’re interested in is println( ), which in effect means “print out what I’m giving you to the console and end with a new line.” Thus, in any Java program you write you can say System.out.println(“things”) whenever you want to print something to the console.

The name of the class is the same as the name of the file. When you’re creating a stand-alone program such as this one, one of the classes in the file must have the same name as the file. (The compiler complains if you don’t do this.) That class must contain a method called main( ) with the signature shown:

public static void main(String[] args) {

The public keyword means that the method is available to the outside world (described in detail in Chapter 5). The argument to main( ) is an array of String objects. The args won’t be used in this program, but they need to be there because they hold the arguments invoked on the command line.

The first line of the program is quite interesting:

System.out.println(new Date());

Consider the argument: a Date object is being created just to send its value to println( ). As soon as this statement is finished, that Date is unnecessary, and the garbage collector can come along and get it anytime. We don’t need to worry about cleaning it up.

The second line calls System.getProperties( ). If you consult the online documentation using your Web browser, you’ll see that getProperties( ) is a static method of class System. Because it’s static, you don’t need to create any objects in order to call the method; a static method is always available whether an object of its class exists or not. When you call getProperties( ), it produces the system properties as an object of class Properties. The handle that comes back is stored in a Properties handle called p. In line three, you can see that the Properties object has a method called list( ) that sends its entire contents to a PrintStream object that you pass as an argument.

The fourth and sixth lines in main( ) are typical print statements. Note that to print multiple String values, we simply separate them with ‘ +’ signs. However, there’s something strange going on here. The ‘ +’ sign doesn’t mean addition when it’s used with String objects. Normally, you wouldn’t ascribe any meaning to ‘ +’ when you think of strings. However, the Java String class is blessed with something called “operator overloading.” That is, the ‘ +’ sign, only when used with String objects, behaves differently from the way it does with everything else. For Strings, it means “concatenate these two strings.”

But that’s not all. If you look at the statement:

    System.out.println("Total Memory = "
                       + rt.totalMemory()
                       + " Free Memory = "
                       + rt.freeMemory());

totalMemory( ) and freeMemory( ) return numerical values , and not String objects. What happens when you “add” a numerical value to a String? The compiler sees the problem and magically calls a method that turns that numerical value ( int, float, etc.) into a String, which can then be “added” with the plus sign. This automatic type conversion also falls into the category of operator overloading.

Much of the Java literature states vehemently that operator overloading (a feature in C++) is bad, and yet here it is! However, this is wired into the compiler, only for String objects, and you can’t overload operators for any of the code you write.

The fifth line in main( ) creates a Runtime object by calling the static method getRuntime( ) for the class Runtime. What’s returned is a handle to a Runtime object; whether this is a static object or one created with new doesn’t need to concern you, since you can use the objects without worrying about who’s responsible for cleaning them up. As shown, the Runtime object can tell you information about memory usage.

[15] Some programming environments will flash programs up on the screen and close them before you've had a chance to see the results. You can put in the following bit of code at the end of main( ) to pause the output:

  try {
      Thread.currentThread().sleep(5 * 1000);
    } catch(InterruptedException e) {}

This will pause the output for five seconds. This code involves concepts that will not be introduced until much later in the book, so you won’t understand it until then, but it will do the trick.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date