|
|
|
| Day 1An Introduction to Java Programmingby Laura Lemay
Hello and welcome to Teach Yourself Java in 21 Days! Starting today and for the next few weeks you'll learn all about the Java language and how to use it to create programs that run inside Web pages (called applets) and programs that can run on their own (called applications). That's the overall goal for the next couple weeks. Today, the goals are somewhat more modest, and you'll learn about the following:
What Is Java?Based on the enormous amount of press Java is getting and the amount of excitement it has generated, you may get the impression that Java will save the world-or at least solve all the problems of the Internet. Not so. Java's hype has run far ahead of its capabilities, and while Java is indeed new and interesting, it really is another programming language with which you write programs that run on the Internet. In this respect, Java is closer to popular programming languages such as C, C++, Visual Basic, or Pascal, than it is to a page description language such as HTML, or a very simple scripting language such as JavaScript.More specifically, Java is an object-oriented programming language developed by Sun Microsystems, a company best known for its high-end UNIX workstations. Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that Java programs (applets and applications) can run on any machine that has the Java virtual machine installed (you'll learn more about this later). Java is usually mentioned in the context of the World Wide Web, where browsers such as Netscape's Navigator and Microsoft's Internet Explorer claim to be "Java enabled." Java enabled means that the browser in question can download and play Java programs, called applets, on the reader's system. Applets appear in a Web page much the same way as images do, but unlike images, applets are dynamic and interactive. Applets can be used to create animation, figures, forms that immediately respond to input from the reader, games, or other interactive effects on the same Web pages among the text and graphics. Figure 1.1 shows an applet running in Netscape 3.0. (This applet, at http://prominence.com/java/poetry/, is an electronic version of the refrigerator magnets that you can move around to create poetry or messages.) Figure 1.1 : Netscape running a Java applet.
To create an applet, you write it in the Java language, compile it using a Java compiler, and refer to that applet in your HTML Web pages. You put the resulting HTML and Java files on a Web site in the same way that you make ordinary HTML and image files available. Then, when someone using a Java-enabled browser views your page with the embedded applet, that browser downloads the applet to the local system and executes it, allowing your reader to view and interact with your applet in all its glory. (Readers using other browsers may see text, a static graphic, or nothing.) You'll learn more about how applets, browsers, and the World Wide Web work together later in this book. While applets are probably the most popular use of Java, the important thing to understand about Java is that you can do so much more with it than create and use applets. Java was written as a full-fledged general-purpose programming language in which you can accomplish the same sorts of tasks and solve the same sorts of problems that you can in other programming languages, such as C or C++. Java's Past, Present, and FutureThe Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devices-television sets, VCRs, toasters, and the other sorts of machines you can buy at any department store. Java's goals at that time were to be small, fast, efficient, and easily portable to a wide range of hardware devices. Those same goals made Java an ideal language for distributing executable programs via the World Wide Web and also a general-purpose programming language for developing programs that are easily usable and portable across different platforms.The Java language was used in several projects within Sun (under the name Oak), but did not get very much commercial attention until it was paired with HotJava. HotJava, an experimental World Wide Web browser, was written in 1994 in a matter of months, both as a vehicle for downloading and running applets and also as an example of the sort of complex application that can be written in Java. Although HotJava got a lot of attention in the Web community, it wasn't until Netscape incorporated HotJava's ability to play applets into its own browser that Java really took off and started to generate the excitement that it has both on and off the World Wide Web. Java has generated so much excitement, in fact, that inside Sun the Java group spun off into its own subsidiary called JavaSoft. Versions of Java itself, or, as it's most commonly called, the Java API, correspond to versions of Sun's Java Developer's Kit, or JDK. As of this writing, the current version of the JDK is 1.0.2. Previously released versions of the JDK (alphas and betas) did not have all the features or had a number of security-related bugs. Most Java tools and browsers conform to the features in the 1.0.2 JDK, and all the examples in this book run on that version as well. The next major release of the JDK and therefore of the Java API will be 1.1, with a prerelease version available sometime in the later part of 1996. This release will have few changes to the language, but a number of additional capabilities and features added to the class library. Throughout this book, if a feature will change or will be enhanced in 1.1, we'll let you know, and in the last two days of this book you'll find out more about new Java features for 1.1 and for the future. Currently, to program in Java, you'll need a Java development environment of some sort for your platform. Sun's JDK works just fine for this purpose and includes tools for compiling and testing Java applets and applications. In addition, a wide variety of excellent Java development environments have been developed, including Sun's own Java Workshop, Symantec's Café, Microsoft's Visual J++ (which is indeed a Java tool, despite its name), and Natural Intelligence's Roaster, with more development tools appearing all the time. To run and view Java applets, you'll need a Java-enabled browser or other tool. As mentioned before, recent versions of Netscape Navigator (2.0 and higher) and Internet Explorer (3.0) can both run Java applets. (Note that for Windows you'll need the 32-bit version of Netscape, and for Macintosh you'll need Netscape 3.0.) You can also use Sun's own HotJava browser to view applets, as long as you have the 1.0 prebeta version (older versions are not compatible with newer applets, and vice versa). Even if you don't have a Java-enabled browser, many development tools provide simple viewers with which you can run your applets. The JDK comes with one of these; it's called the appletviewer.
What's in store for Java in the future? A number of new developments have been brewing (pardon the pun):
Why Learn Java?At the moment, probably the most compelling reason to learn Java-and probably the reason you bought this book-is that applets are written in Java. Even if that were not the case, Java as a programming language has significant advantages over other languages and other environments that make it suitable for just about any programming task. This section describes some of those advantages.Java Is Platform IndependentPlatform independence-that is, the ability of a program to move easily from one computer system to another-is one of the most significant advantages that Java has over other programming languages, particularly if your software needs to run on many different platforms. If you're writing software for the World Wide Web, being able to run the same program on many different systems is crucial to that program's success. Java is platform independent at both the source and the binary level.
At the source level, Java's primitive data types have consistent sizes across all development platforms. Java's foundation class libraries make it easy to write code that can be moved from platform to platform without the need to rewrite it to work with that platform. When you write a program in Java, you don't need to rely on features of that particular operating system to accomplish basic tasks. Platform independence at the source level means that you can move Java source files from system to system and have them compile and run cleanly on any system. Platform independence in Java doesn't stop at the source level, however. Java compiled binary files are also platform independent and can run on multiple platforms (if they have a Java virtual machine available) without the need to recompile the source. Normally, when you compile a program written in C or in most other languages, the compiler translates your program into machine code or processor instructions. Those instructions are specific to the processor your computer is running-so, for example, if you compile your code on an Intel-based system, the resulting program will run only on other Intel-based systems. If you want to use the same program on another system, you have to go back to your original source code, get a compiler for that system, and recompile your code so that you have a program specific to that system. Figure 1.2 shows the result of this system: multiple executable programs for multiple systems. Figure 1.2 : Traditional compiled programs. Things are different when you write code in Java. The Java development environment actually has two parts: a Java compiler and a Java interpreter. The Java compiler takes your Java program and, instead of generating machine codes from your source files, it generates bytecodes. Bytecodes are instructions that look a lot like machine code, but are not specific to any one processor. To execute a Java program, you run a program called a bytecode interpreter, which in turn reads the bytecodes and executes your Java program (see Figure 1.3). The Java bytecode interpreter is often also called the Java virtual machine or the Java runtime.
Where do you get the bytecode interpreter? For applets, the bytecode interpreter is built into every Java-enabled browser, so you don't have to worry about it-Java applets just automatically run. For more general Java applications, you'll need to have the interpreter installed on your system in order to run that Java program. Right now, you can get the Java interpreter as part of your development environment, or if you buy a Java program, you'll get it with that package. In the future, however, the Java bytecode interpreter will most likely come with every new operating system-buy a Windows machine, and you'll get Java for free. Why go through all the trouble of adding this extra layer of the bytecode interpreter? Having your Java programs in bytecode form means that instead of being specific to any one system, your programs can be run on any platform and any operating or window system as long as the Java interpreter is available. This capability of a single binary file to be executable across platforms is crucial to what makes applets work because the World Wide Web itself is also platform independent. Just as HTML files can be read on any platform, so can applets be executed on any platform that has a Java-enabled browser. The disadvantage of using bytecodes is in execution speed. Because system-specific programs run directly on the hardware for which they are compiled, they run significantly faster than Java bytecodes, which must be processed by the interpreter. For many basic Java programs, speed may not be an issue. If you write programs that require more execution speed than the Java interpreter can provide, you have several solutions available to you, including being able to link native code into your Java program or using special tools (called just-in-time compilers) to convert your Java bytecodes into native code and speed up their execution. Note that by using any of these solutions, you lose the portability that Java bytecodes provide. You'll learn about each of these mechanisms on Day 20, "Using Native Methods and Libraries." Java Is Object OrientedTo some, the object-oriented programming (OOP) technique is merely a way of organizing programs, and it can be accomplished using any language. Working with a real object-oriented language and programming environment, however, enables you to take full advantage of object-oriented methodology and its capabilities for creating flexible, modular programs and reusing code.Many of Java's object-oriented concepts are inherited from C++, the language on which it is based, but it borrows many concepts from other object-oriented languages as well. Like most object-oriented programming languages, Java includes a set of class libraries that provide basic data types, system input and output capabilities, and other utility functions. These basic libraries are part of the standard Java environment, which also includes simple libraries, form networking, common Internet protocols, and user interface toolkit functions. Because these class libraries are written in Java, they are portable across platforms as all Java applications are. You'll learn more about object-oriented programming and Java tomorrow. Java Is Easy to LearnIn addition to its portability and object orientation, one of Java's initial design goals was to be small and simple, and therefore easier to write, easier to compile, easier to debug, and, best of all, easy to learn. Keeping the language small also makes it more robust because there are fewer chances for programmers to make mistakes that are difficult to fix. Despite its size and simple design, however, Java still has a great deal of power and flexibility.Java is modeled after C and C++, and much of the syntax and object-oriented structure is borrowed from the latter. If you are familiar with C++, learning Java will be particularly easy for you because you have most of the foundation already. (In fact, you may find yourself skipping through the first week of this book fairly rapidly. Go ahead; I won't mind.) Although Java looks similar to C and C++, most of the more complex parts of those languages have been excluded from Java, making the language simpler without sacrificing much of its power. There are no pointers in Java, nor is there pointer arithmetic. Strings and arrays are real objects in Java. Memory management is automatic. To an experienced programmer, these omissions may be difficult to get used to, but to beginners or programmers who have worked in other languages, they make the Java language far easier to learn. However, while Java's design makes it easier to learn than other programming languages, working with a programming language is still a great deal more complicated than, say, working in HTML. If you have no programming language background at all, you may find Java difficult to understand and to grasp. But don't be discouraged! Learning programming is a valuable skill for the Web and for computers in general, and Java is a terrific language to start out with. Getting Started Programming in JavaEnough background! For the second half of this day let's actually dive into simple Java programming and create two Java programs: a standalone Java application and an applet that you can view in a Java-enabled browser. Although both these programs are extremely simple, they will give you an idea of what a Java program looks like and how to compile and run it.Getting a Java Development EnvironmentIn order to write Java programs, you will, of course, need a Java development environment. (Although browsers such as Netscape allow you to play Java applets, they don't let you write them. For that you'll need a separate tool.) Sun's JDK, which is available for downloading at the JavaSoft Web site (http://www.javasoft.com/) and included on the CD for this book, will do just fine. It runs on Solaris, Windows 95 and NT, and Macintosh. However, despite the JDK's popularity, it is not the easiest development tool to use. If you're used to using a graphical user interface-based development tool with an integrated editor and debugger, you'll most likely find the JDK's command-line interfaces rather primitive. Fortunately, the JDK is not the only tool in town.As mentioned earlier, a number of third-party development environments (called integrated development environments, or IDEs) are also available for developing in Java. These include Sun's Java Workshop for Solaris, Windows NT and Windows 95 (you can get more information about it at http://www.sun.com/developer-products/java/); Symantec's Café for Windows 95, Windows NT, and Macintosh (http://cafe.symantec.com/); Microsoft's Visual J++ for Windows 95 and Windows NT (http://www.microsoft.com/visualj/); and Natural Intelligence's Roaster (http://www.natural.com/pages/products/roaster/index.html). All three are commercial programs, but you might be able to download trial or limited versions of these programs to try them out. You'll learn more about the features and capabilities of the various Java IDEs on Day 22, "Java Programming Tools."
Installing the JDK and Sample FilesSun's JDK for Solaris, Windows, and Macintosh is included as part of the CD-ROM that comes with this book. Also on the CD-ROM are all of the code examples from this book-a great help if you don't want to type them all in again. To install either the JDK or the sample files (or both), use one of the following procedures:
To install the JDK or the sample files on Windows, run the Setup program on the CD-ROM (double-clicking the CD icon will do this automatically). By default, the package will be installed into C:\Java; you can install it anywhere on your hard disk that you'd like. You'll be given options to install the JDK, the sample files, and various other extra files; choose the options you want and those files will be installed. If you've installed the JDK, note that in the directory JDK\lib there is a file called classes.zip. Do not unzip this file; it needs to remain in zip form for it to work correctly. The file JDK\src.zip contains the source code for many of the JDK libraries; you can unzip this one if you like. Make sure if you do that you have a zip program that supports long filenames, or it will not work correctly!
To install the JDK or the sample files on the Macintosh, double-click the installation program on the CD-ROM. By default, the package will be installed into the folder Java on your hard disk; you can install it anywhere on your disk that you'd like. You'll be given options to install the JDK, the sample files, and various other extra files; choose the options you want and those files will be installed.
The CD-ROM for this book contains the tarred and zipped JDK in the directory jdk/solaris/jdk1.02.tgz. Using the utilities gunzip and tar, you can extract the contents of that file anywhere on the file system you would like. For example, if you copy the .tgz file to your home directory and use the following commands to extract it, you'll end up with a java directory that contains the full JDK: Note that in the directory java\lib there is a file called classes.zip. Do not unzip this file; it needs to remain in zip form for it to work correctly. The file java\src.zip contains the source code for many of the JDK libraries; you can unzip this one if you're interested in the source code.gunzip ./jdk1.02.tgz The sample files are also contained on the CD-ROM in authors/authors.tar. Create a directory where the sample files will live (for example, a directory called javasamples in your home directory), copy the authors.tar file there, and then use the tar command to extract it, like this: mkdir ~/javasamples Configuring the JDKIf you've installed the JDK using the setup programs from the CD-ROM, chances are good that it has been correctly configured for you. However, because most common problems with Java result from configuration errors, I recommend that you double-check your configuration to make sure everything is right. And if you've installed the JDK from a source other than the CD-ROM, you'll definitely want to read this section to make sure you're all set up.
Edit your autoexec.bat file using your favorite editor (Notepad will do just fine). Look for a line that looks something like this: Somewhere in that line you should see an entry for the JDK; if you installed the JDK from CD-ROM, it'll look something like this (the dots are there to indicate that there may be other stuff on this line):PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\DOS; ... If you cannot find any reference to JDK\BIN or JAVA\BIN in your PATH, you'll need to add it. Simply include the full pathname to your JDK installation to the end of that line, starting with C: and ending with BIN; for example, C:\JAVA\BIN or C:\Java\JDK\BIN.PATH C:\WINDOWS; ... C:\TEAchY~1\JDK\BIN; ...
The second thing you'll need to add to the autoexec.bat file (if it isn't already there) is a CLASSPATH variable. Look for a line that looks something like this: The CLASSPATH variable may also have other entries in it for Netscape or Internet Explorer, but the one you're most interested in is a reference to the classes.zip file in the JDK, and to the current directory (.). If your autoexec.bat file does not include either of these locations, add a line to the file that contains both these things (the line shown above will work just fine).SET CLASSPATH=C:\TEAchY~1\JDK\lib\classes.zip;.; After saving your autoexec.bat file, you'll need to restart Windows for the changes to take effect.
This line assumes that you've installed the JDK (as the directory java) into your home directory; if you've installed it somewhere else, you'll want to substitute that pathname.set path= (~/java/bin/ $path) Make sure you use the source command with the name of the appropriate file to make sure the changes take effect (or log out and log back in again): source ~/.login Creating a Java ApplicationNow let's actually get to work. We'll start by creating a simple Java application: the classic Hello World example that many programming language books use to begin.Java applications are different from Java applets. Applets, as you have learned, are Java programs that are downloaded over the World Wide Web and executed by a Web browser on the reader's machine. Applets depend on a Java-enabled browser in order to run.
Java applications are standalone Java programs that do not require a Web browser to run. Java applications are more general-purpose programs such as you'd find on any computer. A single Java program can be an applet or an application, or both, depending on how you write that program and the capabilities that program uses. Throughout this first week as you learn the Java language, you'll be writing mostly applications; then you'll apply what you've learned to write applets in Week 2. If you're eager to get started with applets, be patient. Everything that you learn while you're creating simple Java applications will apply to creating applets, and it's easier to start with the basics before moving onto the hard stuff. You'll be creating plenty of applets in Week 2. Creating the Source FileAs with all programming languages, your Java source files are created in a plain text editor, or in an editor that can save files in plain ASCII without any formatting characters. On UNIX, emacs, pico, and vi will work; on Windows, Notepad or DOS Edit are both text editors that will work (although I prefer to use the shareware TextPad). On the Macintosh, SimpleText (which came with your Mac) or the shareware BBedit will work. If you're using a development environment like Café or Roaster, it'll have its own built-in text editor you can use.
Fire up your editor of choice and enter the Java program shown in Listing 1.1. Type this program, as shown, in your text editor. Be careful that all the parentheses, braces, and quotes are there, and that you've used all the correct upper- and lowercase letters.
Listing 1.1. Your first Java application. 1: class HelloWorld {
After you've finished typing in the program, save the file somewhere on your disk with the name HelloWorld.java. This is very important. Java source files must have the same name as the class they define (including the same upper- and lowercase letters), and they must have the extension .java. Here, the class definition has the name HelloWorld, so the filename must be HelloWorld.java. If you name your file something else (even something like helloworld.java or Helloworld.java), you won't be able to compile it. Make absolutely certain the name is HelloWorld.java. You can save your Java files anywhere you like on your disk, but I like to have a central directory or folder to keep them all in. For the examples in this chapter, I've put my files into a directory called TYJtests (short for Teach Yourself Java Tests). Compiling and Running the Source FileNow it's time to compile the file. If you're using the JDK, you can use the instructions for your computer system contained in the next few pages. If you're using a graphical development environment, there will most likely be a button or option to compile the file (check with the documentation that came with your program).
From inside DOS, change directories to the location where you've saved your HelloWorld.java file. I put mine into the directory TYJtests, so to change directories I'd use this command: Once you've changed to the right directory, use the javac command as follows, with the name of the file as you saved it in Windows (javac stands for Java compiler). Note that you have to make sure you type all the same upper- and lowercase here as well:CD C:\TYJtests javac HelloWorld.java
Figure 1.4 shows what I've done in the DOS shell so you can make sure you're following along. Figure 1.4 : Compiling Java in the DOS shell. If all goes well, you'll end up with a file called HelloWorld.class (or at least that's what it'll be called if you look at it outside the DOS shell; from inside DOS its called HELLOW~1.cla). That's your Java bytecode file. If you get any errors, go back to your original source file and make sure you typed it exactly as it appears in Listing 1.1 with the same upper- and lowercase. Also make sure the filename has exactly the same upper- and lowercase as the name of the class (that is, both should be HelloWorld). Once you have a class file, you can run that file using the Java bytecode interpreter. The Java interpreter is called simply java, and you run it from the DOS shell as you did javac. Run your Hello World program like this from the command line, with all the same upper- and lowercase (and note that the argument to the java program does not have a .class extension): If your program was typed and compiled correctly, you should get the phrase Hello World! printed to your screen as a response. Figure 1.5 shows how I did it.java HelloWorld Figure 1.5 : Running Java applications in the DOS shell.
If you get any errors, go back to your original source file and make sure you typed it exactly as it appears in Listing 1.1, with the same upper- and lowercase. Also make sure the filename has exactly the same upper- and lowercase as the name of the class (that is, both should be HelloWorld). Once you've successfully generated a HelloWorld.class file, simply double-click it to run it. The application Java Runner, part of the Mac JDK, will start, and the program will ask you for command-line arguments. Leave that screen blank and click OK. A window labeled stdout will appear with the message Hello World!. Figure 1.6 shows that window. Figure 1.6 : Running Java applications on the Mac using Java Runner. That's it! Keep in mind as you work that you use the Java Compiler application to compile your .java files into .class files, which you can then run using Java Runner. To compile the Java source file in Solaris, you'll use the command-line Java compiler that comes with the JDK. From a UNIX command line, cd to the directory that contains your Java source file. I put mine in the directory TYJtests, so to change directories I'd use this command: Once you're in the right directory, use the javac command with the name of the file, like this:cd ~/TYJtests If all goes well, you'll end up with a file called HelloWorld.class in the same directory as your source file. That's your Java bytecode file. If you get any errors, go back to your original source file and make sure you typed it exactly as it appears in Listing 1.1, with the same upper- and lowercase letters. Also make sure the filename has exactly the same upper- and lowercase letters as the name of the class (that is, both should be HelloWorld).javac HelloWorld.java Once you have a class file, you can run that file using the Java bytecode interpreter. The Java interpreter is called simply java, and you run it from the command line as you did javac, like this (and note that the argument to the java program does not have a .class extension): If your program was typed and compiled correctly, you should get the phrase Hello World! printed to your screen as a response. Figure 1.7 shows a listing of all the commands I used to get to this point (the part with [desire]~[1] is my system prompt).java HelloWorld Figure 1.7 : Compiling and running a Java application on Solaris.
Creating a Java AppletCreating applets is different from creating a simple application. Java applets run and are displayed inside a Web page with other page elements, and therefore have special rules for how they behave. Because of these special rules for applets, creating an applet may in many cases be more complex than creating an application.For example, to create a simple Hello World applet, instead of merely being able to print a message as a set of characters, you have to make space for your message on the Web pages and then use special font and graphics operations to paint the message to the screen.
Creating the Source FileIn this example, you'll create a simple Hello World applet, place it inside a Web page, and view the result. As with the Hello World application, you'll first create the source file in a plain text editor. Listing 1.2 shows the code for the example.Listing 1.2. The Hello World applet. 1: import java.awt.Graphics; Save that file just as you did the Hello World application, with the filename exactly the same as the name of the class. In this case the class name is HelloWorldApplet, so the filename you save it to would be HelloWorldApplet.java. As with the application, I put the file in a directory called TYJch01, but you can save it anywhere you like. Compiling the Source FileThe next step is to compile the Java applet file. Despite the fact that this is an applet, you compile the file exactly the same way you did the Java application, using one of the following procedures:javac HelloWorldApplet.java
Including the Applet in a Web PageIf you've typed the file correctly, you should end up with a file called HelloWorldApplet.class in the same directory as your source file. That's your Java applet file; to have the applet run inside a Web page you must refer to that class file inside the HTML code for that page using the |
Saturday, November 8, 2008
# What Is Java?# Java's Past, Present, and Future,,Getting a Java Development Environm#,Java Is Object Oriented,# Getting Started Programming in Java,
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment