The material in this eBook also appears in the print version of this title: 0-07-222588-2
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps.
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-hill.com or (212) 904-4069.
TERMSOFUSE
This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms. THE WORK IS PROVIDED “AS IS”. McGRAW-HILLAND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACYOR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANYINFORMATION THATCAN BE ACCESSED THROUGH THE WORK VIAHYPERLINK OR OTHERWISE, AND EXPRESSLYDISCLAIM ANYWARRANTY, EXPRESS OR IMPLIED, INCLUDING BUTNOTLIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITYOR FITNESS FOR APARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.
For more information about this title, click here.
Contents at a Glance
1 Java Fundamentals.
2 Introducing Data Types and Operators.
3 ProgramControlStatements.
4 Introducing Classes, Objects, and Methods.
5 More Data Types and Operators.
6 A Closer Look at Methods and Classes.
7 Inheritance.
8 Packages and Interfaces.
9 Exception Handling.
10 Using I/O.
11 Multithreaded Programming.
12 Applets, Events, and Miscellaneous Topics.
A Answers to Mastery Checks.
B Using Java’s Documentation Comments.
Index.
1 Java Fundamentals.
The Origins of Java.
How Java Relates to C and C++.
How Java Relates to C#.
Java’s Contribution to the Internet.
Java Applets and Applications.
Security.
Portability.
Java’s Magic: The Bytecode.
The Java Buzzwords.
Object-Oriented Programming.
Encapsulation.
Inheritance.
Obtaining the Java Software Developer’s Kit.
Entering the Program.
Compiling the Program.
A Second Simple Program.
Another Data Type.
Project 1-1 Converting Gallons to Liters.
Two Control Statements.
The if Statement.
The for Loop.
Create Blocks of Code.
Semicolons and Positioning.
Indentation Practices.
Project 1-2 Improving the Gallons-to-Liters Converter.
The Java Keywords.
Identifiers in Java.
The Java Class Libraries.
Module 1 Mastery Check.
2 Introducing Data Types and Operators.
Why Data Types Are Important.
Java’s Simple Types.
Integers.
Floating-Point Types.
Characters.
The Boolean Type.
Project 2-1 How Far Away Is the Lightning?.
Literals.
Hexadecimal and Octal Constants.
Character Escape Sequences.
String Literals.
A Closer Look at Variables.
Initializing a Variable.
Dynamic Initialization.
The Scope and Lifetime of Variables.
Operators.
Arithmetic Operators.
Increment and Decrement.
Relational and Logical Operators.
Short-Circuit Logical Operators.
The Assignment Operator.
Shorthand Assignments.
Type Conversion in Assignments.
Casting Incompatible Types.
Operator Precedence.
Project 2-2 Display a Truth Table for the Logical Operators.
Expressions.
Type Conversion in Expressions.
Spacing and Parentheses.
Module 2 Mastery Check.
3 ProgramControlStatements.
Input Characters from the Keyboard.
The if Statement.
Nested ifs.
The if-else-if Ladder.
The switch Statement.
Nested switch Statements.
Project 3-1 Start Building a Java Help System.
The for Loop.
Some Variations on the for Loop.
Missing Pieces.
Loops with No Body.
Declaring Loop Control Variables Inside the for Loop.
The while Loop.
The do-while Loop.
Project 3-2 Improve the Java Help System.
Use break to Exit a Loop.
Use break as a Form of goto.
Use continue.
Project 3-3 Finish the Java Help System.
Nested Loops.
Module 3 Mastery Check.
4 Introducing Classes, Objects, and Methods.
Class Fundamentals.
The General Form of a Class.
Defining a Class.
How Objects Are Created.
Reference Variables and Assignment.
Methods.
Adding a Method to the Vehicle Class.
Returning from a Method.
Returning a Value.
Using Parameters.
Adding a Parameterized Method to Vehicle.
Project 4-1 Creating a Help Class.
Constructors.
Parameterized Constructors.
Adding a Constructor to the Vehicle Class.
The new Operator Revisited.
Garbage Collection and Finalizers.
The finalize( ) Method.
Project 4-2 Demonstrate Finalization.
The this Keyword.
Module 4 Mastery Check.
5 More Data Types and Operators.
Arrays.
One-Dimensional Arrays.
Project 5-1 Sorting an Array.
Multidimensional Arrays.
Two-Dimensional Arrays.
Irregular Arrays.
Arrays of Three or More Dimensions.
Initializing Multidimensional Arrays.
Alternative Array Declaration Syntax.
Assigning Array References.
Using the length Member.
Project 5-2 A Queue Class.
Strings.
Constructing Strings.
Operating on Strings.
Arrays of Strings.
Strings Are Immutable.
Using Command-Line Arguments.
The Bitwise Operators.
The Bitwise AND, OR, XOR, and NOT Operators.
The Shift Operators.
Bitwise Shorthand Assignments.
Project 5-3 A ShowBits Class.
The ? Operator.
Module 5 Mastery Check.
6 A Closer Look at Methods and Classes.
Controlling Access to Class Members.
Java’s Access Specifiers.
Project 6-1 Improving the Queue Class.
Pass Objects to Methods.
How Arguments Are Passed.
Returning Objects.
Method Overloading.
Overloading Constructors.
Project 6-2 Overloading the Queue Constructor.
Recursion.
Understanding static.
Static Blocks.
Project 6-3 The Quicksort.
Introducing Nested and Inner Classes.
Module 6 Mastery Check.
7 Inheritance.
Inheritance Basics.
Member Access and Inheritance.
Constructors and Inheritance.
Using super to Call Superclass Constructors.
Using super to Access Superclass Members.
Project 7-1 Extending the Vehicle Class.
Creating a Multilevel Hierarchy.
When Are Constructors Called?.
Superclass References and Subclass Objects.
Method Overriding.
Overridden Methods Support Polymorphism.
Why Overridden Methods?.
Applying Method Overriding to TwoDShape.
Using Abstract Classes.
Using final.
final Prevents Overriding.
final Prevents Inheritance.
Using final with Data Members.
The Object Class.
Module 7 Mastery Check.
8 Packages and Interfaces.
Packages.
Defining a Package.
Finding Packages and CLASSPATH.
A Short Package Example.
Packages and Member Access.
A Package Access Example.
Understanding Protected Members.
Importing Packages.
Java’s Class Library Is Contained in Packages.
Interfaces.
Implementing Interfaces.
Using Interface References.
Project 8-1 Creating a Queue Interface.
Variables in Interfaces.
Interfaces Can Be Extended.
Module 8 Mastery Check.
9 Exception Handling.
The Exception Hierarchy.
Exception Handling Fundamentals.
Using try and catch.
A Simple Exception Example.
The Consequences of an Uncaught Exception.
Exceptions Enable You to Handle Errors Gracefully.
Using Multiple catch Statements.
Catching Subclass Exceptions.
Try Blocks Can Be Nested.
Throwing an Exception.
Rethrowing an Exception.
A Closer Look at Throwable.
Using finally.
Using throws.
Java’s Built-in Exceptions.
Creating Exception Subclasses.
Project 9-1 Adding Exceptions to the Queue Class.
Module 9 Mastery Check.
10 Using I/O.
Java’s I/O Is Built upon Streams.
Byte Streams and Character Streams.
The Byte Stream Classes.
The Character Stream Classes.
The Predefined Streams.
Using the Byte Streams.
Reading Console Input.
Writing Console Output.
Reading and Writing Files Using Byte Streams.
Inputting from a File.
Writing to a File.
Reading and Writing Binary Data.
Project 10-1 A File Comparison Utility.
Random Access Files.
Using Java’s Character-Based Streams.
Console Input Using Character Streams.
Console Output Using Character Streams.
File I/O Using Character Streams.
Using a FileWriter.
Using a FileReader.
Using Java’s Type Wrappers to Convert Numeric Strings.
Project 10-2 Creating a Disk-Based Help System.
Module 10 Mastery Check.
11 Multithreaded Programming.
Multithreading Fundamentals.
The Thread Class and Runnable Interface.
Creating a Thread.
Some Simple Improvements.
Project 11-1 Extending Thread.
Creating Multiple Threads.
Determining When a Thread Ends.
Thread Priorities.
Synchronization.
Using Synchronized Methods.
The synchronized Statement.
Thread Communication Using notify( ), wait( ), and notifyAll( ).
An Example That Uses wait( ) and notify( ).
Suspending, Resuming, and Stopping Threads.
Project 11-2 Using the Main Thread.
Module 11 Mastery Check.
12 Applets, Events, and Miscellaneous Topics.
Applet Basics.
Applet Organization and Essential Elements.
The Applet Architecture.
A Complete Applet Skeleton.
Applet Initialization and Termination.
Requesting Repainting.
The update( ) Method.
Project 12-1 A Simple Banner Applet.
Using the Status Window.
Passing Parameters to Applets.
The Applet Class.
Event Handling.
The Delegation Event Model.
Events.
Event Sources.
Event Listeners.
Event Classes.
Event Listener Interfaces.
Using the Delegation Event Model.
Handling Mouse Events.
A Simple Mouse Event Applet.
More Java Keywords.
The transient and volatile Modifiers.
instanceof.
strictfp.
assert.
Native Methods.
What Next?.
Module 12 Mastery Check.
A Answers to Mastery Checks.
Module 1: Java Fundamentals.
Module 2: Introducing Data Types and Operators.
Module 3: Program Control Statements.
Module 4: Introducing Classes, Objects, and Methods.
Module 5: More Data Types and Operators.
Module 6: A Closer Look at Methods and Classes.
Module 7: Inheritance.
Module 8: Packages and Interfaces.
Module 9: Exception Handling.
Module 10: Using I/O.
Module 11: Multithreaded Programming.
Module 12: Applets, Events, and Miscellaneous Topics.
B Using Java’s Documentation Comments.
The javadoc Tags.
@author.
@deprecated.
{@docRoot}.
@exception.
{@inheritDoc}.
{@link}.
{@linkplain}.
@param.
@return.
@see.
@serial.
@serialData.
@serialField.
@since.
@throws.
{@value}.
@version.
The General Form of a Documentation Comment.
What javadoc Outputs.
An Example that Uses Documentation Comments.
Index.
This page intentionally left blank.
Preface
Inthespaceofafewshortyears,Javawentfromrelativeobscuritytobeingthemostimportant languageoftheInternet.TheimpactofJavacannotbeunderstated.IttransformedtheWebinto a highly interactive environment, setting a new standard in computer language design in the process. The innovative aspects of Java have already changed the course of programming well intotheforeseeablefuture.Therefore,ifInternet-basedprogrammingisinyourfuture,youhave chosentherightlanguagetolearn—andthisbookwillhelpyoulearnit.
It is important to state at the outset that this book is just a starting point. Java is more than just the elements that define the language. Java also includes extensive libraries and tools that aid in the development of programs. Furthermore, Java provides a sophisticated set of libraries that handle the browser user interface. To be a top-notch Java programmer implies mastery of these areas, too. After completing this book you will have the knowledge to pursue any and all other aspects of Java.
Copyright 2003 by The McGraw-Hill Companies, Inc. Click here for Terms of Use.
HowThisBookIsOrganized
This book presents an evenly paced tutorial in which each section builds upon the previous one. It contains 12 modules, each discussing an aspect of Java. This book is unique because it includes several special elements that reinforce what you are learning.
CriticalSkills
Each module begins with a set of critical skills that you will be learning. The location of each skill is indicated within the module.
MasteryCheck
Each module concludes with a Mastery Check, a list of questions that lets you test your knowledge. The answers are in Appendix A.
ProgressChecks
At the end of each major section is a “Progress Check” that tests your understanding of the key points that were presented. The answers to these questions are at the bottom of the page.
AsktheExpert
Sprinkled throughout the book are “Ask the Expert” boxes. These contain additional information or interesting commentary about a topic. They use a question-and-answer format.
Projects
Each module contains one or more projects that show you how to apply what you are learning. These are real-world examples that you can use as starting points for your own programs.
To compile and run the programs in this book you will need the latest Java Software Developers Kit (SDK) from Sun, which at the time of this writing is Java 2, version 1.4. Instructions for obtaining the Java SDK are given in Module 1.
Don’tForget:CodeontheWeb
Remember, the source code for all of the examples and projects in this book is available free of charge on the Web at www.osborne.com.
xxii Java 2: A Beginner’s Guide
ForFurtherStudy
Java 2: A Beginner’s Guide is your gateway to the Herb Schildt series of programming books. Here are some others that you will find of interest.
To learn more about Java programming, we recommend the following:
● Java 2: The Complete Reference
● Java 2 Programmer’s Reference
To learn about C++, you will find these books especially helpful.
● C++: The Complete Reference
● Teach Yourself C++
● C++ from the Ground Up
● STL Programming from the Ground Up
● C/C++ Annotated Archives
To learn about C#, we suggest the following Schildt books:
● C#: A Beginner’s Guide
● C#: The Complete Reference
If you want to learn more about the C language, then the following titles will be of interest.
● C: The Complete Reference
● Teach Yourself C
When you need solid answers, fast, turn to Herbert Schildt, the recognized authority on programming.
Module 1 Java Fundamentals
CRITICALSKILLS
1.1 Know the history and philosophy of Java
1.2 Understand Java’s contribution to the Internet Understand the importance of bytecode Know the Java buzzwords
1.5 Understand the foundational principles of object-oriented programming
1.6 Create, compile, and run a simple Java program
1.7 Use variables
1.8 Use the if and for control statements
1.9 Create blocks of code
1.10 Understand how statements are positioned, indented, and terminated
1.11 Know the Java keywords
1.12 Understand the rules for Java identifiers
1.1
The rise of the Internet and the World Wide Web have fundamentally reshaped computing. Only a few short years ago, the cyber landscape was dominated by stand-alone PCs. Today, nearly all PCs are connected to the Internet. The Internet, itself, was transformed—originally offeringaconvenientwaytosharefilesandinformation,todayitisavast,distributedcomputing universe. These changes have been as rapid as they have been profound, and in their wake, they gave rise to a new way to program: Java.
Java is the preeminent language of the Internet, but it is more than that. Java has revolutionized programming, changing the way that we think about both the form and the function of a program. To be a professional programmer today implies the ability to program in Java—it has become that important. In the course of this book, you will learn the skills needed to master it.
The purpose of this module is to introduce you to Java, including its history, its design philosophy,andseveralofitsmostimportantfeatures.Byfar,thehardestthingaboutlearninga programminglanguageisthefactthatnoelementexistsinisolation.Instead,thecomponentsof thelanguageworkinconjunctionwitheachother.Thisinterrelatednessisespeciallypronounced in Java. In fact, it is difficult to discuss one aspect of Java without involving others. To help overcome this problem, this module provides a brief overview of several Java features, including the general form of a Java program, some basic control structures, and operators. It does not go into too many details but, rather, concentrates on the general concepts common to any Java program.
TheOriginsofJava
Computer language innovation is driven forward by two factors: improvements in the art of programming and changes in the computing environment. Java is no exception. Building upon the rich legacy inherited from C and C++, Java adds refinements and features that reflect the current state of the art in programming. Responding to the rise of the online environment, Java offers features that streamline programming for a highly distributed architecture.
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems in 1991. This language was initially called “Oak” but was renamed “Java” in 1995. Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation was the need for a platform-independent language that could be used to create software to be embedded in various consumer electronic devices, such as toasters, microwave ovens, and remote controls. As you can probably guess, many different types of CPUs are used as controllers. The trouble was that most computer languages are designed to be compiled for a specific target. For example, consider C++.
Although it is possible to compile a C++ program for just about any type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem, however, is that compilers are expensive and time-consuming to create. In an attempt to find a better solution, Gosling
and others worked on a portable, cross-platform language that could produce code that would runonavarietyofCPUsunderdifferingenvironments.Thiseffortultimatelyledtothecreation of Java.
About the time that the details of Java were being worked out, a second, and ultimately more important, factor emerged that would play a crucial role in the future of Java. This second force was, of course, the World Wide Web. Had the Web not taken shape at about the same time that Java was being implemented, Java might have remained a useful but obscure language for programming consumer electronics. However, with the emergence of the Web, Java was propelled to the forefront of computer language design, because the Web, too, demanded portable programs.
Most programmers learn early in their careers that portable programs are as elusive as they are desirable. While the quest for a way to create efficient, portable (platform-independent) programs is nearly as old as the discipline of programming itself, it had taken a back seat to other, more pressing problems. However, with the advent of the Internet and the Web, the old problem of portability returned with a vengeance. After all, the Internet consists of a diverse, distributed universe populated with many types of computers, operating systems, and CPUs. What was once an irritating but a low-priority problem had become a high-profile necessity. By 1993 it became obvious to members of the Java design team that the problems of portability frequently encountered when creating code for embedded controllers are also found when attempting to create code for the Internet. This realization caused the focus of Java to switch from consumer electronics to Internet programming. So, while it was the desire for an architecture-neutral programming language that provided the initial spark, it was the Internet that ultimately led to Java’s large-scale success.
HowJavaRelatestoCandC++
Java is directly related to both C and C++. Java inherits its syntax from C. Its object model is adapted from C++. Java’s relationship with C and C++ is important for several reasons. First, many programmers are familiar with the C/C++ syntax. This makes it easy for a C/C++ programmer to learn Java and, conversely, for a Java programmer to learn C/C++.
Second, Java’s designers did not “reinvent the wheel.” Instead, they further refined an already highly successful programming paradigm. The modern age of programming began with C. It moved to C++, and now to Java. By inheriting and building upon that rich heritage, Java provides a powerful, logically consistent programming environment that takes the best of the past and adds new features required by the online environment. Perhaps most important, because of their similarities, C, C++, and Java define a common, conceptual framework for the professional programmer. Programmers do not face major rifts when switching from one language to another.
One of the central design philosophies of both C and C++ is that the programmer is in charge! Java also inherits this philosophy. Except for those constraints imposed by the Internet environment,Javagivesyou,theprogrammer,fullcontrol.Ifyouprogramwell,yourprograms
reflect it. If you program poorly, your programs reflect that, too. Put differently, Java is not a language with training wheels. It is a language for professional programmers.
JavahasoneotherattributeincommonwithCandC++:itwasdesigned,tested,andrefined by real, working programmers. It is a language grounded in the needs and experiences of the peoplewhodevisedit.Thereisnobetterwaytoproduceatop-flightprofessionalprogramming language.
BecauseofthesimilaritiesbetweenJavaandC++,especiallytheirsupportforobjectorientedprogramming, it is tempting to think of Java as simply the “Internet versionofC++.” However,todosowouldbeamistake.Javahassignificantpracticalandphilosophicaldifferences. Although Java was influenced by C++, it is not an enhanced version of C++. For example, it is neither upwardly nor downwardly compatible with C++. Of course, the similarities with C++ are significant, and if you are a C++ programmer, you will feel right at home with Java.
Another point: Java was not designed to replace C++. Java was designed to solve a certain set of problems. C++ was designed to solve a different set of problems. Both will coexist for many years to come.
HowJavaRelatestoC#
Recently a new language called C# has come on the scene. Created by Microsoft to support its .NET Framework, C# is closely reated to Java. In fact, many of C#’s features were directly adapted from Java. Both Java and C# share the same general C++-style syntax, support distributed programming, and utilize the same object model. There are, of course, differences between Java and C#, but the overall “look and feel” of these languages is very similar. This means that if you already know C#, then learning Java will be especially easy. Conversely, if C# is in your future, then your knowledge of Java will come in handy.
Given the similarity between Java and C#, one might naturally ask, “Will C# replace Java?” The answer is No. Java and C# are optimized for two different types of computing environments. Just as C++ and Java will co-exist for a long time to come, so will C# and Java.
Progress Check
1. Java is useful for the Internet because it can produce _____________ programs.
2. Java is the direct descendent of what languages?
Java’sContributiontotheInternet
The Internet helped catapult Java to the forefront of programming, and Java, in turn, has had a profound effect on the Internet. The reason for this is quite simple: Java expands the universe of objects that can move about freely in cyberspace. In a network, there are two very broad categories of objects that are transmitted between the server and your personal computer: passive information and dynamic, active programs. For example, when you read your e-mail, you are viewing passive data. Even when you download a program, the program’s code is still only passive data until you execute it. However, a second type of object can be transmitted to your computer: a dynamic, self-executing program. Such a program is an active agent on the client computer, yet it is initiated by the server. For example, a program might be provided by the server to properly display the data that it is sending.
As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability. Prior to Java, cyberspace was effectively closed to half of the entities that now live there. As you will see, Java addresses those concerns and, in doing so, has defined a new form of program: the applet.
JavaAppletsandApplications
Java can be used to create two types of programs: applications and applets. An application is aprogramthatrunsonyourcomputer,undertheoperatingsystemofthatcomputer.Anapplication created by Java is more or less like one created using any other type of computer language, such as Visual Basic or C++. When used to create applications, Java is not much different from any other computer language. Rather, it is Java’s ability to create applets that makes it important.An applet isanapplicationdesignedtobetransmittedovertheInternetandexecuted by a Java-compatible Web browser. Although any computer language can be used to create an application, only Java can be used to create an applet. The reason is that Java solves two of the thorniest problems associated with applets: security and portability. Before continuing, let’s define what these two terms mean relative to the Internet.
Security
As you are almost certainly aware, every time you download a “normal” program, you are risking a viral infection. Prior to Java, most users did not download executable programs frequently, and those that did, scanned them for viruses prior to execution. Even so, most users stillworriedaboutthepossibilityofinfectingtheirsystemswithavirusorallowingamalicious program to run wild in their systems. (A malicious program might gather private information, such as credit card numbers, bank account balances, and passwords by searching the contents of your computer’s local file system.) Java answers these concerns by providing a firewall between a networked application and your computer.
When using a Java-compatible web browser, it is possible to safely download Java applets without fear of viral infection. The way that Java achieves this is by confining a Java program to the Java execution environment and not allowing it access to other parts of the computer. (You will see how this is accomplished, shortly.) Frankly, the ability to download applets with confidence that no harm will be done to the client computer is the single most important aspect of Java.
Portability
As discussed earlier, many types of computers and operating systems are connected to the Internet. For programs to be dynamically downloaded to all of the various types of platforms, some means of generating portable executable code is needed. As you will soon see, the same mechanism that helps ensure security also helps create portability. Indeed, Java’s solution to these two problems is both elegant and efficient.
Java’sMagic:TheBytecode
The key that allows Java to solve both the security and the portability problems just described is that the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the Java Virtual Machine is an interpreter for bytecode. This may come as a bit of a surprise. As you know, most modern languages, such as C++, are designed to be compiled, not interpreted—mostly because of performance concerns. However, the fact that a Java program is executed by the JVM helps solve the major problems associated with downloading programs over the Internet. Here is why.
Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments. The reason is straightforward: only the Java Virtual Machine needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember that although the details of the JVM will differ from platform to platform, all interpret the same Java bytecode. If a Java program were compiled to native code, then different versions of the same program would have to exist for each type of CPUconnectedtotheInternet.Thisis,ofcourse,notafeasiblesolution.Thus,theinterpretation of bytecode is the easiest way to create truly portable programs.
ThefactthataJavaprogramisinterpretedalsohelpsmakeitsecure.Becausetheexecution of every Java program is under the control of the JVM, the JVM can contain the program and prevent it from generating side effects outside the system. Safety is also enhanced by certain restrictions that exist in the Java language.
Whenaprogramisinterpreted,itgenerallyrunssubstantiallyslowerthanthesameprogram would run if compiled to executable code. However, with Java, the differential between the
1.4
two is not so great. The use of bytecode makes it possible for the Java run-time system to execute programs much faster than you might expect.
Although Java was designed for interpretation, there is technically nothing about Java that prevents on-the-fly compilation of bytecode into native code. Along these lines, Sun supplies a JIT(JustInTime)compilerforbytecode.WhentheJITcompilerispartoftheJVM,itcompiles bytecode into executable code in real time, on a piece-by-piece, demand basis. It is important to understand that it is not possible to compile an entire Java program into executable code all at once because Java performs various checks that can be performed only at run time. Instead, the JIT compiles code as it is needed, during execution. The just-in-time approach still yields a significantperformanceboost,though.Evenwhendynamiccompilationisappliedtobytecode, theportabilityandsafetyfeatureswillstillapply,becausetherun-timesystem(whichperforms the compilation) will still be in charge of the execution environment. Whether your Java program is actually interpreted in the traditional way, or compiled on-the-fly, its functionality is the same.
TheJavaBuzzwords
No overview of Java is complete without a look at the Java buzzwords. Although the fundamental forces that necessitated the invention of Java are portability and security, other factors played an important role in molding the final form of the language. The key considerations were summed up by the Java design team in the following list of buzzwords.
Simple
Secure
Java has a concise, cohesive set of features that makes it easy to learn and use.
Java provides a secure means of creating Internet applications.
Portable Java programs can execute in any environment for which there is a Java run-time system.
Object-oriented
Java embodies the modern, object-oriented programming philosophy.
Robust Java encourages error-free programming by being strictly typed and performing run-time checks.
Multithreaded
Java provides integrated support for multithreaded programming.
Architecture-neutral Java is not tied to a specific machine or operating system architecture.
Interpreted Java supports cross-platform code through the use of Java bytecode.
High performance
The Java bytecode is highly optimized for speed of execution.
Distributed Java was designed with the distributed environment of the Internet in mind.
Dynamic Java programs carry with them substantial amounts of run-time type informationthatisusedtoverifyandresolveaccessestoobjectsatruntime.
Another random document with no related content on Scribd:
listen to them. Arnaud lies, as usual, and relates in his journal, that he bought a beautiful slave from a captain—although the black girl belonged to a sailor, and Thibaut, in my presence, played the interpreter when she was sold. He pretends to have been a pupil of the Polytechnic School at Paris, and yet is not capable of writing three lines of French correctly. “In Egypt one must be everything,” Dr. Gand used to say, who studied in Germany, and who, in 1822, was in Greece with me, and the physician in ordinary of Abbas Basha. Europeans appear generally to know this, and therefore exhibit no shame in getting themselves appointed, in Egypt, to situations for which they were never brought up. “Exempla sunt odiosa.”
Still mist this morning, and the hygrometer stood, at eight o’clock, at 78°. We advance about ten o’clock, with a gentle east wind, towards the west. About eleven o’clock, direction S.S.E., one mile’s rapidity of course, and half a mile rapidity of current. Half an hour later we sail westward, in which direction Suliman Kashef has already gone ahead of us. At midday the east wind strengthened and passed over into S.E. We sail for scarcely half an hour S.S.W.; then a very short track to S., where we approach the trees of the Haba, and immediately, W. by N., making three miles and a half in the hour. We remained scarcely five minutes in this direction, as the river winds S.E. A small lake with reed banks, sharply separated from it, lies to the right shore, in this encroaching corner. Probably the river ran formerly through this lake in a straight line, and the angle from S.W. to N.E. was cut off. The S.E. wind is contrary for us, wishing to go S.S.E.; but fortunately this neck of land is dry, and so we take to libàton. Our Dinkas and Mariàn assert that the land here still belongs to the Dinkas, who continue on the right shore still higher up, whilst the Kèks possess the left shore. We go southwards, and anchor at the right shore to fell wood.
In spite of the hot exhalations of the ground, which I felt indeed in my feet and legs, and notwithstanding the heat of 28°, I go a little into the interior of the country. The usual clay soil was under the humus, for the whole surface of the earth was open to it, and full of
deep holes or foot-prints of the colossal animals running here. The trees have a sickly appearance, and are old dwarf trees standing upon and round about the ant-hills. These trees are called Enderàbs. The bark is smooth on the old trunk and has nearly fallen off; on the young straight shoots it is rough, and a brownish grey, like in the hazel-tree; the leaf is lanceolated similar to that of the Oleander’s, but light green and slender, with sharply indented borders. The wood is, on the whole, soft, and may be compared to the linden wood. The greatest part of the Haba consists of these trees, which, however, had also previously appeared. The reed-grass was eaten away and trodden down by the beasts. It might, in former times, have caught fire, and contributed to the destruction of this forest.
Four o’clock. Already the drum has beaten three times for departure; but everything in our vessel remains in the most beautiful state of tranquillity; because the wood-hewers, scattered in the Haba, must be waited for.
The Nile makes here also a circular stream, which is stronger than in the preceding curve, where we were driven, in spite of sailing and rowing, on to Selim Capitan’s vessel. So likewise Suliman Kashef comes upon us, as if he were going to board us, whilst we were lying quite peaceably at the shore. The current of the river is far stronger, and receives below a check by the lake, which may give it additional water, for the islands floating there dance a waltz in front of us before going further. There must be some cause for that. I advance, and see, on the left, another small lake, and succulent green grass, from its shore even to the Nile. This lake stretches from N.E. to S.W. The river makes a bend from our landing-place, which we leave soon after four o’clock, from W. to S.S.W. I am inclined to believe, judging from the yellow reed-grass, that this lake, like the former one, where the crew, when towing, were able to go over the dam, separating it from the river, is closed at its heading, whilst the river flows by it. I remark also, up the country, green tracks of vegetation, possibly covering for a short time, or for ever, the vital veins of the lake. The Haba loses itself, and only solitary trees denote still the right side of the Nile, whilst W.N.W. to S.W. a tract,
rich in trees, bounds the horizon. The south extends before us, from S.W. to S.E., without a tree, and perhaps, therefore, has the riverbed in its centre.
The trees of the left side are unfortunately too far for us to distinguish them. The crew think, however, that they must be a kind of date-palms (naghel; the fruit, however, is called tammer, or bellàgh). But Mariàn says that there are many trees on that side belonging to the palm species, but bearing large, beautiful fruit, containing milk, which, he thought, were a species of cocoa-palm. These trees rise with a straight shaft similar to the date and dhellèbpalms; but the top appears to be entirely flat, like an extended fan, or a round table. I had seen also, from the ship, in that forest, some poison-trees: now, I heard dreadful things told of them, that even the scent of their flowers, or a thorn, nearly invisible on them, falling on one’s hand, is certain death, and that the natives poison their arrows with it. This Shudder el Simm is called, in the language of the Nubas, Auer, and I was curious to see the tree somewhat nearer.
With the before-mentioned short course from W. to S.S.W., we came again to the right shore, and to the Haba, where we halted again. I sprang on the shore, which is only two and a half to three feet above the water, as in the preceding place, under the very same appearances, and I found in the poison-tree an old acquaintance of mine at Taka; but with this difference, however, that it might be called here a tree, whilst there it was only a shrub. Both of them are Euphorbias. I had, in Taka, cut off such a cactus-like plant, with its blue-reddish flowers, similar to those of the ushàr (Asclepias procera), and crushed it in my hand, when I punished in the Haba the stubbornness of my donkey, who wanted to join his brothers grazing in the meadow. I had involuntarily touched my lips and the tip of my tongue with the hand wet with the poisonous sap. Notwithstanding all the washing, I for two days found the taste of it quite abominable, without alarming myself the least about it, for I did not consider it more poisonous than the ushàr, the leaves of which are eaten by goats. These leaves, well-known from their intoxicating quality, are laid upon funnel-shaped sieves, in order to
strain merissa through them, by which the milk, gushing from the leaves, mixes with the liquor itself.
I made no ceremony of cutting off a branch from a poison-tree fifteen feet high, with the fruit, which are little round knobs, and had not yet come to maturity. The crew were somewhat angry when I came on board with it, and avoided me, till they saw that I laid it close to me on my bed, without the least evil consequences arising from it. Mariàn told me that they prepared the poison from this tree by boiling its milk and the sap, pressed between two stones; when this has become thick, like asside (meal-pap), the arrows are dipped into it.
The wind has left us, and we advance with the assistance of oars, about five o’clock, from S.S.W. to W.S.W. Towards S.W. the oars were obliged to assist the hoisted sails, owing to the faint wind. A small lake shews itself again, as before, on the left, where it goes round in the obtuse corner from S.W. to N.E. This announces here the old direction of the once majestically flowing river, parallel with the forest, to the brink of which these lakes are arranged in a line, one by the other. We go from S.W., around the before-named corner, to N.E., leave the lake mentioned behind us, and have, at sunset, a long row of low tokuls, near which a thick cloud of smoke extends to a distance. Our blacks perceive through the smoke a large herd of cattle. We have wood enough, but for several days have been deficient in meat, and the crew cannot apparently pass without tasting the flesh of these animals. No human form, however, is to be seen on the shore any more than on the right, where we had remarked isolated huts, as well as by the lakes. To the west, behind this village, extends an immeasurable meadow, having mists rising over it, like clouds, whilst a thick layer of mist lies round the whole horizon, which we may consider as an exhalation from the dried-up country.
The new moon is seen and heartily greeted by the Reïs, as a sign of our fortunate journey. Nevertheless, it was two days old, and there was but little merit, therefore, in its discovery by the Arabs,
who themselves discover immediately the fine sickle of the new moon, even when the sun is still in the heavens. We moved up to eight o’clock a short distance in S.W., and anchored in the middle of the river to wait for the morning, and with it the hospitality of the herdsmen.
26th December . We looked in vain this morning for an oblation of flesh, and an embassy on the part of the herdsmen. Therefore, even before sunrise, we moved on with a faint wind from S.W. to N.W. On the left of the right shore a village, but no human beings, and, somewhat forward, a lake in the corner, from N.W. to W.: they told me from the mast that even behind the village there was a lake. It is the very same case with this lake as with the preceding ones. The range of these lakes of themore straighttract, which the river previously followed as the direction most worthy of it, and even now at high-water may renew for a short time, is plainly manifest. Solitary trees stand right and left, more or less removed from the shore; but no high shore is to be seen here, such as the line of the horizon, covered with trees, had deceived me to believe. This dry pasture-land is, at the most, three feet above the water; and even from the trees and high ant-hills yesterday, I could not discover any other tract of shore than that which the separated trees afford, and in the direction of which the lakes follow behind one another.
The bed of the Nile has raised itself here like in all other places, without the shore being proportionably elevated: this is also the case in Nubia and Egypt; for the level ground gives an indefinite extension to the stream, by which it can wallow and carouse in the untried shores; not to mention that this whole territory navigated by us was a fresh water lake. The shore land could not therefore be raised in the manner of downs here by the river, on account of the want of sand or light earth, and moreover, because the river deposits also but little slime, the ingredients of which flow away to the hollow land, and only receive their fertilizing qualities by the process that takes place on their journey.
Eight o’clock.—The faint S.W. veered for a short time to the North, with a slight squall, and we sailed with two miles course from S.W. to S.; but on the left the evolution continues in the form of an arch to E. by S., where we halt, in order to go, libàhn, the wind coming now from the east. The left shore forms a broad edge of high reeds, over which we cannot see. Red and blue convolvulus float and creep around, as well as two species of wild cucumbers, one of which has a large and deep yellow flower; the other, small and pale yellow. Reddish and yellowish flowing beans, and other water-plants, are entwined in picturesque confusion. On the left hand is observed in the distance a single palm, which was previously on our right, so that we can scarcely imagine how we shall get in the old path again. Over an extended, magnificently green savannah prairie of high grass, the melancholy Enderàb forest of yesterday is still visible at a distance: its soft wood is as brittle as glass.
I yesterday split several stems of the ambak already described. I found, as previously, that they are more like a woody pith than real wood. No pith, properly speaking, is distinguished at the first sight, but I now discover that a pith-canal of about a quarter of an inch in diameter shoots through it. The contents were cleared out in the most careful manner by ants, as is generally the case where these insects are in the neighbourhood. The giant rush is becoming less abundant. The ray-formed expanding rushes of the corolla are often two feet long, and branch again into smaller ones, with the usual tendency of the flowers of rushes. From nine to half-past one o’clock, we have only made two miles and-a-quarter with the towing-rope, for the high reeds hung with creepers on the right margin of the river present endless difficulties. It is to be hoped that the N.E. wind which has now set in, will continue for a time, for we make three miles, as we go from E. by S., over S.E. to S. At three o’clock we make a further bend from S. over E. to N.E., yet with the line, where another margin of high reeds gave us the same trouble.
We passed here by some tokuls, which were plundered of everything by the men towing the vessels. They gave me also fruits and lotus-roots, being here as large as pomegranates, and quite
fresh; on account of which they were placed on reed-stalks to dry. This fruit is still abundant in the rushy marshes, and very quickly ripens, because we have not seen any lotus-flowers since the land of the Shilluks. They also brought me seeds of the broad reeds called “slaves’ rice.” When we survey the small stock of rice in the corbel, we find that this is not even collected in a mass, and therefore a harvest of grain—that is, of this and similar seeds—must be always very troublesome. The reed-grass here was never trodden down by cattle, and these people may therefore only live by fishing. Two fish, large of their species, the Bolti (Chromis Niloticus), a favourite with every one in Khartùm, lie on the shore, and must therefore not be quite fresh, as the Egyptian wolves let them remain. A dark brown thick felt cap, found there, was well adapted by its globular form to make a blow with a club less sensible or entirely harmless. At four o’clock we sail a short track S. by E.: see on the right and left small fishing-villages, and, indeed at this moment shaded by the reeds. The surface of the earth is here clearly somewhat higher, and therefore was dried sooner. The extreme margin of the shore was, near the plundered village, from two and a half to three feet high; whilst that towards the huts was one and a half or two feet higher, and formed a kind of low dike. A subordinate river, choked up with mud, and appearing to be used as a fish-pond, lies behind the huts on the right shore. We have soon at our side a second village with two geïlid-trees, as well as a deserted river-bed for fishing in; for we see at the lower end a ditch, serving, after the high water has receded, for the letting off of this fish-pond.
Beyond this village we perceive some trees, near which the smoke rises up in several places. The last little hamlet consists of fourteen tokuls, and the people are seen afar off amid the grass hastening to five other tokuls by the reeds. The inundation seems here altogether to cease, and the medium height of the water to have commenced for some time. A vigorous smoke, like a widespread steam of slaughtering, delights our crew. They hope to be able to regale their stomachs with the delicious roasted morsels, enveloped by these clouds of smoke, and protected against the
insects. We wind an ell’s length to the right S.W., and over S.S.E. to S.E., and immediately again to W.N.W., where we have at five o’clock a large island, in the shape of a half-moon at our left, and we go then in a bend to the East. The border of the island consists of reeds continually running into the river, with their beautiful wreaths of flowers in dentated points; whilst the ambak forms, in the direction of the interior, gently ascending hills and woods, which, with their fresh green reeds, promise more than they may be able to keep. The floating islands are always meeting us or driving by us, and afford us, on the whole, the best proof that we have not yet escaped the marshy regions. I have been seeking for several days, but in vain, a small-leaved water moss, on account of its elegance, in order to put it again in my collection.
The wind at last, having veered to the north, is nearly quite spent, and we go from an easterly direction, shortly before sun-set, to the south. The before-named island seems to have a considerable breadth, according to the account from the mast. The river winds again eastward, and we halt immediately after sun-set, having left behind a well-built village, containing fifteen tokuls, to wait for the Kaiass and the sandal, which we had abandoned again to their fate. The Turks hoped, however, that there would be some people in this village, as it shewed signs of prosperity, and that they would come to us, to make our worthy acquaintance; but they were deceived, for the natives appeared to have fled from hence far and wide.
The Arabs are fond of giving nicknames, derived either from the figure, or some other distinction and manner of acting, to which they prefix the word Abù. The Kurd, Hüsseïn Aga, has distinguished himself for a short time, by drinking merissa, which he prepared on board his vessel; for he found the time hang heavy on his hands, as he told me, and was vexed that his vessel was always behind. He was therefore called AbùSofaia,—the latter word being the name of the sieve for merissa. If a pair of them wanted to teaze each other, they began to ask, reciprocally: “Your father, what is his name?” “You, what is your name?” then followed jeering, abusing, and scoffing. They do not fail, in addition, to use the coarsest words, if
the Turkish listeners are pleased at it. On the sun setting, the new moon turned both her horns in equal height to the heavens, and Venus shone immediately over it, exactly similar to the Turkish escutcheon. This symbol appeared to me more suitable than all our heraldic compositions.
For the last two nights the gnats have been very troublesome, notwithstanding that a small cat, which I have not yet seen by daylight, seems to find particular pleasure in licking my face all the night through, pulling my beard, and purring continually, thus scaring away the gnats. The cats, however, in Belled-Sudàn are generally of a more savage nature, apparently arising from the unkind treatment of the people: they go even into the hen-roosts, and the strongest fowls are lacerated by them; but they meddle very little with rats and mice. The Baràbras, especially those of Dòngola, like them for eating; not so, however, the Arabs, who do not persecute them, because the cat is one of the favourite animals of their Prophet, but yet hold them unclean. The sky was cloudy to-day, as it was yesterday and the day before.
27th December . Set out immediately after sunrise towards N.N.W. The sun rises of a dark red colour, exactly behind us, out of the river, into the red humid atmosphere, and yet there is the main direction of the river; we have, therefore, a real labyrinth of circuitous routes to work through. If yesterday, no object disclosed itself in the south, for the eye to rest upon, so now in the left, the arm flowing round the island is only to be seen; there is nothing besides but reeds, and the water which we are navigating. The high reeds may, it is true, here and there conceal from the eye a tree or a hut, because, on the whole, we go lower between the dried-up shores. The N.E. wind is slack, and we assist the sails by rowing in S.W., where, about eight o’clock, a small village of twelve tokuls starts up, on the left side of the river, the river coming from S.E. A dog barks from the neighbouring reeds, and betrays the hiding-place of the people who had fled, which the blacks, accustomed to similar signs, corroborated, and wanted even to shoot into the reeds. Our
Abù Hashiss barked lustily against the animal, and it really appeared as if several large and small dogs were barking.
About an hour’s distance beyond the village some trees are to be seen; whilst, on the left, where the river now winds to S.E., we do not observe anything. This also appears to be a fishing village, for we do not remark any trace of the tread of cattle in the grass. These poor Icthyophagi have, according to their usual custom, wretched huts, and their tokuls are also partly plastered with Thin. This thin, or Nile slime, naturally affords a good material for plastering the reed walls. It would be good for airstones, if these should be generally considered a suitable building material in places where the violent periodical rains of the tropics only too often shew the contrary. I myself have experienced this in Khartum, where in one night some thirty houses fell. The storm of rain was so violent, that it broke through the wall of our bed-room, three feet thick, built of airstones, and in a short time tore an opening the size of a window. It was only with the greatest difficulty that I was able to save my brother (the servants being at a distance), by carrying him away. He was dangerously ill at the time, and, bursting out into a clear loud laugh, vigorously resisted my endeavours to lay him upon a table under the door-way, in order that he might not be buried by the fall of the roof.
The whole horizon is without a high tree; only the ambak covers, in small thickets, a great part of the island, which is still drawing nearer to us. The ambak appears here considerably higher and stronger, to which the warmer climate, together with the earlier inundation and the growth thereby produced, has mostly contributed. On the return voyage I will try to procure, at all events, seeds of it; for I am really curious to see, at some future day, this new species of tree, the ambak, in my own native country, even should it be in a hot-house. Although it may not thrive and grow as quickly with us as here, yet I am quite sure that its incredible productive powers will excite the more astonishment, because its many large flowers and great succulent acacia-like leaf, make it an ornamental tree.