Creating Java Files

The actual Java code that we'll write is stored in plain text files holding Java statements and declarations. To store Java code in a file, you can use a simple text editor or as fancy a word processor as you like, as long as the result is a plain text file without any fancy formatting that the Java compiler can't handle. You can use whatever text editor you prefer, such as vi in UNIX, or WordPad in Windows.

You should give such files the extension .java because the Java compiler expects that extension. As you saw, I saved the application named app in a file named app.java. This Java file is the one that you'll pass to the Java compiler to create a bytecode file. A very important point to remember is that the file into which you save a java class must have the same name as the java class itself.

The tools we'll use are ready; it's time to start writing code.

Writing Code: Creating an Application

Here's the sample Java application that I'll develop through to the compiling and running stages over the next few sections. Place this code in a file named app.java:

public class app
{
    public static void main(String[] args)
    {
        System.out.println("Welcome to Java");
    }
}

As we've seen, this application will print out the text Welcome to Java when you run it. For example, here's how things would look in a DOS window under Windows:

C:>java app
Welcome to Java

As you can see, this is not the most powerful of programs, but it's simple enough to get us started. We'll work up from this point to windowed Java applications at the end of the chapter. To see what's going on in app.java, the following sections take it apart, line by line.

public class app

Note the first line in app.java:

public class app
{
    .
    .
    .
}

This line of code says that we're creating a new Java class named app. When we translate this file into a bytecode file, Java itself will create an object of this class and give it control.

Note also the keyword public in this line of code. This keyword is an access specifier. When you use the public access specifier for a class, that class is accessible anywhere in your program. The main class for a Java application must always be public. In fact, Java insists that you name the file after the public class in it, which is why this file is named app.java (note that capitalization counts—app.java must hold a public class named app, not APP or App). Because the name of a public class sets the name of the file in which that class is defined, you should have only one public class in a file.

Following the public class app line is the actual implementation of the class, which goes in curly braces:

public class app
{
    .
    .
    .
}

As with the code that you write for methods, the code that you write for objects must go inside curly braces.

public static void main(String[] args)

The next line of code in the application is as follows:

public class app
{
    public static void main(String[] args)
    {
        .
        .
        .
    }
}

What's going on here? In this case, I'm defining a function that's part of an object (because it's defined inside the object's definition), which makes it a method. I'm also declaring this method public, which means that it's accessible (may be called) outside the object. Methods that I declare private cannot be called from outside the object (and are usually utility methods that other methods inside the object call). As with functions in JavaScript, you can pass arguments to Java methods, and you can have methods return values. I'll go into more detail on this process later in the section "Creating Methods in Java," but here I'm indicating that this method is named main and does not return any value, which I indicate with the void keyword. The main method is a special one in Java because it's the one that will be called automatically when Java starts this application. When Java finds the main method, it passes control to it. (Applets don't need a main method—in fact, that's a major programming difference between programming applets and applications.) You place the code that you want run as soon as the application starts in the main method.

In addition, I'm indicating that this method is passed an array of Java String objects by enclosing the code String[] args in parentheses after the method name. You must declare the type of every argument that you pass to a method, and I'm listing that type as String[] here, which is an array of strings. I'm also naming that array args, which is how I can refer to it in the method's code. This array is passed to every application's main method; as we'll see later in the section "Creating Methods in Java," you can use it to read the command-line arguments passed to the application. (For example, if you were to start the application like this: %java app Welcome to Java, the command-line arguments are Welcome, to, and Java.)

There's one more point here—note the static keyword. Technically speaking, the main method is a method of the application's main class, app. You don't create an object of the app class yourself in code; it remains as a class. For that reason, the methods and data items in the app class are class methods and data items (as opposed to object methods and data items). There is a rule for class methods and data items: They must be declared static, which gives Java a special way of storing them. When you've declared them static, you have access to the methods and data items in a class without having to create an object of that class.

This line of code starts the main method, and the rest of this method's code is inside curly braces, as usual:

public class app
{
    public static void main(String[] args)
    {
        .
        .
        .
    }
}

The purpose of this method is to print out the text Welcome to Java, and I'll do that in the next line of code.

System.out.println("Welcome to Java");

The main method has just one line of code in it, and here it is:

public class app
{
    public static void main(String[] args)
    {
        System.out.println("Welcome to Java");
    }
}

This line of code is the only one that actually produces anything as far as the user sees; it prints out Welcome to Java. So what's going on here?

In this case, I'm using some of the built-in functionality that comes with Java. Like JavaScript, Java has plenty of classes and objects ready for you to use. In Java, that functionality is available in Java packages (which are class libraries). One of the Java packages that is available in any Java program is java.lang, the Java language package itself, and this package includes a class named System, which contains a static object named out that enables you to communicate with the user. In particular, I'm using the out object's println method here to display text on the user's console.

Here's another thing to notice: This line of code ends with a semicolon (;). Ending each simple statement with a semicolon has become standard in languages such as C, C++, Java, and even JavaScript. In JavaScript, we were able to omit the semicolon because browsers don't require it—in fact, most people do omit it. In Java, it's another story. The semicolons are required. If you're coming to Java from JavaScript, you may get the feeling that Java is a very prickly language by comparison to JavaScript: Not only do you have to put in the semicolons, but you also have to specify a data type for each data item. When you try to assign a value of one type to a variable of another (which may be legal in JavaScript), Java will give you warning and error reports.

At this point, you've created your new application and stored it in a file named app.java. What's the next step? How do you get it to actually run? Take a look at the next section.

Compiling Code

We have the complete file, app.java, and we're ready to run it. The first step is compiling it into a bytecode file, app.class. To compile app.java, you use the Java tool javac, the Java compiler (on Windows machines, this program is called javac.exe and is located in the bin subdirectory of the JDK installation). Here's how you use javac in general. (All the arguments here are optional, and I'll place them in square brackets to indicate that, which is the convention Sun itself uses in the Java documentation.)

javac [options] [sourcefiles] [files]

Here are the arguments to javac:

ArgumentDescription
optionsCommand-line options; see the Java documentation for the details; we won't need any command-line options here.
sourcefilesOne or more code files to be compiled (here, that'll be just app.java).
filesOne or more files that list command-line options code files to compile.

In this case, I'll compile app.java with this command:

%javac app.java

The Java compiler, javac, compiles the file app.java (assuming that there are no errors), translating it and creating a new file named app.class. If errors occur, the Java compiler will tell you what they are, including what line of code is wrong, as in this case, where I've forgotten the name of the println method and tried to use one called printText:

%javac app.java
app.java:5: Method printText(java.lang.String) not found in class
java.io.Print
Stream.
        System.out.printText("Welcome to Java");
                            ^
1 error

At this point, we've created the file app.class, the bytecode file that Java will need to run the application. This bytecode file will run unchanged on any system that supports Java.

So, how do you actually run app.class? I'll take a look at that in the next section.

Running Java Applications

The way you actually run Java applications is with the Java tool named, appropriately enough, java. This tool is a program that comes with the Java SDK (java.exe in Windows, in the Java bin directory).

Running Java Apps Without the SDK

You don't need the full Java SDK to simply run Java applications. You can get the java tool in the Java Runtime Environment, or JRE, which you can get from the Sun Java site, at http://java.sun.com/js2e.


To run the app application, I use the java tool like this on the command line:

%java app

The result appears at once:

%java app
Welcome to Java

You can see what this looks like in Figure 10.1, where I'm running this application in a DOS window in Windows.

Figure 10.1. Running a Java application.


That's all it takes—you've created, compiled, and run your first Java application. (Note that if your application isn't responding or you want to stop it for some reason, you can type Ctrl+C. If that doesn't work, try the Escape key.)

While we're on the topic of compiling and running code, we should cover another detail—commenting your Java code.

Commenting Your Code

As with JavaScript, you can comment your Java code. Comments serve the same purpose here as they do in XML or JavaScript—they hold descriptive text that explains what's going on in your code. There are two ways to insert comments in a Java program. The first way is to surround comments, especially multiline comments, with the characters /* and */, like this:

/* This application is designed to display
   the message "Welcome to Java" on the console
*/
public class app
{
    public static void main(String[] args)
    {
        System.out.println("Welcome to Java");
    }
}

As with any type of comment, the Java compiler will ignore the text in the comment—that is, any text between the /* and */ markers.

As with JavaScript, Java also supports a one-line comment, using a double slash (//). The Java compiler will ignore everything on a line after the // marker, so you can create whole lines that are comments, or just add a comment to an individual line, like this:

/* This application is designed to display
   the message "Welcome to Java" on the console
*/

public class app        //Define the class app
{
    //Define main(), the first method to be called.
    public static void main(String[] args)
    {
        //Display the message "Welcome to Java"
        System.out.println("Welcome to Java");
    }
}

In fact, there's even another type of comments, JavaDoc comments, that start with /** and end with */, and are used by the javadoc tool to provide documentation for a program.)

Importing Java Packages and Classes

As mentioned, the classes that Sun has put together already for you to use are stored in class libraries called packages. The classes that we'll use to interact with XML documents in the next two chapters are also stored in packages. Although the java.lang package is already available to your code by default, the classes in other packages are not, and you must import those packages to use them. You can also import individual classes, as well as whole packages. Knowing how to do this is very important in Java programming because a great deal of the resources that most programs use are in packages that you must import.

To import a package, you use the Java import statement, which looks like this:

import [package1[.package2…].](classname|*);

Following the Sun conventions, items in square brackets ([]) are optional, and the upright bar (|) means or, much as it does when you write DTDs.

Note that you put a dot (.) between package and class names to keep them separate. The standard Java packages themselves are stored in a large package called java, so the util package is really called the java.util package. (Other large packages like the java package are available—for example, the extensive Swing package is stored in the javax package.)

Here's an example; in this case, I want to use the Date class in the java.util package. To do that, I can import that class this way in code:

import java.util.Date;

public class app
{
    public static void main(String[] args)
    {
    .
    .
    .
    }
}

Now I'm able to use the Date class in code. To do that, I create a new Date object with the new operator—which is how you create objects from classes in JavaScript as well. (In fact, we used the JavaScript Date class and created a new object of that class in Chapter 6.) The new Date object represents today's date, which I can display like this—note that I'm also adding a pair of empty parentheses after the Date class to indicate that I'm not passing any value to that class's constructor. (As we saw in Chapter 6, a class's constructor is a method that runs when an object is created from the class, allowing you to initialize the object.)

import java.util.Date;

public class app
{
    public static void main(String[] args)
    {
        System.out.println("Today's date is " + new Date());
    }
}

When you compile and run this application, this is the kind of result you'll see:

%java app
Today's date is Mon May 22 16:28:53 EDT 2001

In this case, I imported a specific class, the Date class, from the java.util package. However, you can import all classes from a package at once with the * wildcard, like this, where I'm importing all java.util classes. (Note that this does not make the app.class file any larger—only those classes that are actually referenced in the code are used when building the final bytecode file—the bytecode file app.class will be the same size if you use either the statement import java.util.Date; or the statement import java.util.*;.)

import java.util.*;

public class app
{
    public static void main(String[] args)
    {
        System.out.println("Today's date is " + new Date());
    }
}

You can also import classes that you've created. For example, say that you've created a class named Display that uses a method named showImage to display an image on the user's screen. You might create a new object of the Display class and use the showImage method something like this:

public class app
{
    public static void main(String[] args)
    {
        (new Display()).showImage("flowers.gif");
    }
}

When you've created the file Display.class, you can import the Display class into your program like this:

import Display;

public class app
{
    public static void main(String[] args)
    {
        (new Display()).showImage("flowers.gif");
    }
}

This technique relies on having Display.class in the same directory as the application you're compiling so that the import statement can find it. On the other hand, you might want to store Display.class in another directory, such as C:display. In that case, you have to add c:display to the Java environment variable CLASSPATH. We'll see more about this in the next chapter, or you can see the Java documentation for all the details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.104.177