Monday, December 26, 2011

The Hypertext Markup Language

The Hypertext Markup Language, or HTML as it is commonly known, is used to define a web page. 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 uppercase or lowercase, 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 blog of Java < /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.

Executing an Applet

The Java compiler in the JDK will compile both applications and applets. However, java applet is not executed in the same way as an application. You must embed an applet in a web page before it can be run. You can then execute it either within a Java 2-enabled web browser, or by using the applet-viewer, a bare-bones browser provided as part of the JDK. It is a good idea to use the applet-viewer to run applets while you are learning. This ensures that if your applet doesn’t work, it 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 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.

Executing a Java Application

To execute the bytecode program in the .class file with the Java interpreter in the JDK, you make the directory containing the .class file current and enter the command:

java -enableassertions MyProgram

Note that we use just the name MyProgram to identify the program, not the name of the file generated by the compiler, MyProgram.class. It is a common beginner’s mistake to use the latter by analogy with the compile operation. If you put a .class file extension on MyProgram, your program won’t execute, and you will get an error message:

Exception in thread “main” java.lang.NoClassDefFoundError: MyProgram/class

While the compiler expects to find the name of your source file, the java application interpreter expects the name of a class, which is MyProgram in this case, not the name of a file. The MyProgram.class file contains the MyProgram class. We will explain what a class is shortly. The -enableassertions option is necessary for JDK 5.0 programs that use assertions, and since you will be using assertions once you have learned about them it’s a good idea to get into the habit of always using this option. You can abbreviate the -enableassertions option to -ea if you wish. If you want to override an existing CLASSPATH definition, the option is the same as with the compiler. You can also abbreviate -classpath to -cp with the compiler or the Java interpreter. Here’s how the command would look:

java -ea -cp . MyProgram

To execute your program, the Java interpreter analyzes and then executes the bytecode 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 already said, your program will run just as well on a Unix Java implementation as it will on that for Microsoft Windows, Solaris, Linux, OS/2, or any other operating system that supports Java.

Wednesday, December 21, 2011

Compiling a Java Program

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 make the directory that contains your Java source file the current directory, and then enter the following command:

javac MyProgram.java

Here, javac is the name of the Java compiler, and MyProgram.java is the name of the program source file. This command assumes that the current directory contains your source file. If it doesn’t, the compiler won’t be able to find your source file. It also assumes that the source file corresponds to the Java language as defined in the current version of the JDK. There is a command-line option, -source, that you can use to specify the Java language version, so for JDK 5.0, the command above to execute the compiler is equivalent to:

javac -source 5 MyProgram.java

Note that you can also use 1.5 as the value with the source command-line option, in which case you could write the command like this:

javac -source 1.5 MyProgram.java

In practice you can ignore the -source command-line option unless you are compiling a Java program that was written using an older version of the JDK. For example, to compile code written for JDK 1.4 you would write:

javac -source 1.4 oldSourceCode.java

Here’s a simple program you can try out the compiler on:

public class MyProgram {
public static void main(String[] args) {
System.out.println(“Rome wasn’t burned in a day!”);
              &nb}
}

This just outputs a line of text to the command line. As this is just to try out the compiler, I won’t explain how the program works at this point. Of course, you must type the code in exactly as shown and save the source file as MyProgram.java. If you have made any mistakes the compiler will issue error messages. If you need to override an existing definition of the CLASSPATH environment variable - perhaps because it has been set by a Java development system you have installed - the command would be:

javac -classpath . MyProgram.java

The value of CLASSPATH follows the -classpath specification and here it is just a period. This defines just the path to the current directory, whatever that happens to be. This means that the compiler looks for your source file or files in the current directory. If you forget to include the period, the compiler will not be able to find your source files in the current directory. If you include the -classpath . commandline option in any event, it will do no harm. Note that you should avoid storing your source files within the directory structure that was created for the JDK, as this can cause problems. Set up a separate directory of your own to hold the source code for a program and keep the code for each program in its own directory.

Assuming your program contains no errors, the compiler generates a bytecode program that is the equivalent of your source code. The compiler stores the bytecode 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. By default, the .class file will be stored in the same directory as the source file. The command-line options we have introduced here are by no means all the options you have available for the compiler.

You will be able to compile all of the examples in the blog just knowing about the options we have discussed. There is a comprehensive description of all the options within the documentation for the JDK. You can also specify the -help command-line option to get a summary of the standard options you can use. 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. However, the file name extensions for your source file and the object file that results from it will be just the same.

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, you should watch out for a few things 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. The JDK for Windows is available in two versions - as a web install where components are downloaded incrementally, and as a full download of an .exe file that you just execute to start installation. The documentation for the JDK consists of a large number of HTML files structured in a hierarchy that are distributed in a ZIP archive. You will find it easier to install the JDK first, followed by the documentation. If you install the JDK to drive C: under Windows, the jdk1.5.0 directory sometimes referred to as the root directory for Java.

In some contexts it is also referred to as the Java home directory. The actual root directory name may have the release version number appended, in which case the actual directory name will be of the form jdk1.5.0_n where n is a release number, so in the first maintenance release, it will be jdk1.5.0_01, for example.

The sample directory contains sample applications that use JNLP, which is the Java Network Launching Protocol that is used for executing applications or applets from a network server without the need for a browser or the need to download and install the code. You don’t need to worry about the contents of most of these directories, at least not when you get started, but you should add the path for the jdk1.5.0\bin directory to the paths defined in your PATH environment variable. That way you will be able to run the compiler and the interpreter from anywhere without having to specify the path to it. If you installed the JDK to C:, then you need to add the path C:\jdk1.5.0\bin. A word of warning - if you have previously installed a commercial Java development product, check that it has not modified your PATH environment variable to include the path to its own Java 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. One way to fix this is to remove the path or paths that cause the problem. If you don’t 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 jre 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.

The CLASSPATH environment variable is a frequent source of problems and confusion to newcomers to Java. The current JDK does NOT require CLASSPATH to be defined, and if it has been defined by some other Java version or system, it is likely to cause problems. Commercial Java development systems and versions of the Java Development Kit prior to 1.2 may well define the CLASSPATH environment variable, so check to see whether CLASSPATH has been defined on your system. If it has and you no longer have whatever defined it installed, you should delete it. If you have to keep the CLASSPATH environment variable - maybe because you want to keep the system that defined it or you share the machine with someone who needs it - you will have to use a command-line option to define CLASSPATH temporarily whenever you compile or execute your Java code. This corresponds to C:\jdk1.5.0 if you installed the JDK to your C: drive. This will create a new subdirectory, docs, to the root directory, and install the documentation files in that. To look at the documentation, you just open the index.html file that is in the docs sub-directory.

Java Program Development

For java application you need the Java 2 Platform, Standard Edition (J2SE) version 5.0 or later. You can download the JDK from Sun for a variety of hardware platforms and operating systems, either directly from the Sun Java web site at java.sun.com (for Windows, Solaris, and Linux operating systems) or from sites that you can link to from there. The JDK you’ll be using is available from java.sun.com/j2se. Versions of the Java Development Kit for Mac OS X are available from devworld.apple.com/java/.

Note that J2SE 5.0 succeeded J2SE 1.4. Normally, release 1.5 would have followed release 1.4, but it was decided to identify it as release 5.0 in recognition of the significance of the new features that are introduced by release 5.0 and the maturity of the product. Code module names in release 5.0 still use the denotation 1.5.0 so expect to see folder names incorporating 1.5.0 rather than 5.0, and you’ll see 1.5.0 popping up in a few other places too, so don’t let this confuse you.

One aspect of terminology also causes confusion sometimes - the Java Development Kit has been referred to at various times as the JDK - the Java Development Kit - and as the SDK - the Software Development Kit. The current usage with release 5.0 is JDK but with release 1.4 it was SDK, so if you see SDK this generally means the same as JDK. Just for consistency, I’ll use JDK to refer to any Java Development Kit in this blog of java.

To create the Java program source files that you will use with the JDK, you’ll need a plain text editor. Any editor will do as long as it does not introduce formatting codes into the contents of a file. Quite a number of shareware and freeware editors around are suitable, some of which are specific to Java, and you should have no trouble locating one. I find the JCreator editor is particularly good. There’s a free version and a fee version with more functionality, but the free version is perfectly adequate for learning.

A number of excellent professional Java program development environments are available, including products from Sun, Borland, Metrowerks, and Symantec. These all provide very friendly environments for creating and editing your Java source code and compiling and debugging your programs. These are powerful tools for the experienced programmer, but for learning Java using this blog of java, I recommend that you resist the temptation to use any of these, especially if you are relatively new to programming. Instead, stick to using the JDK from Sun together with a suitable simple program text editor for creating your source code. So why am I suggesting that you will be better off not using a tool that makes programming easier and faster? There are several reasons.

Firstly, the professional development systems tend to hide a lot of things you need to get to grips with so that you have a full understanding of how Java works. Secondly, the pro development environments are geared to managing complex applications with a large amount of code, which introduces complexity that you really are better off without while you are learning. Virtually all commercial Java development systems provide prebuilt 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 productivity features supported by a commercial Java development are sometimes tied to a specific version of the Java 2 Platform. This means that some features of the latest version of Java may not work. The professional Java development tools are intended primarily for knowledgeable and experienced programmers, so start with one when you get to the end of the blog. Having said that, if you really do prefer to work with a commercial Java development system for whatever reason, and you have problems with running a particular example from the book, try it out with the JDK from the command line. The chances are good it will work okay.

Learning Java - The Road Ahead

Before starting out on any journey, it is always helpful to have an idea of where you’re heading and what route you should take, so let’s take a look at a brief road map of where you’ll be going with Java. There are five broad stages you’ll progress through in learning Java using this blog:

[1] The first stage is this post. 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.

[2] Next, you’ll 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.

[3] In the third stage, you’ll learn about classes - how you define them and how you can use them. Classes are blueprints for objects, so this is where you’ll learn the object-oriented characteristics of Java. By the time you are through this stage, you will have learned all the basics of how the Java language works, so you’ll be ready to progress further into how you can use it.

[4] In the fourth stage, you’ll 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.

[5] In the fifth stage, you’ll learn in detail how you implement an application or an applet with a 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. When you finish this stage, you will be equipped to write your own fully fledged applications and applets in Java.

Throughout this book I’ll 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’re uncertain how some aspect of Java that you have already covered works, don’t look it up right away - try it out. Making mistakes is a very effective way to learn.

Tuesday, December 20, 2011

Java Programs

There are two basic 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 (to the command line on a PC under Windows, for example), and windowed applications, which can create and manage multiple windows. The latter use the typical GUI mechanisms of window-based programs - menus, toolbars, dialogs, and so on.

While you are learning the Java language basics, you will be using console applications as examples to illustrate how things work. These are applications that use simple command-line input and output. With this approach you can concentrate on understanding the specifics of the language, without worrying about any of the complexity involved in creating and managing windows. Once you are comfortable with using all the features of the Java language, you’ll move on to windowed applications and applet examples.

Because your Java program consists of bytecodes 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 2 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.

Learning Java

Java is not difficult to learn, but there is a great deal to it. Although the Java language is very powerful, it is fairly compact, so acquiring an understanding of it will take less time than you think. However, there’s more to Java than just the language. To be able to program effectively in Java, you also need to understand the libraries that go with the language, and these 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’ll 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 Java applications with a GUI 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, you’ll minimize the chance of drowning, and there is a high expectation that you’ll end up being a competent swimmer.

You can run Java programs on a wide variety of computers using a range of operating systems. Your Java programs will run just as well on a PC running any supported version of Microsoft Windows as it will on Linux or a Sun Solaris workstation. This is possible because a Java program does not execute directly on your computer. It runs on a standardized environment called the Java 2 Platform that has been implemented as software on a wide variety of computers and operating systems. The Java Platform consists of two elements - a software implementation of a hypothetical computer called the Java Virtual Machine (JVM) and the Java Application Programming Interface (Java API), which is a set of software components that provides the facilities you need to write a fully fledged interactive application in Java.

A Java compiler converts the Java source code that you write into a binary program consisting of bytecodes. Bytecodes are machine instructions for the Java Virtual Machine. When you execute a Java program, a program called the Java interpreter inspects and deciphers the bytecodes 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 the bytecodes specify within the Java Virtual Machine. A Java interpreter can run standalone, or it can be part of a web browser such as Netscape Navigator, Mozilla, or Microsoft Internet Explorer where it can be invoked automatically to run applets in a web page.

Features of The Java Language

The most important characteristic of Java is that it was designed from the outset to be machine independent. You can run Java programs unchanged on any machine and operating system combination 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 application written in Java will only require a single set of source code statements, 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 an extensive graphical user interface is involved. Java offers substantial savings in time and resources in developing, supporting, and maintaining major applications on several different hardware platforms and operating systems.

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 post. Object-oriented programs are easier to understand and less time consuming to maintain and extend than programs that have been written without the benefit of using objects.

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 easy to learn and very straightforward to use. By and large, it lacks the traps and “gotchas” that arise in some other programming languages. This makes the learning cycle shorter, and you need less real-world coding experience to gain competence and confidence. It also makes Java code easier to test.

Java has a built-in ability to support national character sets. You can write Java programs as easily for use in Greece or Japan as you can for English-speaking countries, always assuming you are familiar with the national languages involved, of course. You can even build programs from the outset to support several different national languages with automatic adaptation to the environment in which the code executes.

What Is Java All About?

Java is an innovative programming language that has become 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 web pages to provide some intelligence. Being able to embed executable code in a web page 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 you want. You can include animations, games, interactive transaction processing - the possibilities are almost unlimited.

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 won’t do anything that might interfere with the operation of your computer, or damage the data you have on your system. This implies that 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.

Java’s support for the Internet and network-based applications generally doesn’t end with applets. For example, Java Server Pages (JSP) provides a powerful means of building a server application that can dynamically create and download HTML pages to a client that are precisely customized for the specific request that is received. Of course, the pages that are generated by JSP can themselves contain Java applets.

Java also allows you to write large-scale application programs that you can run unchanged on any computer with an operating system environment in which Java is supported. This applies to the majority of computers in use today. You can even write programs that will work both as ordinary applications and as applets.

Java has matured immensely in recent years, particularly since the introduction of Java 2. The breadth of function provided by the standard core Java has grown incredibly. Java provides you with comprehensive facilities for building applications with an interactive graphical user interface (GUI), extensive image processing and graphics programming facilities, as well as support for accessing relational databases and communicating with remote computers over a network. Just about any kind of application can now be programmed effectively in Java, with the implicit plus of complete portability.

Of course, Java is still developing and growing. Amongst a myriad of other enhancements, release 1.4 of Java added a major additional capability, the ability to read and write XML. Java 5.0, which followed release 1.4, adds further new facilities, including important new language features as well as significant additions to the class libraries. You’ll be learning about all of these in this book.

Introducing Java

This blog will give you an appreciation of what the Java language is all about. Understanding the details of what I’ll discuss in this post is not important at this stage; you will see all of the topics again in greater depth in later posts of the blog. The intent of this post is to introduce you to the general ideas that underpin what I’ll be covering through the rest of the book, as well as the major contexts in which Java programs can be used and the kind of program that is applicable in each context.

book of java


In this blog you will learn:

[1] The basic characteristics of the Java language
[2] How Java programs work on your computer
[3] Why Java programs are portable between different computers
[4] The basic ideas behind object-oriented programming
[5] How a simple Java program looks and how you can run it using the Java Development Kit
[6] What HTML is and how it is used to include a Java program in a web page