This chapter will give you an appreciation of what the Java language is all about. Understanding the details that we'll introduce in this chapter is not important at this stage; You will see all of them again im greater depth in later chapters of the book. The intent of this chapter is to introduce you to the general ideas that underpin what we'll be covering through the rest of the book, as well as the contexts in which Java programs can be used and the kind of program that is applicable in each context.
In this chapter you will learn:
The basic characteristics of the Java language.
How Java programs work on your computer.
Why Java programs are portable between different computers.
The basic ideas behind object-oriented programming.
How a simple Juva program looks and how you can run it using the Java Development Kit.
What HTML is and how it is used to include a java program in a Web page.
What is Java All About?
Java is an innovative programming language that is becoming the language of choice for programs that need to run on a variety of different computer systems. First of all Java enables you to write small programs called applets. These are programs that you can embed in Internet Web pages to provide some intelligence. They might simply display an animated logo, or support data entry of some kind. Java also allows you to write large-scale application programs that you can run normally on any computer that supports the language. You can even write programs that will work both as ordinary applications and as applets. Java has matured immensely over the past couple of years, particularly with the introduction of Java 2. The breadth of capability provided by the standard core Java has grown incredibly, with the latest release extending into sampled sound and MIDI data processing.
Being able to embed executable code in a Web pave introduces a vast range of exciting possibilities. Instead of being a passive presentation of text and graphics, a Web page can be interactive in any way that ou want. You can include animations, games, interactive transaction processing - the possibilities are almost unlinited.
Of course, embedding program code in a Web page creates special security requirements. As an Internet user accessing a page with embedded Java code, you need to be confident that it will not do anything that might interfere with the operation of your computer, or damage the data of your system. This implies that the execution of the embedded code must be controlled in such a way that it will prevent accidental damage to your computer environment, as well as ensure that any Java code that was created with malicious intent is effectively inhibited. Java implicitly incorporates measures to minimize the possibility of such occurrences arising with a Java applet.
Aside from its ability to create programs that can be embedded in a Web page, perhaps the most important characteristic of Java is that it was designed from the outset to be machine independent. Java programs can run unchanged on any computer that supports Java. Of course there is still the slim possibility of the odd glitch as you are ultimately dependent on the implementation of Java on any particular machine, but Java programs are intrinsically more portable than programs written in other languages. An interactive application written in Java will only require a single set of source code, regardless of the number of different computer platforms on which it is run. In any other programming language, the application will frequently require the source code to be tailored to accommodate different computer environments, particularly if there is an extensive graphical user interface involved.
Possibly the next most important characteristic of Java is that it is object oriented. The object-oriented approach to programming is also an implicit feature of all Java programs, so we will be looking at what this implies later in this chapter. Not only is Java object oriented, but it also manages to avoid many of the difficulties and complications that are inherent in some other object - oriented languages, making it very straightforward and easy to learn.
Learning Java
Java is not difficult, but there is a great deal to it. The language itself is fairly compact, but very powerful. To be able to program effectively in Java, however, you also need to understand the libraries that go with the language, and there are very extensive. In this book, the sequence in which you learn how the language works, and how you apply it, has been carefully structured so that you can gain expertise and confidence with programming in Java through a relatively easy and painless process. As far as possible, each chapter avoids the use of things you haven't learned about already. A consequence, though, is that you won't be writing lava to be embedded in Web pages right away. While it may be an appealing idea, this would be a bit like learning to swim by jumping in the pool at the deep end. Generally speaking, there is good evidence that by starting in the shallow end of the pool and learning how to float before you try to swim, the chance of drowning is minimized, and there is a high expectation that you will end up a competent swimmer.
Java Programs
As we have already noted, there are two kinds of programs you can write in Java. Programs that are to be embedded in a Web page are called Java applets, and normal standalone programs are called Java applications. You can further subdivide Java applications into console applications, which only support character output to your computer screen (in a DOS window on a PC under Windows, for example). and windowed Java applications that can create and manage multiple windows. The latter use the typical graphical user interaction (GUI) mechanisms of window - based programs - menus, toolbars, dialogs and so on.
While we are learning the Java language basics, we will be using console applications as examples to illustrate how things work. This is because we can then focus on the specifics of the language, without worrying about any of the complexity involved in creating and managing windows. Once we are comfortable with using all the features of the Java language, we'll move on to windowed applications and applet examples.
Learning Java - the Road Ahead
Before starting out, it is always helpful to have an idea of where you are heading and what route you should take, so let's take a look at a brief road map of where you will be going with Java. There are five broad stages you will progress through in learning Java using this book:
The first stage is this chapter. It sets out some fundamental ideas about the structure of Java programs and how they work. This includes such things as what object - oriented programming is all about, and how an executable program is created from a Java source file. Getting these concepts straight at the outset will make learning to write Java programs that much easier for you.
Next you will learn how statements are put together, what facilities you have for storing basic data in a program, how you perform calculations and how you make decisions based on the results of them. These are the nuts and bolts you need for the next stages.
In the third stage you will learn about classes - how you define them and how you can use them. This is where you learn the object - oriented characteristics of the language. By the time you are through this stage you will have learned all the basics of how the Java language works so you will be ready to progress further into how you can use it.
In the fourth stage, you will learn how you can segment the activities that your programs carry out into separate tasks that can execute concurrently. This is particularly important for when you want to include several applets in a Web page, and you don't want one applet to have to wait for another to finish executing before it can start. You may want a fancy animation to continue running while you play a game, for example, with both programs sitting in the same Web page.
In the fifth stage you will learn in detail how you implement an application or an applet with graphical user interface, and how you handle interactions with the user in this context. This amounts to applying the capabilities provided by the Java class libraries. As well as learning about GUI implementation, you will also learn about handling images in various ways, as well as using the database access facilities in Java. You will also learn a bit about how you can handle sound in your programs, and how you can access relational databases. When you. finish this stage you will be equipped to write your own fully - fledged applications and applets in Java. At the end of the book, you should be a knowiedgeable Java programmer. The rest is down to experience.
Throughout this book we will be using complete examples to explore how Java works. You should create and run all of the examples, even the simplest, preferably by typing them in yourself. Don't be afraid to experiment with them. If there is anything you are not quite clear on, try changing an example around to see what happens, or better still, write an example of your own. If you are uncertain how some aspect of Java that you have already covered works, don't look it op right away - try it out. Making mistakes is a great way to learn.
The Java Environment
Java programs will run just as well on a PC running Windows 95/98 / NT / 2X as it will on Linux or a You can run Java programs on a wide variety of computers using a range of operating systems. Your Sun Solaris workstation. This is possible because a Java program does not execute directly on your computer. It runs on a standardized hypothetical computer that is called the Java virtual machine or JVM, which is emulated inside your computer by a program.
Java work
A Java compiler converts the Java source code that you write into a binary program consisting of byte codes. Byte codes are machine instructions for the Java virtual machine. When you execute a Java program, a program called the Java interpreter inspects and deciphers the byte codes for it, checks it out to ensure that it has not been tampered with and is safe to execute, and then executes the actions that specify the byte codes. within the Java virtual machine. A Java interpreter can run stand-alone. or it can be part of a Web browser such as Netscape Navigator or Microsoft Internet Explorer where it can be invoked automatically to run applets in a Web page.
Because your Java program consists of byte codes rather than native machine instructions, it is completely insulated from the particular hardware on which it is run. Any computer that has the Java environment implemented will handle your program as well as any other, and because the Java interpreter sits between your program and the physical machine, it can prevent unauthorized actions in the program from being executed.
In the past there has been a penalty for all this flexibility and protection in the speed of execution of your Java programs. An interpreted Java program would typically run at only one tenth of the speed of an equivalent program using native machine instructions. With present Java machine implementations, much of the performance penalty has been eliminated, and in programs that are not computation intensive - which is usually the case with the sort of program you would want to include in a Web page. for example - you really wouldn't notice this anyway. With the JVM that is supplied with the current Java Development Kit (JDK) available from the Sun web site, there are very few circumstances where you will notice any appreciable degradation in performance compared to a program compiled to native machine code. If you happen to have a Java environment that supports 'Just - In - Time' compilation of your programs, you will not suffer the penalty in any event. On - the - fly compilers can convert your Java programs to native machine instructions as they are loaded. Your programs will take a litle longer te load, but once loaded they execute at maximum speed.
Java Program Development
There are a number of excellent Java program development environments available, including products from Sun, Borland and Symantec. These all provide very friendly environments for creating and editing your source code, and compiling and debugging your programs. These are powerful tools for the experienced programmer, but for learning Java using this book, I recommend that you use the Java Development Kit from Sun. While it is not the easiest to use, the lowest cost development package with the most up-to-date libraries for Java programs is undoubtedly the Java Development Kit (JDK) from Sun, because it is free. You can download this for a variety of hardware platforms and operating systems, either directly from the Sun Java Web site at http://java.sun.com (for Windows, Solaris, and Linux operating systems), or from sites that you can link to from there. For instance a version of the JDK for Mac OS is available from http://www.oracle.com/.
I would urge you to install the JDK even if you are using one or the other of the interactive development environments that are available. The JDK provides an excellent reference environment that you can use to check out problems that may arise. Not only that but your programs will only consist of the code that you write plus the classes from the Java libraries that you use. Virtually all commercial Java development systems provide pre-built facilities of their own to speed development. While this is very helpful for production program development, it really does get in the way when you are trying to learn Java. A further consideration is that the version of Java supported by a commercial Java product is not always the most recent. This means that some features of the latest version of Java just won't work. 1 have problems with running a particular example from the book, try it out with the JDK. The chances are it will work OK
To make use of the JDK you will need a plain text editor. Any editor will do as long as it does not introduce formatting codes into the contents of a file. There are quite a number of shareware and freeware editors around that are suitable, and you should have no trouble locating one. A good place to start looking if you don't have one is http://www.download.com.
Java download for Windows
Java download for Windows 10
Java Update
Java 8 download
Java latest version
java download 64-bit
Java JDK
Java tutorial
Installing the JDK
You can obtain detailed instructions on how to install the JDK for your particular operating system from the Sun web site, so I won't go into all the variations for different systems here. However, there are a few things to watch out for that may not leap out from the pages of the installation documentation
First of all, the JDK and the documentation are separate and you install them separately. You will find it easier to install the JDK first, followed by the documentation. It is important to install the documentation into the same directory as the JDK. By doing this the documentation files will be in the correct directories in relation to the directory hierarchy for the JDK. If you install the JDK to drive C: under Windows, the directory structure shown in the diagram will be created.
Installing JDK
You should now install the documentation to the same directory that you chose for the JDK. This corresponds to C: as we have described here. This will create a new subdirectory, docs, to the jdk1.3 root directory, and install the documentation files to that. You should not install the documentation into C: \ jdk1.3 as you might imagine, otherwise you will get an extra sub - directory jdk1.3, so the documentation will end up in C: \ jdk1.3 \ jdk1.3 \ docs . To look at the documentation you just open the index.html file that is in the docs subdirectory.
You don't need to worry about the contents of most of these directories, at least not to get started, but the jdk1.3 \ bin directory should be in your PATH for convenience. That way you can run the compiler and the interpreter from anywhere without supplying the full path to it. A word of warning if you have previously installed a commercial Java development product. Check that it has not modified your PATH in autoexec.bat to include the path to its own executables. If it has, when you try to run the Java compiler or interpreter, you are likely to get the versions supplied with the commercial product rather that those that came with the JDK. If you do not want to remove the paths that were inserted for the commercial product, you will have to use the full path specification when you want to run the compiler or interpreter from the JDK. The gre directory contains the Java Runtime facilities that are used when you execute a Java program. The classes in the Java libraries are stored in the jre \ lib directory. They don't appear individually though. They are all packaged up in the archive, rt.jar Leave this alone. The Java Runtime takes care of retrieving what it needs from the archive when your program executes.
Extracting the Source Code for the Class Libraries
The source code for the Class libraries is included in the archive sro.jar that you will find in the jdk1.3 root directory. Browsing this source can be very educational, and it can also be helpful when you are more experienced with Java in giving a better understanding of how things work - or when they don't, why they don't. You can extract the source files from the archive using the jar utility, jar.exe, that is in the jdk1.3 \ bin directory - but be warned - there's a lot of it and it takes a while! To extract the source, change to the directory. 3 and execute the command (in a DOS window):
jar xvf src.jar
This will create a new subdirectory, arc, to the current directory, jdk1.3, and install the source code in the subdirectories to this. To look at the source code, just open the .java file that you are interested in, using any plain text editor.
Running a Java Application
Java source code is always stored in files with the extension.java. Once you have created the source code for a program and saved it in a .java file, you need to process the source using a Java compiler. Using the compiler that comes with the JDK, you would do this with the following command:
javac My Program.java
Here, javac is the name of the Java compiler, and My Program.java is the name of the program source file. Assuming your program contains no errors, the compiler generates a byte code program that is the equivalent of your source code. The compiler stores the byte code program in a file with the same name as the source file, but with the extension .class. Java executable modules are always stored in a file with the extension .class.
If you are using some other product to develop your Java programs, you will probably be using a much more user-friendly, graphical interface for compiling your programs that won't involve entering commands such as that shown above. The file name extensions for your source file and the object file that results from it will be just the same however.
To execute the byte code program in the class file with the Java interpreter in the JDK. you enter the command:
Java Myprogram
Note the absence of any file extension here. This is because the name My Program in this instance is not the name of a file, it is the name of a Java class (we will further explain the meaning of this term shortly). If you put a file extension on My Program, your program won't execute. To execute your program, the Java interpreter analyzes and then executes the byte code instructions. The Java virtual machine is identical in all computer environments supporting Java, so you can be sure your program is completely portable. As we have already said, your program will run just as well on a Unix Java implementation as it will on that for Windows 95/98 / NT / 2000, for OS / 2, or any other operating systein that supports Java. (Beware of variations in the level of Java supported though. Some environments, such as the Macintosh, tend to lag a little, so implementations for Java 2 will typically be available later than under Windows or Solaris.)
Note that the Java compiler in the JDK will compile both applications and applets. However, an applet is not executed in the same way as an application. You must embed an applet in a Web page before it appletviewer to run applets while you are learning. This ensures that if your applet doesn't work, it appletviewer, a bare - bones browser provided as part of the JDK. It is a good idea to use the is almost certainly your code that is the problem, rather than some problem in integration with the browser.
If you have compiled an applet and you have included it in a Web page stored as MyApplet.html in the current directory on your computer, you can execute it by entering the command:
appletviewer MyApplet.html
So how do you put an applet in a Web page?
The Hypertext Markup Language
Web page. The HyperText Mark - up Language, or HTML as it is commonly known, is used to define a If you want a good, compact, reference guide to HTML, I recommend the book Instant HTML Programmer's Reference (Gameczone). Here we will gather just enough on HTML 50 that you can run a Java applet. When you define a Web page as an HTML document, it is stored in a file with the extension.html. An HTML document consists of a number of elements, and each element is identified by tags. The document will begin with <HTML> and end with </ HTML>. These delimiters, <html> and </html> are tags, and each element in an HTML document will be enclosed between a similar pair of tags between angle brackets. All element tags are case insensitive, so you can use upper or lower case, or even a mixture of the two, but by convention they are capitalized so they stand out from the text. Here is an example of an HTML document consisting of a title and some other text:
<HTML>
<HEAD>
<TITLE> This is the title of the document </ TITLE>
</ HEAD>
<BODY> You can put whatever text you like here. The body of a document can contain all kinds of other HTML elements, including <B> Java applets </B>. Note how each element always begins with a start tag identifying the element, and ends with an end tag that is the same as the start tag but with a slash added. The pair of tags around Java applets' in the previous sentence will display the text as bold. </BODY>
</HTML>
There are two elements that can appear directly within the <HTML> element, a <HEAD> element and a <BODY> element, as in the example above. The <HEAD> element provides information about the document, and is not strictly part of it. The text enclosed by the <TITLE> element tags that appears here within the <HEAD> element, will be displayed as the window title when the page is viewed.
Other element tags can appear within the <BODY> element, and they include tags for headings, lists, tables, links to other pages and Java applets. There are some elements that do not require an end tag because they are considered to be empty. An example of this kind of element tag is <HR>, which specifies a horizontal rule, a line across the full width of the page. You can use the <HR> tag to divide up a page and separate one type of element from another. You will find a comprehensive list of available HTML tags in the book 1 mentioned earlier.
Adding an Applet to an HTML Document
For many element tag pairs, you can specify an element attribute in the starting tag that defines additional or qualifying data about the element. This is how a Java applet is identified in an <APPLET> tag. Here is an example of how you include a Java applet in an HTML document:
Comments