Chapter 10. Understanding Java

CONTENTS
  •  Java Resources
  •  Writing Java Programs
  •  Creating Java Files
  •  Creating Variables in Java
  •  Creating Arrays in Java
  •  Creating Strings in Java
  •  Java Operators
  •  Java Conditional Statements:if, if else, switch
  •  Java Loops: for, while, do while
  •  Declaring and Creating Objects
  •  Creating Methods in Java
  •  Creating Java Classes

Chapter 7, "Handling XML Documents with JavaScript," and Chapter 8, "XML and Data Binding," describe how to work with XML and JavaScript in Internet Explorer. However, JavaScript is a relatively lightweight language, and most serious XML programming doesn't take place in browsers such as Internet Explorer. Today, the most common way of handling XML in code is to use Java. Working with XML by using Java has become a central XML topic, and no XML book can ignore this connection.

Java should not be confused with JavaScript; despite their names and similar syntax, they are not truly related. Java is a creation of Sun Microsystems and JavaScript of Netscape. Java is far deeper and far more extensive than JavaScript.

On the other hand, now that we have used JavaScript, we've got a good leg up on Java because much of the basic syntax is similar (because both are based on the C++ model, not because JavaScript and Java are directly related). In the next two chapters, we'll see how to work with the most popular XML package written for Java the XML for Java package from IBM's AlphaWorks.

In this chapter, we'll come up to speed with Java, building on what we already know of JavaScript. We'll get the skills that we need for the next two chapters in this chapter, including creating Java classes and windowed applications.

In general, creating serious applications with Java is more involved than working with JavaScript because Java is so much more extensive. As you can imagine, there's way more Java than we can cover in one chapter, so if you want to learn more, pick up a good book on the subject. Try Special Edition Java 2 Platform by Joseph Weber, published by Que, or Sams Teach Yourself Java 2 in 24 Hours, 2nd Edition by Roger Candenhead, published by Sams. On the other hand, this chapter introduces all the Java coding skills we'll use in the next two chapters. If you're already comfortable with Java, feel free to skip to the next chapter, where I work with the XML DOM in Java (not JavaScript, as in Chapter 7).

Java Resources

Java is a product of Sun Microsystems. These are some Web sites that contain Java resources online, most of them at Sun:

  • http://developer.netscape.com/tech/java/. Netscape's "Java Developer Central" site, which contains a good amount of useful information

  • http://java.sun.com. The main Java site; it's filled with information

  • http://java.sun.com/docs/. Java documentation available online; this is the reference Web site.

  • http://java.sun.com/js2e/. The site for the current Java software development kit (this URL is very subject to change).

  • http://java.sun.com/j2se/1.3/. The home of Java Version 1.3, which is the current version as of this writing (actually called Java 2 Platform, Standard Edition, version 1.3), of the Java software development kit

  • http://www.javaworld.com. A great number of Java resources and discussions

Here's another list that you might want to look into; these are free online tutorials that you can use to develop your Java skills:

  • http://java.sun.com/docs/books/tutorial/index.html. Sun's own, very extensive Java tutorial

  • http://gamelan.earthweb.com/javaprogramming/javanotes/. Gamelan's Java tutorial

  • http://www.javacoffeebreak.com. A good online Java tutorial

  • http://www-4.ibm.com/software/developer/education/buildapplet/. IBM's Java tutorial with some outstanding features

Here's an important note Java programming is not for everyone. Java is a complex language, and to cover it fully would take thousands of pages. We can't ignore it because it has come to play such a big part in the XML world, but if you're not into programming, you can skip the Java chapters (this and the next two chapters) and continue on with the rest of the book. Many people prefer to get their Java XML applications written by someone else, and that's fine. However, these days, to really work with XML, it usually comes down sooner or later to working with Java.

Writing Java Programs

You're probably already familiar with Java, if only because of Java applets. Applets windowed Java applications designed to work in browsers took the world by storm when first introduced, and all major browsers support some version of Java these days. You can find millions of applets on the Internet, and you can pick up whole banks of them for free. There are even applets out there that work with XML.

A Java applet takes up a predefined area in a browser and can display graphics, controls (such as buttons and text fields), text, and more. It's interactive because it runs in your browser. As mentioned, applets took the Internet by storm when first introduced. However, they're on the wane now, largely because of other solutions that can be easier to program, such as Dynamic HTML, or more powerful, such as Shockwave.

Don't worry about Java though as applets have become less popular (although still very popular), Java applications have gathered strength. The main reason that Java applications have become so powerful is that they're nearly as powerful as C++, but they're also cross-platform you can use the same application in Windows or UNIX, for example. Many large corporations have switched from using C++ internally to using Java for most programming.

A Java application does not run in a browser like an applet it's a free-standing program. Java applications can themselves create windows, such as applets, and we'll see how to do that here. In fact, Java applications can act as browsers, and we'll see an example of that in the next chapter with a Java application that reads an XML document from the Internet and uses it to display graphics. In that case, the XML document will specify circles to draw, and we'll be creating a graphical, not text-based, browser, which is typical of the kinds of things you can do when you create your own XML applications.

Our XML Java work will center on writing Java applications, not applets. (For security reasons, applets are very restricted in terms of what they can do, and they can't handle most types of file access we don't want to restrict our XML programs to work only in browsers.) So how do you create a Java application? You write applications as Java code and then compile them with the Java Software Development Kit (SDK). (Before Java 2, the SDK was called the Java Development Kit [JDK], and some people, including some Web pages at Sun, still call it that.) The compiled application is ready to run, and we'll see how to do that here.

I'll make this more concrete with an immediate example. Here's how to create an application named app, which I'll store in a file named app.java (I'll go through the details of this application in this chapter):

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

I can use the Java compiler, which is named javac, to compile this file into a bytecode file named app.class, and app.class is what you actually run. The bytecodes in app.class are what Java reads and executes. (Java bytecodes are very compact compared to text, which makes applets fast to download. You can run the same bytecode file on many different operating systems, which makes it cross-platform.) Here's how you use javac to compile app.java (I'm using % as a generic command-line prompt, following the UNIX usage, where the prompt often is %; on an operating platform such as Windows, this prompt will be something like C:\XML>):

%javac app.java

This creates app.class, and it's that file you use when running that application. To run the application, you use the tool named java (which comes with the Java SDK), like this:

%javac app.java %java app Welcome to Java

As you can see, the java tool executes the bytecode file app.class, and the result the text Welcome to Java appears. As mentioned, I'm using % as a generic command-line prompt because Java is available on many platforms. In Windows, you use these tools in an MS DOS window like this:

C:\>java app Welcome to Java

That's what running a Java application looks like. As we'll see, there are many similarities between Java and JavaScript but there are also significant differences. For example, we'll need to indicate the type of variables in Java, which you don't have to do in JavaScript, and Java is also a lot more object-oriented than JavaScript.

Java Is Object-Oriented from the Ground Up

We first got a look at object-oriented programming when working with JavaScript, but that was only a quick glance. Object-oriented programming is integral to every aspect of Java. For example, take a look at the application we just saw:

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

The very first line public class app defines a class named app. Our whole program is based on that class because, unlike JavaScript, every line of code that you write in Java must be part of a class (or an interface, which is a more generalized form of class). When Java runs this application, it creates an object of this class and gives that object control. So, although you can optionally use objects in JavaScript, there's no avoiding them in Java.

I'll take a closer look at the idea behind classes now because we'll have to understand more about them than we did when discussing JavaScript. Object-oriented programming is really just another technique to let you implement that famous programming dictum: Divide and conquer.

Here's the idea: You encapsulate data and functions into objects, which makes objects into self-contained units. The data inside an object can be purely internal to the object, in which case it's called private data, or it can be accessible externally, in which case it's called public data.

The functions built into an object can also be purely private, or they can be public. In fact, ideally, the object should interact with the rest of the program only through a well-defined interface as created by its public functions. As we saw in Chapter 6, "Understanding JavaScript," functions that are part of classes or objects are called methods.

Object-oriented programming was first developed to let programmers handle larger programs by breaking them up into functional units that can be easily conceptualized. As you know, you can already break your code up into functions; object-oriented programming goes a step further than that, letting you create objects that can contain not just one function, but many, as well as internal data items. When you encapsulate part of your code into an object, it lets you think of that part of the program in an easily conceptualized way, and that's the motivation behind object-oriented programming.

For example, consider a car but consider it not as a sleek new automobile, but as an assemblage of pipes, wires, valves, switches, gasoline, and all the various parts that make it work. Now imagine that you are responsible yourself for handling everything that the car usually does itself, such as pumping the fuel, igniting the fuel, transmitting power to the wheels, regulating electrical power, and more. A device requiring such attention would be impossible to drive. Now imagine all those functions back where they should be, internal to the car, and interacting with each other automatically as needed when you step on the gas. You think of the result simply as a car an easily imagined single concept. All you have to do is to turn it on and step on the gas.

That's the idea behind encapsulation you can take a complex system that requires a lot of attention and turn it into an object that handles the details internally when you pass control to it. If the first dictum of object-oriented programming is, "Divide and conquer," then the second is surely "Out of sight, out of mind."

In Java, object-oriented programming revolves around a few key concepts: classes, data members, inheritance, methods, and objects. This list summarizes these terms:

  • Class. A class can be thought of as a template from which you can create objects. The definition of the class includes the formal specifications for the class and any data and methods in it.

  • Data members. The data members of a class are the variables that are part of an object. You store the data that the object uses in its data members.

  • Inheritance. This is the process of deriving one class, called the derived class, from another, the base class, and being able to make use of the base class's methods in the derived class, while adding new functionality to the derived class.

  • Method. A method is a function built into an object. Methods can be part of classes (class methods) or objects (object methods), as we'll see in this chapter.

  • Object. This is an instance of a class what you create with classes. You can think of a class as the type of an object. When you've created an object, you can customize it by storing data in it (which you can't do with a class).

All these constructs are important to object-oriented programming, and we'll get more details on each of them in this chapter as we see how to create our own classes.

Getting the Java SDK

To create your own Java applications, you'll need to get and install the Java SDK, at http://java.sun.com/js2e. After downloading the Java SDK, usually as one executable package that installs itself, follow the installation instructions on the http://java.sun.com site.

At this point, I'd love to be able to give detailed instructions on how to install the Java SDK, but that's a trap too many books have fallen into. The actual installation procedure has changed so often and so many times that any book that covers Java (and I've written many on Java) and tries to give those instructions is sure to make itself obsolete immediately. On the other hand, in recent versions, all you have to do is run an executable program that you download, and it'll do all the work for you.

As indicated in the Sun installation instructions, you must make sure that your machine can find the Java tools, including the Java compiler, javac. To do this, make sure that the Java bin subdirectory is in your computer's path. For example, in Windows, the bin subdirectory is c:\jdk1.2.2\bin for the Java 2 SDK by default, version 1.2.2. You add a line like the following to autoexec.bat:

SET PATH=%PATH%;C:\JDK1.2.2\BIN

Depending on your operating system, you must reboot your computer to make these changes take effect. Now that the bin directory is in the path, you'll be able to use the Java tools from the command line; otherwise, you'll have to preface them with a pathname each time you want to use them.

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:

Argument Description
options Command-line options; see the Java documentation for the details; we won't need any command-line options here.
sourcefiles One or more code files to be compiled (here, that'll be just app.java).
files One 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.

graphics/10fig01.gif

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.

Creating Variables in Java

We've seen that Java applications are class-based, and we've gotten enough Java down now to create basic programs. The next step in Java programming is to start storing your data so that you can work on that data. As with JavaScript, variables serve as locations in memory in which you can store your data. However, unlike JavaScript, Java variables are strongly typed, which means that you must declare a type for each variable and be careful about mixing those types. (This is actually one of the strengths of Java because the basic data types are always the same, and the programmer does not need to worry about arcane floating point standards or word orders.)

For example, one of the most common variable types is int, which stands for integer. This type sets aside 4 bytes of memory, which means that you can store values between 2,147,483,648 and 2,147,483,647 in int variables. Quite a few different variable types are built into Java, such as integers, floating point numbers, and individual characters.

When you want to use a variable in Java, you must declare it, specifying the variable's type:

type name [= value][, name [= value] ];

Here's an example showing how to declare a variable of the int type. This variable is named counter:

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

What I've done is set aside 4 bytes of memory for the variable named counter. I can store a value of 2001 in that counter like this, using the Java assignment operator:

public class app {     public static void main(String[] args)     {         int counter;         counter = 2001;     .     .     .     } }

And I can display the value in the counter variable with a println statement, like this:

public class app {     public static void main(String[] args)     {         int counter;         counter = 2001;         System.out.println("The current counter value is " + counter);     } }

Here's the result of this code:

%java app The current counter value is 2001

As in JavaScript, you can use a shortcut to both declare a variable and assign a value to it at the same time:

public class app {     public static void main(String[] args)     {         int counter = 2001;         System.out.println("The current counter value is " + counter);     } }

Plenty of variable types are built into Java besides int:

  • Boolean. The boolean type holds only two types of values: true and false.

  • Characters. The char type holds representations of characters such as letters and numbers.

  • Floating point numbers. There are two types here float and double (for double precision), which hold signed floating point numbers.

  • Integers. There are a number of integer types, such as byte (1 byte of storage), short (usually 2 bytes), int (usually 4 bytes), and long (usually 8 bytes), which hold signed (that is, plus or minus), whole-value numbers.

Because Java is a very strongly typed language, it's very particular about mixing data types. For example, look at this code, where I'm declaring a floating point number and an integer, and then assigning the floating point number to the integer:

public class app {     public static void main(String[] args)     {         float counter = 2001;         int counter2;         counter2 = counter;         System.out.println("The current counter2 value is " + counter2);     } }

Java regards this as a problem because the floating point type can hold numbers with greater precision than the int type. It returns an error when you try to compile this code, saying that an "explicit cast" is required to convert a floating point number to an integer:

%javac app.java app.java:8: Incompatible type for =. Explicit cast needed to convert float to int.         counter2 = counter;                  ^ 1 error

To solve a problem like this, you can explicitly request Java to convert the floating point number to an integer with the cast (int):

public class app {     public static void main(String[] args)     {         float counter = 2001;         int counter2;         counter2 = (int) counter;         System.out.println("The current counter2 value is " + counter2);     } }

You can convert between types like this if required, but bear in mind that you could lose some numerical precision this way.

Creating Arrays in Java

Simple data types of the kind we saw in the previous section are fine for storing single data items, but data is often more complex. Like JavaScript, Java supports arrays as well. Here's an example; in this case, I'll store the balances in customers' charge accounts in an array named chargesDue. I start by declaring that array, making it of type double:

public class app {     public static void main(String[] args)     {         double chargesDue[];     .     .     .

Before using the array, you also have to allocate the number of elements that you want the array to hold. You do that like this, using the new operator:

public class app {     public static void main(String[] args)     {         double chargesDue[];         chargesDue = new double[100];     .     .     .

You can combine the array declaration and definition into one statement, like this:

public class app {     public static void main(String[] args)     {         double chargesDue[] = new double[100];     .     .     .

After the array has been created, you can address individual elements using square brackets and an array index, like this:

public class app {     public static void main(String[] args)     {         double chargesDue[] = new double[100];         chargesDue[4] = 99.06;         System.out.println("Customer 4 owes $" + chargesDue[4]);     } }

Here's the result of this code:

%java app Customer 4 owes $99.06

In Java, the lower bound of an array that you declare this way is 0, so the statement chargesDue = new double[100] creates an array with a first item of chargesDue[0] and a last item of chargesDue[99].

You can also initialize arrays with values at the same time you create them. You do that by specifying a comma-separated list of values in curly braces, like this (note that the number of elements in the created array will be the number of elements in the list):

public class app {     public static void main(String[] args)     {         double chargesDue[] = {1093.66, 667.19, 45.99, 890.30, 99.06};         System.out.println("Customer 4 owes $" + chargesDue[4]);     } }

I'll elaborate this example now. Say that the store we're handling customer balances for opens a new branch, so now there are both eastern and western branches. If customers can open accounts in both branches, we'll need to keep track of two balances for each customer. You can do that by using a two-dimensional array, like this:

public class app {     public static void main(String[] args)     {         double chargesDue[][] = new double[2][100];     .     .     .

Now you refer to every element in the array with two array indices, not just one, as in the previous, one-dimensional version of this array:

public class app {     public static void main(String[] args)     {         double chargesDue[][] = new double[2][100];         chargesDue[0][4] = 99.06;         chargesDue[1][4] = 23.17;     .     .     .

I can display the balance in both a customer's eastern and western branch accounts, like this:

public class app {     public static void main(String[] args)     {         double chargesDue[][] = new double[2][100];         chargesDue[0][4] = 99.06;         chargesDue[1][4] = 23.17;         System.out.println("Customer 4 owes $" +         chargesDue[0][4] + " in the eastern branch.");         System.out.println("Customer 4 owes $" +         chargesDue[1][4] + " in the western branch.");     } }

Here's the result:

%java app Customer 4 owes $99.06 in the eastern branch. Customer 4 owes $23.17 in the western branch.

You can also initialize a two-dimensional array by assigning values when declaring such an array:

public class app {     public static void main(String[] args)     {         double chargesDue[][] = {{1093.66, 667.19, 45.99, 890.30, 99.06},                                  {2019.00, 129.99, 19.01, 630.90, 23.17}};         System.out.println("Customer 4 owes $" +             chargesDue[0][4] + " in the eastern branch.");         System.out.println("Customer 4 owes $" +             chargesDue[1][4] + " in the western branch."); } }

Determining the Length of an Array

Need to find the length of an array? Just use the array's length property, like this: scores.length.

Creating Strings in Java

You may have noticed that you can combine strings with the + operator in Java, just as you can in JavaScript:

public class app {     public static void main(String[] args)     {         double chargesDue[][] = {{1093.66, 667.19, 45.99, 890.30, 99.06},                                  {2019.00, 129.99, 19.01, 630.90, 23.17}};         System.out.println("Customer 4 owes $" +             chargesDue[0][4] + " in the eastern branch.");         System.out.println("Customer 4 owes $" +             chargesDue[1][4] + " in the western branch.");     } }

The reason this works is that strings are supported by the built-in class String in Java. In fact, the String class is treated in a special way in Java, and you can use it just as you would any built-in data type, as in the following case. (Note that I don't have to use the new operator or call the String class's constructor here.)

public class app {     public static void main(String[] args)     {         String welcome = "Welcome to Java";         .         .         .

You can treat this new String variable as you would other simple variables, including printing it out like this:

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

In fact, there are really two string classes that are available in Java the String and StringBuffer classes. String objects are read-only because they don't allow you to change their internal data. However, you can change the internal text in the StringBuffer class. Both these classes have many methods built into them, which you can find in the Java documentation.

Java Operators

As in JavaScript, operators are an important part of programming in Java. Here's an example adding two values using the Java + operator:

public class app {     public static void main(String[] args)     {         int int1 = 130, int2 = 250, sum;         sum = int1 + int2;         System.out.println(int1 + " + " + int2 +             " = " + sum);     } }

Here are the results of this code:

%java app 130 + 250 = 380

So what operators are available in Java? Table 10.1 contains all of them note that JavaScript shares nearly all of them as well.

Table 10.1. Java Operators
Operator Operation Performed
++ Increment
-- Decrement
= Assignment
== Equal to
+ Addition
+= Addition assignment
- Subtraction
-= Subtraction assignment
* Multiplication
*= Multiplication assignment
/ Division
/= Division assignment
< Less than
<= Less than or equal to
<< Shift left
<<= Shift left assignment
> Greater than
>= Greater than or equal to
>> Shift right
>>= Shift right assignment
>>> Shift right with zero fill
>>>= Shift right zero fill assignment
^ Logical Xor
^= Bitwise Xor assignment
| Logical Or
|| Short-circuit Or
|= Bitwise Or assignment
~ Bitwise unary Not
! Logical unary Not
!= Not equal to
& Logical And
&& Short-circuit And
&= Bitwise And assignment
?: Ternary if else
% Modulus
%= Modulus assignment

Java Conditional Statements: if, if else, switch

After operators, the next level up is to use conditional statements, and Java supports the same conditional statements as JavaScript: if, if else, and switch.

The if statement enables you to check a condition, which you create using the Java conditional operators such as <, >, and ==:

if (condition) {     code executed if condition is true } else {     code executed if condition is false }

For example, say that you had two double variables, assets and debts, and you wanted to compare the two to make sure that you're solvent. You might want the code to display a message, such as You're solvent. You can do that like this (note the \ before the ' in this code; you must add the \ to let Java know that the ' is not a quotation mark):

public class app {     public static void main(String[] args)     {         double assets = 175.99;         double debts = 115.99;         if (assets > debts) {             System.out.println("You\'re solvent."); }     } }

As we've seen when discussing JavaScript, the if statement checks its condition and, if that condition evaluates to true, executes the code in the if statement's body. In this case, the code will display the message; here are the results:

%java app You're solvent.

You can also explicitly handle the case in which the condition in an if statement turns out to be false by including an else clause. If the condition in the if statement evaluates to false, the code in the else clause is executed if the if statement has such a clause. Here's an example; in this case, the second message will be displayed if the amount in assets is less than or equal to the amount in debts:

public class app {     public static void main(String[] args)     {         double assets = 175.99;         double debts = 115.99;         if (assets > debts) {             System.out.println("You\'re solvent."); }         else {             System.out.println("Uh oh.");         }     } }

You can also create "ladders" of if..else statements, like this, where I'm handling the cases in which the amount in assets is either the same as or greater than that in debts:

public class app {     public static void main(String[] args)     {         double assets = 175.99;         double debts = 115.99;         if (assets > debts) {             System.out.println("You\'re solvent."); }         else {             if(assets == debts) {                 System.out.println("You\'re broke.");             }             else {                 System.out.println("Uh oh.");             }         }     } }

As with JavaScript, Java also supports a switch statement:

switch(test){     case value1:           .           .           .         code executed if test matches value1           .           .           .         break;     case value2:           .           .           .         code executed if test matches value2           .           .           .         break;     default:           .           .           .         code executed if test doesn't matches any case           .           .           .         break; }

But there's a catch: You can't use it with most of the many variable types Java defines. The only values that you can check in switch statements are byte, char, short, or int values. Here's an example where I'm working with integers:

public class app {     public static void main(String[] args)     {         int day = 5;         switch(day) {             case 0:                 System.out.println("Today is Sunday.");                 break;             case 1:                 System.out.println("Today is Monday.");                 break;             case 2:                 System.out.println("Today is Tuesday.");                 break;             case 3:                 System.out.println("Today is Wednesday.");                 break;             case 4:                 System.out.println("Today is Thursday.");                 break;             case 5:                 System.out.println("Today is Friday.");                 break;             default:                 System.out.println("It must be Saturday.");         }     } }

There's another useful way of handling if else situations you can use the Java ?: operator. This operator returns one of two values depending on whether an expression evaluates to true or false. You put the condition in front of the ?, the value that this operator should return if the condition is true immediately after the ?, and the value that the operator should return if the condition is false after the colon (:). Here's an example, where I've converted the earlier if else example to use the ?: operator:

public class app {     public static void main(String[] args)     {         double assets = 175.99;         double debts = 115.99;         String output;         output = assets > debts ? "You\'re solvent." : "Uh oh.";         System.out.println(output);     } }

Java Loops: for, while, do while

The next step after working with conditional statements is to handle loops. Like JavaScript, Java supports a for loop, a while loop, and a do while loop.

Here's how you use a Java for loop in general; note that the statement that makes up the body of the for loop can be a compound statement it can be made up of several single statements enclosed in curly braces:

for (initialization_expression; test_condition; iteration_expression) {     statement }

You place an expression in the initialization part of the for loop (which often initializes a variable that is, a loop index to 0), and then you place a test condition in the test part of the loop to be tested each time the code in the loop has been executed. If the test is false, the loop ends (often the test condition checks whether the value in the loop index exceeds a specified maximum value). On the other hand, if the test condition is true, the body of the loop is executed and the code in the iteration part of the loop is executed to get the loop ready for the next iteration (often by incrementing the loop index).

Here's an example; in this case, I'm summing the values in five bank accounts, as stored in an array named accounts, using a for loop:

public class app {     public static void main(String[] args)     {         double accounts[] =             {365.55, 789.19, 532.11, 1079.96, 185.19};         double sum = 0;         for (int loopIndex = 0; loopIndex < accounts.length;             loopIndex++) {             sum += accounts[loopIndex];         }         System.out.println("The total in all accounts is $" + sum);     } }

Here are the results of this code:

%java app The total in all accounts is $2952

Java also supports a while loop. I'll create an example showing how to use this loop and how you can read input from the keyboard. In this case, I'll keep reading from the keyboard until the user types the word quit.

You can use the System.in.read method to read character by character from the keyboard. This method waits until the user presses Enter at the end of the line, at which point Java stores all those typed characters. When you call this method, it reads the next character from those that were typed and returns it.

To read what the user has typed using this method, I'll start by creating a string named input, and I'll add all the waiting characters to this string in succession by repeatedly calling the System.in.read method. I'll then search the string for the word quit. I can use the String class's indexOf method to search this string for that word and keep looping until that word is found. The indexOf method returns the starting location of the string that you're searching for, or -1 if that string is not found. Here's how I can keep waiting for quit until it's found:

public class app {     public static void main(String[] args)     {         String input = "";         while (input.indexOf("quit") < 0){             .             .             .         }     } }

Each time the user enters a new line, I can use System.in.read to read the characters the user has typed, and add them one by one to the input string. The System.in.read method actually returns ASCII codes as integers, so we'll need an explicit cast, (char), to convert those values to characters we can add to the input string.

The creators of Java knew that I/O operations are prone to errors, so they allowed the System.in.read to generate errors that your program can handle, called trappable errors or exceptions in Java. Generating such an error is called throwing an exception. You must enclose the code that can cause errors in a special construct called a try block:

public class app {     public static void main(String[] args)     {         String input = "";         while (input.indexOf("quit") < 0){             try {                 input += (char) System.in.read();             }             .             .             .         }     } }

You follow the try block with a catch block to catch any errors that occurred. The catch block is passed an object of class Exception, and I'll name that object e here. I can use that object's printStackTrace method to display the error that occurred, sending the text from that method to the System.err output channel (which corresponds to the console by default), like this:

public class app {     public static void main(String[] args)     {         String input = "";         while (input.indexOf("quit") < 0){             try {                 input += (char) System.in.read();             } catch (Exception e) {                 e.printStackTrace(System.err);             }         }     } }

That's all we need; now the user can enter text, which the application will read and when the user types the word quit anywhere in that text, the application will terminate:

%java app Hi there! This is great. Anything happening? Well, looks like it's time to quit.

Not bad; now we've seen one way to read from the keyboard as well as use the while loop.

Declaring and Creating Objects

In Java, you must declare new objects, then you create them with the new operator. For example, here's how I create an object of the Java String class, passing the text Welcome to Java to that class's constructor:

public class app {     public static void main(String[] args)     {         String greeting1;         greeting1 = new String("Welcome to Java");     .     .     .

Note that I first declared the greeting1 object, giving the object's class, String, as its type. Then I create the object with the new operator.

Overloading Constructors

Classes can have different constructors that handle different types of data. For example, I passed a string to the String class's constructor in the previous example, but I can also pass an array of characters this way, which is useful if my data is stored as such an array:

public class app {     public static void main(String[] args)     {         String greeting1, greeting2, greeting3;         greeting1 = new String("Welcome to Java");         char characters[] = {'W', 'e', 'l', 'c', 'o', 'm', 'e',                     ' ', 't', 'o', ' ', 'J', 'a', 'v', 'a'};         greeting2 = new String(characters);         .         .         .     } }

Constructors and methods that can take different argument lists are called overloaded.

To overload a constructor or method, you just define it a number of times, each with a different argument list.

Assigning Objects

You can also assign one object to another, using the = assignment operator:

public class app {     public static void main(String[] args)     {         String greeting1, greeting2, greeting3;         greeting1 = new String("Welcome to Java");         char characters[] = {'W', 'e', 'l', 'c', 'o', 'm', 'e',                     ' ', 't', 'o', ' ', 'J', 'a', 'v', 'a'};         greeting2 = new String(characters);         greeting3 = greeting2;         .         .         .     } }

To end this example, I'll print out all the strings that we've created:

public class app {     public static void main(String[] args)     {         String greeting1, greeting2, greeting3;         greeting1 = new String("Welcome to Java");         char characters[] = {'W', 'e', 'l', 'c', 'o', 'm', 'e',                     ' ', 't', 'o', ' ', 'J', 'a', 'v', 'a'};         greeting2 = new String(characters);         greeting3 = greeting2;         System.out.println(greeting1);         System.out.println(greeting2);         System.out.println(greeting3);     } }

Here's what this application looks like when run:

%java app Welcome to Java Welcome to Java Welcome to Java

That's how to declare and create objects in Java. It's similar to the way you declare and create simple variables, with the added power of configuring objects by passing data to a class's constructor.

Creating Methods in Java

In JavaScript, we created functions; in Java, everything is object-oriented, so we'll be creating methods. A method is just a function that's part of a class or object. As an example, I'll create a method now named adder that will add two integers and return their sum.

To start, I'll need two numbers to add, and I'll let the user enter them as command-line arguments. I can read those arguments from the array passed to the main method, which I name args, and then store them in integers value1 and value2, like this:

public class app {     public static void main(String[] args)     {         int value1 = Integer.parseInt(args[0]);         int value2 = Integer.parseInt(args[1]);     .     .     . }

Now I display those values, pass them to the adder method, and display the value that adder returned, like this:

public class app {     public static void main(String[] args)     {         int value1 = Integer.parseInt(args[0]);         int value2 = Integer.parseInt(args[1]);         System.out.println(value1 + " + " + value2 +         " = " + adder(value1, value2));     }     .     .     . }

All that remains is to create the adder method. You can give methods access specifiers such as public or private. If you give it the access specifier public, the method is accessible outside the object or class. If you give it the access specifier private (which is the default if you don't use an access specifier), it's accessible only inside the object or class. I'll use public here.

In addition, you must specify the return type of the value the method returns (you can use the keyword void if the method doesn't return a value). And you must give a comma-separated argument list for the method, giving the type of each argument in parentheses following the method's name (if the method takes no arguments, leave the parentheses empty). All this gives us the following skeleton for the definition of adder:

public class app {     public static void main(String[] args)     {         int value1 = Integer.parseInt(args[0]);         int value2 = Integer.parseInt(args[1]);         System.out.println(value1 + " + " + value2 +         " = " + adder(value1, value2));     }     public static int adder(int int1, int int2)     {     .     .     .     } }

In the body of the method, I can refer to the two values passed using the names I've given them in the argument list, int1 and int2. I add those values and return the result using the return statement:

public class app {     public static void main(String[] args)     {         int value1 = Integer.parseInt(args[0]);         int value2 = Integer.parseInt(args[1]);         System.out.println(value1 + " + " + value2 +         " = " + adder(value1, value2));     }     public static int adder(int int1, int int2)     {         return int1 + int2;     } }

Now the user can enter values to add on the command line, and the application will handle them without problem:

%java app 180 120 180 + 180 = 300

Using return

You can use the return statement even in methods that you don't return any value from if you want to terminate execution and return from the method just use the return statement alone, without specifying any values to return.

Creating Java Classes

We've already seen how to create classes in a rudimentary way: You need to create a class to do anything at all, as when we created the main class for the applications that we've built:

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

In preparation for the next chapter, let's take a look at a more advanced example. In this case, I'll create a new class named AppFrame based on the Java Frame class, which is what you use to create frame windows (a frame window has a frame, including a border and title bar) in Java. There are two ways to work with graphics in Java: the Abstract Windowing Toolkit (AWT) and the Swing Java packages. In the interests of space, I'm going to stick with the AWT in this book because just starting to understand how Swing works would be a whole chapter itself. However, if you find yourself doing a lot of Java development, I encourage you to examine what Swing has to offer.

Here's what it will look like in the main method; I'll create a new object named f of the AppFrame class, passing the text that we want to appear in that window to that class's constructor:

public class window {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications ");         .         .         .    } }

Because the AppFrame class is built on the Java Frame class, I can use the Frame class's setSize method to give this new window a size of 400 x 200 pixels, and I can use the show method to display it on the screen:

public class window {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications ");        f.setSize(400, 200);        f.show();    } }

Creating New Classes

The AppFrame class is based on the Java Frame class, which means that AppFrame will have all the built-in Frame class's methods. You can find those methods in Table 10.2.

Table 10.2. Methods of the Frame Class
Method Description
void addNotify() Allows this frame to be displayed by connecting it to a native screen resource
protected void finalize() Called when the frame is about to be disposed of
int getCursorType() Replaced by Component.getCursor()
static Frame[] getFrames() Returns an array containing all frames created by the application
Image getIconImage() Returns the image to be displayed in the minimized icon
MenuBar getMenuBar() Returns the menu bar
int getState() Returns the current state of the frame
String getTitle() Returns the frame's title
boolean isResizable() Specifies whether this frame is resizable by the user
protected String paramString() Returns the parameter string of this frame
void remove(MenuComponent m) Removes the given menu bar from this frame
void removeNotify() Makes this frame undisplayable
void setCursor(int cursorType) Replaced by Component.setCursor(Cursor)
void setIconImage(Image image) Sets the image to be displayed in the minimized icon for this frame
void setMenuBar(MenuBar mb) Sets the menu bar for this frame to the specified menu bar
void setResizable(boolean resizable) Specifies whether this frame is resizable by the user
void setState(int state) Sets the state of this frame
void setTitle(String title) Sets the title for this frame to the given string

You can create your own classes with the class statement in Java, as we've seen. The AppFrame class is built on the Frame class, which in object-oriented terms means that AppFrame inherits the Frame class. To indicate that you want one class to be based on another, you use the extends keyword, like this. (Note that I'm not using an access specifier when defining AppFrame, which means that this class will use the default access specifier, which is private.)

import java.awt.*; public class window {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications ");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     .     .     . }

Note also that the Java Frame class is part of the Java Abstract Windowing Toolkit (AWT) package. This means that I must import that package with the statement import java.awt.*;.

Creating a Constructor

This new class needs a constructor because I want to pass the text the window should display to that constructor. You create a constructor simply by creating a method in a class that has the same name as the class. In this case, that's AppFrame (constructors do not specify any return value):

import java.awt.*; import java.awt.event.*; public class window {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications ");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     String displayText;     public AppFrame(String text)     {     .     .     .     } }

You might notice that the methods I'm adding to the AppFrame class are not declared static. That's because these methods will be used only as part of an object, not as class methods. In particular, I create an object of the AppFrame class named f in the main method, and I use the methods of that object.

I'll store the text passed to the constructor in a string named displayText this way:

import java.awt.*; import java.awt.event.*; public class window {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications ");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     String displayText;     public AppFrame(String text)     {         displayText = text;     } }

Using Graphics Objects

The next step is to display the text in the window itself. The Frame class has a method named paint that is automatically called whenever the window needs to be drawn on the screen. This method is passed an object of the Java Graphics class, which I will call g:

import java.awt.*; import java.awt.event.*; public class window {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications ");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     String displayText;     public AppFrame(String text)     {         displayText = text;     }     public void paint(Graphics g)     {     .     .     .     } }

You can use the Graphics object's methods to draw in a window, and you'll find those methods in Table 10.3.

Table 10.3. Methods of the Graphics Class
Method Description
abstract void clearRect(int x, int y, int width, int height) Clears a rectangle (fills it with the background color)
abstract void clipRect(int x, int y, int width, int height) Clips a rectangle
abstract void copyArea(int x, int y, int width, int height, int dx, int dy) Copies an area of size dx and dy
abstract Graphics create() Creates a new graphics object and makes it a copy of the current one
Graphics create(int x, int y, int width, int height) Creates a new graphics object, with a new translation and clip area
abstract void dispose() Disposes of a graphics context
void draw3DRect(int x, int y, int width, int height, boolean raised) Displays a 3D rectangle
abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws a circular or elliptical arc
void drawBytes(byte[] data, int offset, int length, int x, int y) Draws the text stored in the byte array
void drawChars(char[] data, int offset, int length, int x, int y) Draws the text stored in the character array
abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) Draws as much of the specified image as is possible, letting you specify a background color
abstract boolean drawImage(Image img, int x, int y, ImageObserver observer) Draws as much of the specified image as possible
abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) Draws as much of the image as can fit inside the rectangle
abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) Draws as much of the given image as has been scaled to fit inside the rectangle
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) Draws as much of the image as possible, scaling it to fit inside the given area
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) Draws as much of the area of the image as possible, scaling it to fit inside the given area of the destination surface
abstract void drawLine(int x1, int y1, int x2, int y2) Draws a line, in the current default color between the points (x1, y1) and (x2, y2)
abstract void drawOval(int x, int y, int width, int height) Draws the outline of an oval
abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws a closed polygon as defined by the x and y coordinate arrays
void drawPolygon(Polygon p) Draws a polygon defined by the given Polygon object
abstract void drawPolyline (int[] xPoints, int[] yPoints, int[] nPoints) Draws a sequence of connected lines
void drawRect(int x, int y, int width, int height) Draws the specified rectangle
abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Draws a round-cornered rectangle
abstract void drawString (AttributedCharacterIterator iterator, int x, int y) Draws the text given by the iterator
abstract void drawString (String str, int x, int y) Draws the text given by the string
void fill3DRect(int x, int y, int width, int height, boolean raised) Paints a filled 3D rectangle
abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Fills a circular or elliptical arc
abstract void fillOval(int x, int y, int width, int height) Fills an oval bounded by the given rectangle
abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) Fills a closed polygon defined by arrays of x and y coordinates
void fillPolygon(Polygon p) Fills the polygon defined by the Polygon object with the current color
abstract void fillRect(int x, int y, int width, int height) Fills the specified rectangle
abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Fills a rounded corner rectangle
void finalize() Called when the object is about to be disposed of
abstract Shape getClip() Returns the clipping area
abstract Rectangle getClipBounds() Returns the bounding rectangle of the clipping area
Rectangle getClipBounds(Rectangle r) Returns the bounding rectangle of the clipping area for a specific rectangle
Rectangle getClipRect() Replaced by getClipBounds()
abstract Color getColor() Returns this graphics context's current foreground color
abstract Font getFont() Returns the current font
FontMetrics getFontMetrics() Returns the font metrics of the default font
abstract FontMetrics getFontMetrics(Font f) Returns the font metrics for the given font
boolean hitClip(int x, int y, int width, int height) Is true if the given area intersects the rectangle of the clipping area
abstract void setClip(int x, int y, int width, int height) Sets the current clip to the given rectangle
abstract void setClip(Shape clip) Sets the clipping area to a shape
abstract void setColor(Color c) Sets the graphics context's foreground color
abstract void setFont(Font font) Sets the graphics context's font
abstract void setPaintMode() Sets the paint mode
abstract void setXORMode(Color c1) Sets the paint mode to use XOR painting
String toString() Returns a String object that represents the Graphics object
abstract void translate (int x, int y) Translates the origin of the graphics context to a new origin

In this case, I'll use the drawString method to display the text in the window, like this:

import java.awt.*; import java.awt.event.*; public class window {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications ");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     String displayText;     public AppFrame(String text)     {         displayText = text;     }     public void paint(Graphics g)     {         g.drawString(displayText, 60, 100);     } }

Closing Application Windows

There's one more refinement to make; when the user clicks the Close button at the upper right in the window we're creating, we'll need to handle the window closing event that occurs. To handle events in Java, you use an event listener. In this case, I'll use an event listener to catch the window closing event and, when that event occurs, end the program using the call System.exit(0);. This call ends the program and passes a value of 0 (which indicates normal termination) as an exit code to the operating system.

Handling Java events in detail is beyond the scope of this book, but here's how it works in this case, I'll add a window listener to the AppFrame object that will "listen" for window closing events and, when one occurs, end the program. Note that to handle events with AWT objects, you must import the classes in the java.awt.event package:

import java.awt.*; import java.awt.event.*; public class window {    public static void main(String argv[]) {        AppFrame f = new AppFrame("Creating windowed Java applications ");        f.setSize(400, 200);        f.addWindowListener(new WindowAdapter() {public void            windowClosing(WindowEvent e) {System.exit(0);}});        f.show();    } } class AppFrame extends Frame {     String displayText;     public AppFrame(String text)     {         displayText = text;     }     public void paint(Graphics g)     {         g.drawString(displayText, 60, 100);     } }

You can see the results of this code in Figure 10.2. When you start this application, the window appears, displaying the text as shown.

Figure 10.2. Running a windowed Java application.

graphics/10fig02.gif

Now that we're in the Java business, it's time to put all this technology to work with XML. I'll do that in the next chapter.

CONTENTS


Inside XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 23
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net