text: In this chapter.
  What's most special about Java in relation to other programming languages is that it lets you write special programs called applets that can be downloaded from the Internet and run cannot crash your system.
  There's another problem with distributing executable programs from web pages. Computer programs are very closely tied to the specific hardware and operating system they run on. Navigator have to be written almost independently for all the different platforms they run on. Netscape Navigator Java byte code. Java byte code, and are therefore platform independent themselves.
  All these pieces, the javac compiler, the java interpreter, the Java programming language, and more are collectively referred to as Java. However this book restricts its usage of Java to mean only the Java programming language. It will be more specific and spell out the java interpreter or the Java environment when discussing those things.
  Web page authors are excited about Java because of all the cool things it lets them do. Here are just a few things you can do on a web page with Java that you couldn't do before:
  Java changes the Web from a static, fixed medium to a real-time interactive, dynamic, expandable multimedia environment.
  Until Java, web pages were static. They had text and they had pictures but they had very little else, and they didn't change much. For the most part text and pictures just sat there. If you wanted to see something new, you clicked on a link and loaded an entirely new page. Then that page sat there, doing nothing.
  Java makes web pages dynamic. By using Java you can make a page change while the user watches it. You can animate pictures. You can change the text that's displayed without reloading the entire page. For instance there have been stock price pages before Java, but it wasn't until Java that you could have a stock ticker page, i.e. a page that updated the price as the stock price changed. Figure 1-1 shows one such stock ticker applet.
  Figure 1-1:
  Before Java users were limited to seeing the kinds of content their web browsers supported; and web developers were limited to the most basic content supported by their readers' web browsers, generally HTML 2.0 and GIF's. Java lets developers expand the range of content types indefinitely.
  For instance, HotJava was the first web browser to include inline sound in a web page. Inline means that the sound plays inside the browser automatically. The reader doesn't need to launch a separate helper application to view it. The sound can play when the reader first visits a page, it can play when the reader clicks a button on a page, or it can play continuously in the background.
  However Java is more than just a web browser with special features. Although HotJava was the first browser to include inline sound and animation, other browsers have long since added this feature.
  What makes Java special is that it doesn't just allow you to add new types of content to pages like Netscape and Internet Explorer do. Rather it lets you add both the content and the code necessary to display that content. You no longer need to wait for a browser to be released that supports your preferred image format or special game protocol. With Java you send browsers both the content and the program necessary to view this content at the same time! suppose on a UNIX box that can speak HTTP and talk to the card catalog, not an easy task. With Java when a client wants to talk to your card catalog, you send them the code they need to do so. You don't have to try to force everything through an httpd server on port 80.
  Before Java, people browsed the Web. They moved from site to site passively reading the text and viewing the pictures there, but they rarely interacted with the page or changed it in any meaningful way. Occasionally someone might fill out a form which would be submitted back to the server, but even that was slow and limited to typing text and making menu choices. This was hot stuff in 1975, but isn't so exciting in an era where users are accustomed to the interactivity of Quake.
  After Java, users can use the keyboard for more than typing text and the mouse for more than choosing from menus. Instead of just reading a page and perhaps filling out a form, users can now play games, calculate spreadsheets, draw pictures, and in general do anything they might do within a window displayed by a traditional computer program. Most importantly users get immediate feedback. When you press enter in a spreadsheet cell, you don't want to wait for the entire spreadsheet to be sent back to the server and then the entire revised spreadsheet to be sent back to you. You want the update to happen instantaneously. With Java the calculations are performed on the client system and the results updated locally rather than remotely as would have to be done using a CGI program.
  If that were all Java was, it would still be more interesting than a
  <marquee> or
  <frame> tag in some new browser beta,
  but there's a lot more. Java isn't just for web sites.
  Java is a programming language that can do almost anything a traditional programming language like Fortran, Basic or C++ can do. However Java has learned from the mistakes of its predecessors. It is considerably easier to program and to learn than those languages without giving up any of their power.
  The Java language shares many superficial similarities with C, C++, and Objective C. For instance, loops have identical syntax in all four languages, However, Java is not based on any of these languages, nor have efforts been made to make it compatible with them.
  Java is sometimes referred to as C++++--. James Gosling invented Java because C++ proved inadequate for certain tasks. Since Java's designers were not burdened with compatibility with existing languages, they were able to learn from the experience and mistakes of previous object-oriented languages. They added a few things C++ doesn't have like garbage collection and multithreading (the ++) and they threw away C++ features that had proven to be better in theory than in practice like multiple inheritance and operator overloading (the --). A few advanced features like closures and parameterized types that the Java team liked were nonetheless left out of the language due to time constraints. There's still argument over whether the right choices were made. Parameterized types (templates to C++ programmers) may be added in a later revision of Java.
  Java has learned a lot from previous languages. Let's look at some of the advantages Java offers programmers.. The language specification for Java is only about eighty pages long compared to a couple of hundred pages for C and even more for C++. Despite its simplicity Java has considerably more functionality than C.
  Because Java is simple, it is easy to read and write. Obfuscated Java isn't nearly as common as obfuscated C. There aren't a lot of special cases or tricks that will confuse beginners. in it. The language is interpreted so the compile-link-run cycle is much shorter. (In fact, the link phase is eliminated entirely.) was the catch phrase of computer programming in the 1990's. Although object oriented programming has been around in one form or another since the Simula language was invented in the 1960's, it really took runs messages are passed back and forth between objects. When an object receives a message, it responds accordingly as defined by its methods.
  Object oriented programming is alleged to have a number of advantages including: you need to do is run it with an interpreter written for the new platform. You don't even need to recompile. Even the compiler is written in Java. The byte codes are precisely defined, and remain the same on all platforms.
  The second important part of Java's cross-platform savvy is the elimination of undefined.
  This required the elimination of many features of C and C++. Most notably
  there are no pointers in Java. Java programs cannot access arbitrary addresses
  in memory. All memory access is handled behind the scenes by the (presumably)
  trusted runtime environment. Furthermore Java has strong typing. Variables must
  be declared, and a Java program can do to a host system is bring down the runtime environment. It cannot bring down the entire system.
  Most importantly Java applets can be executed in an environment that prohibits them from introducing viruses, deleting or modifying files, or otherwise destroying data and crashing the host computer. A Java enabled web browser checks the byte codes of an applet to verify that it doesn't do anything nasty before it will run the applet.
  However the biggest security problem is not hackers. It's not viruses. It's not Visual Basic worms transmitted by Outlook Express. byte codes can be compiled on the fly to code that rivals C++ in speed using a "just-in-time compiler." Several companies are also working on native-machine-architecture compilers for Java. These will produce executable code that does not require a separate interpreter, and that is indistinguishable in speed from C++. While you'll never get that last ounce of speed out of a Java program that you might be able to wring from C or Fortran, the results will be suitable for all but the most demanding applications.
  As of May, 1999, the fastest VM, IBM's Java 1.1 VM for Windows, is very close to C++ on CPU-intensive operations that don't involve a lot of disk I/O or GUI work; C++ is itself only a few percent slower than C or Fortran on CPU intensive operations.
  It is certainly possible to write large programs in Java. The HotJava web browser, the JBuilder integrated development environment and the javac compiler are large programs that are written entirely in Java.
  Java is inherently multi-threaded. A single Java program can have many different processes executing independently and continuously. Three Java applets on the same page can run simultaneously with each getting equal time from the CPU with very little extra effort on the part of the programmer. This makes Java incredibly responsive to user input. It also helps to contribute to Java's robustness and provides a mechanism whereby the Java environment can ensure that a malicious applet doesn't steal all of the host's CPU cycles.
  Unfortunately multithreading is so tightly integrated with Java, that it makes Java rather difficult to port to architectures like Windows 3.1 or the PowerMac that don't natively support preemptive multi-threading.
  There is another cost associated with multi-threading. Multi-threading is to Java what pointer arithmetic is to C; that is, a source of devilishly hard to find bugs. Nonetheless, in simple programs it's possible to leave multi-threading alone and normally be OK.
  Java, non-public classes and inner classes).
  The compiler searches the current directory and a few other well specified places to find other classes explicitly referenced by name in each source code file. If the file you're compiling depends on other, non-compiled files, then the compiler will try to find them and compile them as well. The Java compiler is quite smart, and can handle circular dependencies as well as methods that are used before they're declared. It also can determine whether a source code file has changed since the last time it was compiled.
  More importantly, classes that were unknown to a program when it was compiled can still be loaded into it at runtime. For example, a web browser can load applets of differing classes that it's never seen before without recompilation.
  Furthermore, Java .class files tend to be quite small, a few kilobytes at most. It is not necessary to link in large runtime libraries to produce an executable. Instead the necessary classes are loaded from the user's local system.
  You do not need to explicitly allocate or deallocate memory
  in Java. Memory is allocated as needed, both on the stack and
  the heap, and reclaimed by the garbage collector when it is no
  longer needed. There are no
  malloc(),
  free(), or destructor methods. There are
  constructors and these do allocate memory on the heap, but this
  is transparent to the programmer.
  Most Java virtual machines use an inefficient, mark and sweep garbage collector. Some more recent virtual machines have improved matters quite a bit by using generational garbage collection.
  To sum up, Java is a safe, robust, garbage-collected, object-oriented, high-performance, multi-threaded, interpreted, architecture-neutral, cross-platform, buzzword-compliant programming language.
  In the late 1970's Bill Joy thought about doing a language that would merge the best features of MESA, an experimental language from Xerox, and C. However other projects (like cofounding Sun) intervened. In the late 1980's he got Sun's engineers started on a complete revision of the UNIX operating system that involved merging SunOS 4.x with AT&T's SYSVR4. pitched Sun engineers on the idea that they should produce an object environment based on C++. Today, however, Joy freely admits that C++ was too complicated and not up to the job.
  Patrick Naughton, then of Sun, later.
  Around this time Sun Distinguished Scientist James Gosling (of emacs fame) had been working for several months on an SGML editor called "Imagination" using C++. The Oak language (now Java) grew out of Gosling's frustration with C++ on his Imagination project. Gosling claims that he named Oak when he looked out his window and saw a tree. However early Sun papers refer to Oak as the "Object Architecture Kernel." It is unknown whether the name or the acronym came first. In either case the Oak name did not survive a trademark search and was changed to Java in 1995.. (The Green project never wrote a single line. In October of 1992 this was demoed to Scott McNealy, Sun's president, settop. Patrick Naughton wrote a prototype browser called WebRunner in one weekend of inspired hacking. After additional work by Naughton and Jonathan Payne this eventually became HotJava. The rest, as they say, is history.
  This chapter has given you a basic overview of why Java is so exciting. The things you learned in this chapter included:
  In the next chapter you'll download and install the software you need to run Java programs. In later chapters you'll learn all the practical details of Java's advanced language features like objects and multi-threading that were discussed theoretically in this chapter. You'll learn how to write your own applets like WallStreetWeb. Get ready. Your journey into Java is about to begin.
  Q: What can't I do with Java?
  A: If you believed everything you read in this chapter unconditionally, please contact the author about a certain bridge he has for sale near his home in Brooklyn, cheap. On the other hand if you're understandably a bit skeptical about whether Java really is the greatest tool since Mosaic, let me point out a few weaknesses:
  Q: Leaving implementation issues aside, Is Java the perfect language?
  A: Once again there are a few weaknesses to be pointed out:
  intaren't objects. This makes data structures such as linked lists that need to hold both objects and primitive data relatively hard to implement and quite cumbersome overall. It also leads to problems with numeric overflow.
  ArithmeticExceptions rather than returning
  Infor
  NaN. Furthermore, the specific implementation of the IEEE 754 floating point model Sun chose is much better suited to Sun's Sparc processors than to X86 or PowerPC CPUs.
  switch-
  casestatement is insufficiently expressive to handle even a majority of the "Choose one of several options" blocks you're likely to encounter.
  \nand
  \tto insert them.
  switch-
  caseexecutes all cases that follow the matched
  caseunless there's an explicit
  breakstatement.
  Q: Can Java be used by non-programmers?
  A: Java isn't just for programmers. Just like you can write text with Microsoft Word without knowing how to write in C++, you can add animations, sounds and other cool Java stuff to your web pages without writing a line of code, just by using other people's applets. However this book is written for people who want to program in Java, and from here on in it will concentrate on developing the skills you need to write your own unique programs.
  Q: What's JavaScript? Where does it fit in?
  A: Java and JavaScript are about as closely related as the Taj Mahal in India is to the Trump Taj Mahal in Atlantic City..
  Q: What's HotJava? Where does it fit in?
  A: HotJava is a particular web browser from Sun Microsystems that can play Java applets. It is not the only one. Netscape Navigator and Microsoft Internet Explorer can also run Java applets.
  Q: Couldn't a browser plug-in be used to to do all the cool stuff an applet can do?
  A: In theory plug-ins can do a lot. However they cannot be downloaded and installed into a user's system on the fly when they visit a web page. Imagine if every web site you visited required a new plug in. Furthermore plug-ins are platform specific. you need to write a plug-in for every platform that may be used by someone visiting your pages. Plug-ins are generally faster than Java applets though and don't have as many security restrictions. Therefore plug-ins are good if you're writing something that will be used by many web unrelated web sites and you have the resources to support a dozen or more platforms equally. However if what you're creating is unique to your site or you don't want to port your software to a dozen platforms, then you should write it as a Java applet.
  Q: Couldn't Flash to do all the cool stuff an applet can do?
  A: Yes, Macromedia Flash can probably do just about everything an applet can do, and it may do it better too. However, Flash is just for applets. Java has a lot more to offer than applets on web pages.
  Sun's web site has several white papers about the philosophy of Java. The most comprehensive one often referred to simply as "The White Paper", is:
  Gosling, James and Henry McGilton, The Java Language Environment, A White Paper, May 1996,.
  Though doubtless one day tomes will be written about the genesis of Java and the Green project will be mentioned in the same hushed tones now reserved for the Home Brew Computer Club, not much has yet been written about the history of Java. Most of the details are being passed around by word of mouth. However there have been a couple of decent articles about the genesis of Java. See
  Bank, David, "The Java Saga," Wired, December 1995, pp. 166-169,
  O'Connell, Michael, "Java: The inside story," SunWorld Online, July 1995,
  So far only one of the original members of the Green Project has written about it publicly. For a rather surprising look at how the Green Project operated and how Java almost didn't happen see
  Naughton, Patrick, "The Long Strange Trip to Java," The Java Handbook, pp 391-409, Berkeley: Osborne McGraw-Hill, 1996
  This is the first book-length treatment about the origins of Java. Doubtless there'll be others as time passes. It focuses on the personalities and squabbles as oppose to the technology.
  Marlowe, Jos and Richard J. Stiller, Asunder: An Unauthorized History of the Origins of Java Programming Language, Briarwood Publications, 1996
  Not everyone agrees that C++ is as horrible as is argued here. For an interesting alternative viewpoint you should read The Design and Evolution of C++ by Bjarne Stroustrup, the inventor of C++. It's a fascinating look at why C++ is what it is, for good or bad.
  Stroustrup, Bjarne, The Design and Evolution of C++, New York: Addison-Wesley, 1995