Java

download Java

If you can't read please download the document

Transcript of Java

TEAM LinGJavaTechAn Introduction to Scientific and Technical Computing with JavaJavaTech is a practical introduction to the Java programming language with anemphasis on the features that benet technical computing, such as platformindependence, extensive graphics capabilities, multi-threading, and tools todevelop network and distributed computing software and embedded processorapplications.The book is divided into three parts. The rst presents the basics ofobject-oriented programming in Java and then examines topics such asgraphical interfaces, thread processes, I/O, and image processing. The secondpart begins with a review of network programming and develops Webclient-server examples for tasks such as monitoring of remote devices. Thefocus then shifts to distributed computing with RMI, which allows programs ondifferent platforms to exchange objects and call each others methods. CORBAis also discussed and a survey of web services is presented. The nal partexamines how Java programs can access the local platform and interact withhardware. Topics include combining native code with Java, communication viaserial lines, and programming embedded processors.JavaTech demonstrates the ease with which Java can be used to createpowerful network applications and distributed computing applications. It can beused as a textbook for introductory or intermediate level programming courses,and for more advanced students and researchers who need to learn Java for aparticular task. JavaTech is up to date with Java 5.0.CinkS. Li os ivreceived his Ph.D. in physics from the University ofCalifornia at Riverside and has held research positions at Iowa State University,Fermilab, and the Royal Institute of Technology, Sweden. This book grew out ofa course in Java programming he developed with Professor Lindblad. He nowruns his own company that develops Java applications, Web publications, andeducational tools and materials.J onv S. Toiii vinholds a Ph.D. in Computational Plasma Physics andhas worked in fusion energy research, computer security, and trusted operatingsystems. He is a Sun Certied Java Programmer and has been actively usingJava since 1997. He is currently at Oak Ridge National Laboratory, developingWeb services software and a GPS vehicle tracking application usingGPS-enabled wireless phone handsets and other GPS devices.Tnoms Li onioreceived his Ph.D. in physics at the University ofStockholm in 1972 and became associate professor two years later. He iscurrently a professor in the Department of Physics at the Royal Institute ofTechnology, Stockholm, and also serves part time as Director of UndergraduateStudies. His research currently concentrates on techniques in image and dataanalysis in high data rate systems.JavaTechAn Introduction to Scientific and TechnicalComputing with JavaClark S. Lindsey, Johnny S. Tolliverand Thomas Lindbladcambridge university pressCambridge, New York, Melbourne, Madrid, Cape Town, Singapore, So PauloCambridgeUniversityPressThe Edinburgh Building, Cambridgecb2 2ru, UKFirst published in print formatisbn-13 978-0-521-82113-1isbn-13 978-0-511-13093-9 C. S. Lindsey, J. S. Tolliver and T. Lindblad 20052005Information on this title: www.cambridge.org/9780521821131This publication is in copyright. Subject to statutory exception and to the provision ofrelevant collective licensing agreements, no reproduction of any part may take placewithout the written permission of Cambridge University Press.isbn-10 0-511-13093-7isbn-10 0-521-82113-4Cambridge University Press has no responsibility for the persistence or accuracy ofurlsfor external or third-party internet websites referred to in this publication, and does notguarantee that any content on such websites is, or will remain, accurate or appropriate.Published in the United States of America by Cambridge University Press, New Yorkwww.cambridge.orghardbackeBook(NetLibrary)eBook(NetLibrary)hardbackContentsPreface page xiiiAcknowledgements xixPart I Introduction to Java1Introduction 31.1 What is Java? 31.2 History of Java 41.3 Versions of Java 51.4 Java open or closed? 81.5 Java features and benets 81.6 Real-world Java applications in science and engineering 121.7 The Java programming procedure 141.8 Getting started 171.9 Changes in Java 2 Standard Edition 5.0 231.10Web Course materials 27References 27Resources 282Language basics 292.1 Introduction 292.2 Language elements and structures 292.3 A simple application 312.4 Comments 322.5 Data types and Java primitives 332.6 Strings 352.7 Expressions 352.8 Operators 362.9 Statements 392.10Casts and mixing 442.11Floating-point 472.12Programming 502.13Basic math in Java 532.14Web Course materials 55Resources 55vvi Contents3Classes and objects in Java 573.1 Introduction 573.2 Custom data types 573.3 Class denition 583.4 Class instantiation 653.5 Static (or class) members 673.6 More about primitive and reference variables 693.7 Wrappers 733.8 Arrays 793.9 Exceptions 803.10OOP in engineering and science 843.11Web Course materials 90Resources 904More about objects in Java 914.1 Introduction 914.2 Class inheritance 914.3 More about constructors 1004.4 Abstract methods and classes 1054.5 Interfaces 1094.6 More about classes 1154.7 More about arrays 1204.8 Improved complex number class 1254.9 Random number generation 1264.10Improved histogram class 1284.11Understanding OOP 1304.12Web Course materials 130References 131Resources 1315Organizing Java les and other practicalities 1325.1 Introduction 1325.2 Class denition les 1325.3 Packages 1335.4 The final modier and constants 1405.5 Static import in J2SE 5.0 1415.6 JAR les 1435.7 Distributing Java code 1465.8 Applet directories 1485.9 Javadoc 1495.10Coding conventions 1505.11Formatting numbers 153Contents vii5.12Web Course materials 158References 159Resources 1596Java graphics 1606.1 Introduction 1606.2 AWT 1616.3 Swing: lightweight beats heavyweight 1626.4 Swing class hierarchy 1636.5 Containers 1646.6 Drawing 1746.7 Drawing with the Graphics class 1786.8 Drawing in the Java 2D API 1836.9 Images 1906.10Java and tech graphics 1926.11Histogram graphics 1926.12Web Course materials 199References 2007Graphical User Interfaces 2017.1 Introduction 2017.2 Events 2017.3 More user interface components 2127.4 Layout managers 2237.5 Convenience classes 2377.6 Frames and menus 2427.7 User interface with histogram display 2477.8 Web Course materials 251References 2528Threads 2538.1 Introduction 2538.2 Introduction to threads 2538.3 Stopping threads 2588.4 Multiprocessing issues 2598.5 Using multiple threads 2628.6 Animations 2768.7 Timers 2818.8 Concurrency utilities in J2SE 5.0 2858.9 Web Course materials 285References 286viii Contents9Java input/output 2879.1 Introduction 2879.2 Streams 2899.3 Stream wrappers 2909.4 Console I/O 2919.5 The File class 2999.6 File I/O 3019.7 Character encoding 3129.8 Object I/O 3139.9 Choosing a stream class 3159.10Primitive types to bytes and back 3159.11Sources, destinations, and lters 3179.12The JFileChooser dialog 3189.13Histogram I/O 3209.14More Java I/O 3259.15Web Course materials 326References 32610Java utilities 32710.1 Introduction 32710.2 The java.util package 32710.3 Vector and Enumeration 32810.4 Hashtable, Properties, and HashMap 32910.5 Preferences 33110.6 The Collections Framework 33510.7 Generics in J2SE 5.0 33810.8 Concurrency utilities in J2SE 5.0 34110.9 Enumerated types in J2SE 5.0 34310.10The Arrays class 34510.11Tools for strings 34910.12Calendar, Date, and Time 35310.13Arbitrary precision numbers 35610.14Bit handling 36010.15Other utilities 36210.16Web Course materials 363References 36311Image handling and processing 36511.1 Introduction 36511.2 The Image and BufferedImage classes 36511.3 Image loading 36711.4 Image display 37111.5 Creating images 37211.6 Saving images 373Contents ix11.7 Image processing 37311.8 Pixel handling 37411.9 Filtering 38011.10Web Course materials 389References 389Resource 38912More techniques and tips 39012.1 Introduction 39012.2 Printing 39012.3 Cursor icons 39212.4 Mouse buttons 39412.5 Popup menu 39612.6 Handling keystrokes 39912.7 Audio 40212.8 Performance and timing 40412.9 Lifelong Java learning 40912.10Web Course materials 410References 410Part II Java and the network13Java networking basics 41313.1 Introduction 41313.2 Internet basics 41313.3 Ports 41513.4 Java networking 41613.5 The URL class 41713.6 InetAddress 42313.7 Sockets 42613.8 The client/server model 42813.9 Web Course materials 430References 430Resources 43014A Java web server 43114.1 Introduction 43114.2 Designing a web server 43214.3 Hypertex Transfer Protocol (HTTP) 43514.4 Running the server 43814.5 A more secure server 43914.6 A client application 44314.7 Server applications 44514.8 Servers, servlets and JSP 446x Contents14.9Web Course materials 447References 44715Client/server with sockets 44815.1Introduction 44815.2The client/server design 44815.3The client/server interaction 44915.4The DataServer 45015.5The DataWorker 45315.6The DataClient 45915.7The DataClientWorker 46415.8Benets and shortcomings of sockets 46915.9Web Course materials 469References 47016Distributed computing 47116.1Introduction 47116.2Distributed computing for scientic applications 47116.3Minimalist UML 47316.4A conceptual model for a simple distributed application 47516.5Collaboration diagram for a simple distributed application 47716.6Server details 48116.7Web Course materials 490References 49117Distributed computing the client 49217.1Introduction 49217.2Multithreaded client 49217.3Model-View-Controller for the client 49317.4More client details 49617.5Improved client class diagram 49817.6Web Course materials 500Resources 50018Java Remote Method Invocation (RMI) 50118.1Introduction 50118.2How distributed computing works 50118.3RMI overview 50318.4The RMI client 50918.5RMI security issues 51118.6Finally, a working example 51518.7How to run on two machines 52718.8Conclusion 528Contents xi18.9Web Course materials 529References 52919CORBA 53019.1Introduction 53019.2CORBA IDL 53119.3Compiling the IDL le 53519.4Creating the server implementation 53719.5Client implementation 54419.6Running the example 54519.7Running the CORBA example on two machines 54719.8Conclusion 54819.9Web Course materials 548Resources 54820Distributed computing putting it all together 54920.1Introduction 54920.2The sample application 54920.3Server interfaces 55120.4Server factory implementation 55320.5Server implementation 55620.6Client implementation 56820.7Enhanced client using the histogram class 56920.8Conclusion 57120.9Web Course materials 572References 57221Introduction to web services and XML 57321.1Introduction 57321.2Introducing web services for distributed computing 57321.3XML 57421.4Java web services 57821.5Other web services technologies 58021.6Conclusion 58121.7Web Course materials 581References 581Part III Out of the sandbox22The Java Native Interface (JNI) 58522.1Introduction 58522.2What is JNI? 58622.3Hello World in JNI 58722.4Deeper into JNI 597xii Contents22.5 Java String objects 60022.6 Java primitive arrays 60422.7 Java object arrays and multidimensional primitive arrays 60622.8 Java objects on the C side 60722.9 Calling Java methods from native code 61522.10Exceptions in JNI 61822.11Local and global references 62222.12Threads and synchronization in JNI 62322.13Conclusion 62422.14Web Course materials 624References 62423Accessing the platform 62523.1 Escaping the sandbox 62523.2 Accessing system properties 62523.3 Running external programs 62923.4 Port communications 63123.5 Web Course materials 650References 650Resources 65024Embedded Java 65124.1 Introduction 65124.2 Embedded Java for science and engineering 65224.3 J2ME Java 2 Micro Edition 65224.4 Real-time Java 65424.5 Java real machines 65724.6 Benets of hardware processors 65824.7 Java processors 65824.8 Java boards 66124.9 Programming the Javelin Stamp 66524.10An embedded web server 67124.11Java processor performance 68024.12Web Course materials 680References 680Appendix 1: Language elements 683Appendix 2: Operators 685Appendix 3: Java oating-point 693Index 697PrefaceJavaisaseriouslanguagesuitablefordemandingapplicationsinscienceandengineering. Really, wepromise!Javaoffersalot morethanjust thoselittleapplets in your Web browser.In JavaTech we focus on how Java can perform useful tasks in technical com-puting. These tasks might involve an animated simulation to demonstrate a scien-tic principle, a graphical user interface for an existing C or C++computationalengine,adistributedcomputingproject,controllingandmonitoringanexper-imentremotelyviatheInternet,orprogramminganembeddedJavahardwareprocessor in a device such as a remote sensor. While other Java books intendedfor the science and engineering audience concentrate primarily on numerical pro-gramming, we take a much broader approach and examine ways that Java canbenet programmers working on many different types of technical applications.This project grew out of a course given by two of us (C.S.L. and Th.L.) atthe Royal Institute of Technology in Stockholm, Sweden in which students ofdiverse backgrounds followed the class via the Internet. For this type of distancelearningsituation, wedevelopedhypertext instructional material fordeliveryvia the Web browser that allows for a high degree of self-study. This approachworks especially well with Java since many of the demonstration programs runas applets within the browser.This book provides a handy print companion to this hypertext course, whichis available online at www.javatechbook.com. The book includes additionalmaterial that deals with distributed computing techniques based on work done byone of us (J.T.) at Oak Ridge National Laboratory in the USA. Throughout thebook we refer to the hypertext materials as the Web Course.Who should use this bookJavaTech targets primarily those who want to learn the Java programming lan-guage so as to apply it to practical applications in science and engineering. Fromthe freshman science major to the experienced programmer in a technical eld,we believe this book and the Web Course will be helpful.For those unfamiliar with the language and with object-oriented programming,we begin with a compact introduction to Java. Since Java has grown into a verybig eld we only touch on the essential elements needed to begin doing usefulxiiixiv Prefaceprogramming. We include examples of howJava can apply to technical tasks suchas histogramming of data and image analysis.While familiarity with C and C++ will hasten a readers understanding ofJava programming, we do not assume the reader knows these languages.After the Java introduction we discuss network programming, which we con-sider to be one of Javas strongest features. We focus particularly on how to buildclient/server systems for distributed computing applications. If you have a net-work application, such as the need to monitor remote devices or to give distantusers access to a complex simulation running on a central server, the survey hereshouldhelpyougetstarted.Ouraimistoshowthatyoucancreatepowerfulnetwork software with Java without needing rst to become an authority on allthe arcane intricacies of network systems. Javas networking tools and platformportability allow you to focus more on your application than on the underlyingmechanisms.The nal part of the book looks at how Java can interact with the local plat-form, with code in other languages, and with embedded processors. For example,perhapsyouhavealegacyprograminCthatrepresentsmanyyearsofdevel-opment and tuning, but it lacks a graphical interface to make it interactive andexible. We discuss the Java Native Interface (JNI) that allows you to connectyour programto Java and to take advantage of the extensive graphical tools avail-able in Java to build an interface around your computational engine in C (or inFortran via intermediate C code as discussed in the Web Course). You can alsoaddthenetworkingcapabilitiesofJavadiscussedabove.Forexample,remoteclients could connect with your legacy program that runs on a central server.HardwaremicroprocessorsdesignedespeciallytorunJavaarenowwidelyavailable. Those who work on embedded processor applications will be interestedinoursurveyoftheeldofJavaprocessors.Inademonstrationprogram,forexample, we show how to connect via a serial port to a microcontroller that isprogrammed with Java and used to read a sensor.We look at compact, low-cost platforms that contain Java processors, Ethernetconnectors,analog-to-digitalinputs,digital-to-analogoutputsandotherusefulfeatures. With such systems you can run servers that allowremote clients to moni-tor, control, and diagnose an instrument of some kind. This offers the opportunityto those who work with large complex installations, such as an elaborate scien-tic apparatus or a power plant, to access and control a system at a ne-grainedlevel. We provide a demonstration of a server on such a Java processor platformin which the server responds to a Web browser with an HTML le containing avoltage reading.Organization and topicsWe attempted with this book and Web Course combination to create an innovativeand highly exible approach that allows readers with a diverse range of interestsPreface xvandbackgroundstondanduseeffectivelythematerialsfortheirparticularneeds. The Web Course includes hypertext tutorial materials, manydemonstrationprograms, andexercises. ThebookcomplimentstheWebCoursewithmoreextensive discussions on a range of topics and with tables and diagrams for quickreference.Wefollowanexample-basedteachingapproach, usinglotsofappletsandapplication programs to demonstrate the concepts and techniques described. Inaddition, we supply a large selection of starter programs that provide templateswith which readers can quickly begin to develop their own programs.The chapters in the book correspond directly to those in the Web Course. Notethat while one of Javas strongest features is its extensive graphics capability, wedo not discuss graphics programming in the rst ve chapters. Instead we focusonthecomponentsandstructureofthelanguage.Wedemonstratetechniqueswith stand-alone programs (referred to in Java as applications) that print to theconsole and applets that send output to the web browsers Java console window.The book and Web Course are divided into three parts plus appendices.Part I Introduction to JavaThe12chaptersinPartIprovideanintroductiontotheJavalanguage.ThesechaptersfocusontheJavalanguagebut alsodiscussvarioustopicsrelevantto applying Java to technical areas. The Web Course expands the introductorymaterial into three tracks:The Java Track provides an introduction to Java programming. The reader canfollowthistrackaloneforaquickcourseinthebasicsofJavaprogramming.Supplements provide additional information on both basic and advanced topics.The Tech Track focuses on topics relevant to general math, science, and engi-neeringapplicationsofJavasuchasoating-point numbers, randomnumbergenerators, and image processing.The Physics Track provides an example of how to apply Java to a particulartechnical subject. Thetrackcorrespondstoashort courseforundergraduatestudents on the use of numerical computing, simulations, and data analysis inexperimental physics.Part II Java and the networkThis part focuses on the application of Java to network programming and dis-tributed computing. It begins with an introduction to TCP/IP programming andthen looks at several topics including socket based client/server demonstrationprograms and distributed computing with RMI, CORBA, and other techniques.An introduction is given to Unied Modeling Language (UML), which leads tobetter object oriented code design and analysis. A brief overview of web servicesand XML is also provided.xvi PrefacePart III Out of the sandboxThis part deals with how Java programs can access information and resources onthe underlying platforms on which the Java Virtual Machine (JVM) is installedand how the JVM can interact with its local environment. It also reviews imple-mentations of Java in hardware rather than in a virtual machine. Topics includeinterfacingJavaprogramstoC/C++andFortrancodeswiththeJavaNativeInterface (JNI), communicating with devices via serial/parallel ports, and work-ing with embedded Java processors.AppendicesAppendices1and2providetablesofJavalanguageelementsandoperators,respectively. Appendix 3 gives additional information about oating-point num-bers in Java.Topics not discussedJava has grown into an enormous industry since it rst appeared in the mid-1990s.No single book could possibly do justice to all of the Java classes, packages, tools,techniques, andapplicationsofthelanguage. Infact, thereexistmanybooksdevoted to individual topics such as Java I/O, graphics, and multithreading. TheJava industry expands further every day.For this book we have chosen what we consider to be an important subset ofJava topics relevant to technical applications. Some important topics not treatedinclude:rJava Enterprise techniques, such as database access and Java application serversrSecurity topics such as the Java Cryptography Extension (JCE)rJava 3D graphicsWe do provide in the Web Course a large set of links to references and resourcesfortheseandotherJavasubjects.Wealsobelievethatthisbookprovidesthereader with a solid base of understanding on which to pursue further learning.All Java programmers must deal with the need to continually learn new classesand APIs (Application Program Interfaces). As we go to press, Sun is about torelease Java 2 Standard Edition version 5.0, which contains signicant additionsto the language. We discuss the most important of these but some are beyond thescope of this book.We emphasize the use of the web for access to language specications, onlinetutorials, and other resources needed to tackle new Java techniques. We includereferences andweblinks ineachchapter andintheWebCourse. Youcanalso nd many online resources at http://java.sun.com, java.net, andwww.ibm.com/developerworks/java/.As mentionedinthe introduction, we donot delve intonumerical programmingwith Java. We only touch on this subject here while the Web Course Tech andPreface xviiPhysics tracks contain several introductory level sections. See the reference listat theendofChapter1foralist ofseveral booksthat deal extensivelywithnumerical programming in Java.How to use this book and Web CourseWe designed the book and Web Course in a way that lets readers follow individ-ualized paths through the materials. Part I, in particular, allows for a variety ofdifferent approaches. You could, for example, study only the Java sections of eachchapter and get a fast introduction to the basics of Java programming. You couldalsostudythesectionswithparticularrelevancetotechnicalapplications(theWeb Course expands on these in its Tech Track) or, alternatively, you could skipthese tech topics in a rst pass and return to them later. Those already familiarwith Java basics could focus just on the tech-related topics.YoucanproceedthroughthebookandWebCourseatyourownpaceandexperiment with the many applets and application demonstration programs. Thereis an emphasis on coding by the reader since ultimately you can only learn Javaor any other language by writing lots of programs yourself.Part II and Part III deal with specialized topics. If you are already familiarwith the basics of Java programming, you could proceed directly to the chapteror sub-section of interest in those parts.One of the most important features of Java is its extensive network program-ming capability. So we designed the course around the assumption that the readerhas easy access to the Internet. Most of the Web Course pages include links toreference and resource materials, especially the tutorials and language specica-tions on the http://java.sun.com website. Rather than reinvent the wheelwe try to incorporate resources such as the Sun tutorials in a way that takes bestadvantage of what is already available.The Web Course hypertext materials and demonstration codes, alongwith updates and corrections to the book, are available at the websitewww.JavaTechBook.com. (Amirrorsiteisavailableat www.particle.kth.se/~lindsey/JavaCourse/Book/.)Note that if we included in the book the source codes for all the demonstrationprograms, it would be a very long book indeed. Since the source codes are easilyavailable from the Web Course, we often print only code snippets rather thanentire classes or programs.ConventionsFixed width style indicates:rcode samples such as: for (i=0; i < 4; i++) j++;rJava class names, variable names, and other code-related termsrconsole commands such as: c:\> java HelloWorldrweb addresses such as http://java.sun.comxviii PrefaceIn code listings, italicized fix width indicates that the text is not actually inthe code but included to emphasize some aspect of the code or to summarize codethat was skipped. We also put the class name in bold in the code listings. (Codingstyle conventions are discussed in Section 5.9.) When discussing a method in thetext we may often ignore the argument list for the sake of brevity. So aMethod(int x, float y, double z) is abbreviated as aMethod().In the main text, new terms of particular importance are italicized. The bookname and Web Course sections are also italicized.InChapter22ontheJavaNativeInterface, weusethenotationXxxandxxx as placeholders to represent the many possible names that can replace theXxxor xxx. For example, JNI hasaGetIntField()method. It alsohasGetFloatField(), GetDoubleField(), etc. methods. We refer to these as agroupwiththe GetXxxField()notation. Similarly, the xxxinjxxxArraycanbe replaced with int, float, double, etc. to produce jintArray, jfloat-Array, jdoubleArray, etc.Java versionThe code in JavaTech primarily follows that of Java version 1.4 released in 2002,but we discuss the signicant enhancements available in the Java 5.0 release whererelevant. (This release was under development for at least two years and becameavailable in beta form near the end of the writing of this book.) Since many webbrowsers currently in use only run Java 1.1 applets and also since some smallplatforms (e.g. embedded processors) with limited resources only run Java 1.1,we also include in the Web Course some discussion of programming techniquesfor this version and provide sample codes.The programs do not usually assume a particular platform and should run onMS Windows, Mac OS X, Linux, as well as Solaris and most Unix platforms.AcknowledgementsWe would like to thank our editors Simon Capelin and Vince Higgs for their helpand patience. We thank Roger Sundman and Carl Wedlin of Imsys Technologiesfor their review of the Java hardware discussion and helpful suggestions. Thanksalso to Michele Cianciulli for his comments on the manuscript.We thank the many students who took our Web Course over the years and gaveus a great amount of useful feedback. We especially want to thank one of our rststudents, Conny Carlberg, who encouraged us by quickly applying Java to hisresearch. Several students at the Royal Institute of Technology (KTH) have usedparts of the manuscript of this book, and many of themhave come with interestingand useful comments, especially Bruno Janvier and Jaakko Pajunen. At a veryearly stage, when the Java course was introduced, and when Java was not generallytoo well known, we received encouraging support from many professors at KTH,the University of Stockholm, and the Manne Siegbahn Institute of Physics.One of us (C. S. L.) would like to dedicate this book to his wife Kerima whoprovided great support and encouragement.Oneofus(J.S.T.)wouldliketothankhiswifeJaneyandchildrenKevinand Chelsea for their enduring patience with a too-often absent or preoccupiedhusband and father during many months on a project that grew to be longer andmore difcult than anyone expected. Thank you.One of us (Th. L.) makes a dedication to whoever said do not write any morebooks, it is a much bigger undertaking than you recall from writing the previousone.xixPart IIntroduction to JavaChapter 1Introduction1.1 What is Java?The term Java refers to more than just a computer language like C or Pascal. Javaencompasses several distinct components:rA high-level language Java is an object-oriented language whose source code at aglance looks very similar to C and C++ but is unique in many ways.rJava bytecode A compiler transforms the Java language source code to les of binaryinstructions and data called bytecode that run in the Java Virtual Machine.rJava Virtual Machine (JVM) AJVM program takes bytecode as input and interpretstheinstructionsjustasifitwereaphysicalprocessorexecutingmachinecode.(Wediscuss actual hardware implementations of the Java interpreter in Chapter 24.)Sun Microsystems owns the Java trademark (see the next section on the historyof Java) and provides a set of programming tools and class libraries in bundlescalled Java Software Development Kits (SDKs). The tools include javac, whichcompiles Java source code into bytecode, and java, the executable program thatcreatesaJVMthatexecutesthebytecode. SunprovidesSDKsforWindows,Linux, and Solaris. Other vendors provide SDKs for their own platforms (IBMAIX and Apple Mac OS X, for example). Sun also provides a runtime bundlewith just the JVM and a few tools for users who want to run Java programs ontheirmachinesbuthavenointentionofcreatingJavaprograms.Thisruntimebundle is called the Java Runtime Environment (JRE).In hope of making Java a widely used standard, Sun placed minimal restric-tions on Java and gave substantial control of the development of the languageovertoabroadlybasedJavacommunityorganization(seeSection1.4Java:openorclosed?).SoaslongasotherimplementationsobeytheofcialJavaspecications,anyoralloftheJavacomponentscanbereplacedbynon-Suncomponents. For example, just as compilers for different languages can createmachine code for the same processor, there are programs for compiling sourcecode written in other languages, such as Pascal and C, into Java bytecode. Thereare even Java bytecode assembler programs. Many JVMs have been written byindependent sources.34 IntroductionJavamight besaidmoreaccuratelytorefertoaset ofprogrammingandcomputingspecications. However, inthisbookandtheWebCourse, unlessotherwise indicated, we follow the common use of the term Java to refer to thehigh-level language that follows the ofcial specications and the virtual machineplatform on which the compiled language runs. The usage is normally clear fromthe context.Finally, many people know Java only from the applets that run in their webbrowsers. Java programs, however, can also run as standalone programs just likeany other language. Such standalone programs are referred to as applicationsto distinguish them from applets.1.2 History of JavaDuring1990,JamesGosling,BillJoyandothersatSunMicrosystemsbegandeveloping a language called Oak. They primarily intended it as a language formicroprocessorsembeddedinconsumerdevicessuchascableset-topboxes,VCRs, andhandheldcomputers (nowknownas personal dataassistants orPDAs).To serve these goals, Oak needed the following features:rplatform independence, since it must run on devices from multiple manufacturersrextreme reliability (cant expect consumers to reboot their VCRs!)rcompactness, since embedded processors typically have limited memoryTheyalsowantedanext-generationlanguagethat built onthestrengthsandavoided the weaknesses of earlier languages. Such features would help the newlanguage provide more rapid software development and faster debugging.By 1993 the interactive TVand PDAmarkets had failed to take off, but internetandwebactivitybeganitsupwardzoom.SoSunshiftedthetargetmarkettointernet applications and changed the name of the project to Java.The portability of Java made it ideal for the Web, and in 1995 Suns HotJavabrowser appeared. Written in Java in only a fewmonths, it illustrated the power ofapplets programs that run within a browser and the ability of Java to accelerateprogram development.Riding atop the tidal wave of interest and publicity in the Internet, Java quicklygained widespread recognition (some would say hype), and expectations grewforit to become the dominant software for browsers and perhaps even for desktopprograms. However, the early versions of Java did not possess the breadth anddepth of capabilities needed for desktop applications. For example, the graphicsinJava1.0appearedcrudeandclumsycomparedwiththegraphicsfeaturesavailable in software written in C and other languages and targeted at a singleoperating system.1.3Versions of Java 5Applets did in fact become popular and remain a common component of webpage design. However, they do not dominate interactive or multimedia displaysin the browser as expected. Many other plug-in programs also run within thebrowser environment.ThoughJavas capabilities grewenormouslywiththe release of severalexpanded versions (see Section 1.3), Java has not yet found wide success in desk-topclientapplications. InsteadJavagainedwidespreadacceptanceatthetwoopposite ends of the platform spectrum: large business systems and very smallsystems.Javaisusedextensivelyinbusinesstodevelopenterprise, ormiddleware,applications such as on-line stores, transactions processing, dynamic web pagegeneration, and database interactions. Java has also returned to its Oak roots andbecome very common on small platforms such as smart cards, cell phones, andPDAs. For example, as of mid-2004 there are over 350 different Java-enabledmobilephonehandsetsavailableacrosstheworld, andover600millionJavaCards have been distributed1.3 Versions of JavaSince its introduction, Sun has released new versions of the Java core languagewith signicant enhancements about every two years or so. Until recently, Sundenoted the versions with a 1.x number, where x reached up to 4. (Less drasticreleaseswithbugxeswereindicatedwithathirdnumberasin1.4.2.)Thenextversion, however, willbecalledJava5.0. Furthermore, Sunhassplititsdevelopmentkitsintoso-callededitions, eachaimedtowardsaplatformwithdifferent capabilities. Here we try to clarify all of this.1.3.1 Standard EditionBelow is a time line for the different versions of the Standard Edition (SE) ofJava, which offers the core language libraries (called packages in Java) and isaimed at desktop platforms. We include a sampling of the new features that camewith each release.r1995 Version 1.0. The Java Development Kit (JDK) included:r8 packages with 212 classes.rNetscape 2.04.0 included Java 1.0.rMicrosoft and other companies licensed Java.r1997 Version 1.1:r23 packages, 504 classes.rImprovements included better event handling, inner classes, improved VM.6 IntroductionrMicrosoft developed its own 1.1-compatible Java Virtual Machine for the InternetExplorer.rMany browsers in use are still compatible only with 1.1.rSwing packages with greatly improved graphics became available during this timebut were not included with the core language.r1999 Version 1.2. Sun began referring to the 1.2 and above versions as the Java 2Platform. The Software Development Kit (SDK) included:r59 packages, 1520 classes.rJavaFoundationClasses(JFC), basedonSwing, forimprovedgraphicsanduserinterfaces, now included with the core language.rCollections Framework API included support for various lists, sets, and hash maps.r2000 Version 1.3:r76 packages, 1842 classes.rPerformance enhancements including the Hotspot virtual machine.r2002 Version 1.4:r135 packages, 2991 classes.rImproved IO, XML support, etc.r2004 Version 5.0 (previously known as 1.5). This version was available only in betarelease as this book went to press. See Section 1.9 for an overview of what is one ofthe most extensive updates of Java since version 1.0. It includes a number of tools andadditions to the language to enhance program development, such as:rfaster startup and smaller memory footprintrmetadatarformatted outputrgenericsrimproved multithreading featuresr165 packages, over 3000 classesDuring the early years, versions for Windows platforms and Solaris (Suns versionof Unix) typically became available before Linux and the Apple Macintosh. Overthe last few years, Sun has fully supported Linux and has released Linux, Solaris,and Windows versions of Java simultaneously. Apple Computer releases its ownversionfortheMacOSXoperatingsystem,typicallyafewmonthsaftertheofcial Sun release of a new version. In addition, in the year 1999, Sun split offtwo separate editions of Java 2 software under the general categories of Microand Enterprise editions, which we discuss next.1.3.2 Other editionsEmbedded processor systems, such as cell phones and PDAs, typically offer verylimitedresourcesascomparedtodesktopPCs. ThismeanssmallamountsofRAM and very little disk space or non-volatile memory. It also usually means1.3Versions of Java 7small, low-resolution displays, if any at all. So Sun offers slimmed-down versionsof Java for such applications. Until recently this involved three separate bundlesof Java 1.1-based packages, organized according to the size of the platform. JavaCard is intended for extremely limited Java for systems with only 16 KB non-volatile memory and 512 bytes volatile. The EmbeddedJava and PersonalJavabundlesareintendedforsystemswithmemoryresourcesinthe512KBand2 MB ranges, respectively.Toprovideamoreuniedstructuretoprogrammingfor small platforms,Sun has replaced EmbeddedJava and PersonalJava (but not JavaCard) with theJava 2 Micro Edition (J2ME). The developer chooses from different subsets ofthe packages to suit the capacity of a given system. (We briey review J2ME inChapter 24.)At the other extreme are high-end platforms, often involving multiple proces-sors, that carry out large-scale computing tasks such as online stores, interactionswithmassivedatabases,etc.WiththeJava2PlatformcameaseparatesetoflibrariescalledtheJava2EnterpriseEdition(J2EE)withenhancedresourcestargeted at these types of applications. Built around the same core as StandardEdition packages, it provides an additional array of tools for building these so-called middleware products.1.3.3 Naming conventionsWe note that the naming and version numbering scheme in Java can be ratherconfusing. As we see from the time line above, the original Java release includedthe Java Development Kit (JDK) and was referred to as either Java 1.0 or JDK1.0. Then came JDK 1.1 with a number of signicant changes. The name Java 2rst appeared with what would have been JDK 1.2. At that time the JDK monikerwas dropped in favor of SDK (for Software Development Kit). Thus the ofcialnameoftherstJava2developmentkitwassomethinglikeJava2PlatformStandard Edition (J2SE) SDK Version 1.2. Versions 1.3 and 1.4 continued thesame naming/numbering scheme.MeanwhilemanypeoplecontinuetousetheJDKterminologythusJDK1.4whenreferringtoJ2SESDKVersion1.4. Anothercommonusageisthesimpler but less specic Java Version 1.x, or even just Java 1.x to mean J2SEVersion 1.x. Both of these usages are imprecise because there is also a Java 2EnterpriseEdition(J2EE)Version1.4. Tomakeitclearwhatyoumean, youshould probably either use J2SE or J2EE rather than just Java when mentioningaversionnumberunlessthemeaningisclearfromcontext. Thisbookisnotabout J2EE, though we do touch on Java Servlet technology in Chapters 14 and21 and on web services in general in Chapter 21. Since we never need to refertotheEnterpriseEdition, weusethetermsJava1.x, SDK1.x, andJ2SE1.xinterchangeably.8 IntroductionBythetimethisbookisinyourhands, SunwillhavereleasedtheJava2Standard Edition Version 5.0. The version number 5.0 replaces what would havebeenversionnumber1.5. Undoubtedlymanypeoplewillcontinuetousethe1.5 terminology. In fact, the Beta 2 release of J2SE 5.0 (the latest available atthe time of this writing) continues to use the value 1.5 in some places. You mayalso come across the code name Tiger for the 5.0 release; however, we expectthat usage to fade away just like previous code names Kestrel and Merlin have allbut disappeared from the scene. This book uses the notation J2SE 5.0 or Release5.0 or Version 5.0 or Java 5.0 or sometimes just 5.0 when referring to this verysignicant new release of Java.We provide a brief overview of Java 5.0 in Section 1.9 and examine a numberof 5.0 topics in some detail throughout the book.1.4 Java open or closed?Java is not a true open language but not quite a proprietary one either. All thecorelanguagecomponentscompiler, virtual machines, corelanguageclasspackages, and many other tools are free from Sun. Furthermore, Sun makesdetailed specications and source code openly available for the core language.Another company can legally create a so-called clean roomcompiler and/or a JavaVirtual Machine as long as it follows the detailed publicly available specicationsand agrees to the trademark and licensing terms. Microsoft, for example, createdits own version 1.1 JVM for the Internet Explorer browser. See the Web Coursefor a listing of other independent Java compilers and virtual machines.Sun, other companies, and independent programmers participate in the JavaCommunity Process (JCP) organization whose charter is to develop and reviseJava technology specications, reference implementations, and technology com-patibility kits. Proposals for newAPIs, classes, and other changes to the languagenow follow a formal process in the JCP to achieve acceptance.Sun, however, does assert nal say on the specications and maintains variousrestrictions and trademarks (such as the Java name). For example, MicrosoftsJVM differed in some signicant details from the specications and Sun led alawsuit (later settled out of court) that claimed Microsoft attempted to weakenJavas Write Once, Run Anywhere capabilities.1.5 Java features and benetsBefore we examine how Java can benet technical applications, we look at thefeatures that make Java a powerful and popular general programming language.These features include:rCompiler/interpreter combinationrCode is compiled to bytecode, which is interpreted by a Java Virtual Machine (JVM).1.5Java features and benets 9rThis provides portability to any base operating system platform for which a virtualmachine has been written.rThe two-step procedure of compilation and interpretation allows for extensive codechecking and improved security.rObject-orientedrObject-oriented programming (OOP) throughout no coding outside of class deni-tions.rThe bytecode retains an object structure.rAn extensive class library available in the core language packages.rAutomatic memory managementrA garbage collector in the JVM takes care of allocating and reclaiming memory.rSeveral drawbacks of C and C++eliminatedrNo accessible memory pointers.rNo preprocessor.rArray limits automatically checked.rRobustrExceptionhandlingbuilt-in, strongtypechecking(that is, all variablesmust beassigned an explicit data type), local variables must be initialized.rPlatform independencerThe bytecode runs on any platform with a compatible JVM.rThe Write Once Run Anywhere ideal has not been achieved (tuning for differentplatforms usually required), but is closer than with other languages.rSecurityrThe elimination of direct memory pointers and automatic array limit checking pre-vents rogue programs from reaching into sections of memory where they shouldnt.rUntrusted programs are restricted to run inside the virtual machine sandbox. Accessto the platform can be strictly controlled by a Security Manager.rCode is checked for pathologies by a class loader and a bytecode verier.rCore language includes many security related tools, classes, etc.rDynamic bindingrClasses, methods, and variables are linked at runtime.rGood performancerInterpretation of bytecodes slowed performance in early versions, but advanced vir-tual machines with adaptive and just-in-time compilation and other techniques nowtypically provide performance up to 50% to 100% the speed of C++ programs.rThreadingrLightweight processes, called threads, can easily be spun off to perform multipro-cessing.rBuilt-in networkingrJava was designed with networking in mind. The core language packages come withmany classes to program Internet communications.rTheEnterpriseEditionprovidesanextensivesetoftoolsforbuildingmiddlewaresystems for advanced network applications.10 IntroductionThese features provide a number of benets compared to program developmentin other languages. For example, C/C++ programs are beset by bugs resultingfrom direct memory pointers, which are eliminated in Java. Similarly, the arraylimit checking prevents another common source of bugs. The garbage collectorrelieves the programmer of the big job of memory management. Its often saidthatthesefeaturesleadtoasignicantspeedupinprogramdevelopmentanddebugging compared to working with C/C++.1.5.1 Java features and benets for technical programmingThe above features benet all types of programming. For science and engineeringspecically, Java provides a number of advantages:rPlatformindependence Engineers and scientists, particularly experimentalists, prob-ably use more types of computers and operating systems that any other group. Codethat can run on different machines without rewrites and recompilation saves time andeffort.rObject-oriented Besides the usual benets from OOP, scientic programming canoftenbenet fromthinkingintermsofobjects. Forexample, atomicparticlesinascattering simulation are naturally self-contained objects.rThreading Multiprocessing is very useful for many scientic tasks such as simulationsof phenomena where many processes occur simultaneously. This can be quite useful inthe conceptual design of a programeven when it will run on a single-processor machine.However, Java Virtual Machines on multiprocessor platforms also can distribute threadsto the different processors to obtain true parallel performance.rSimulation tools The extensive graphics resources and multithreading in the core Javalanguage provide for depicting and animating engineering and scientic devices andphenomena.rNetworking Java comes with many networking capabilities that allow one to builddistributed systems. Such capabilities can be applied, for example, to data collectionfrom remote sensors.rInterfacing and enhancing legacy code Javas strong graphics and networking capa-bilities can be applied to existing Cand Fortran programs. AJava graphical user interface(GUI) can bring enhanced ease of use to a Fortran or C program, which then acts as acomputational engine behind the GUI.1.5.2 Java shortcomings for technical programmingSeveral featuresofJavathat makeit apowerful andhighlysecurelanguage,suchasarraylimitcheckingandtheabsenceofdirectmemorypointers, canalso slow it down, especially for large-scale intensive mathematical calculations.Furthermore, the interpretation of bytecode that makes Java programs so easilyportablecancauseabigreductioninperformanceascomparedtorunninga1.5Java features and benets 11program in local machine code. This was a particular problem in the early daysofJava, anditsslowperformanceledmanywhoexperimentedwithJavatodrop it.Fortunately, moresophisticatedJVMshavegreatlyimprovedJavaperfor-mance. So called Just-in-Time compilers, for example, convert bytecode to localmachinecodeonthey.Thisisespeciallyeffectiveforrepetitivesectionsofcode. Duringtherst passthroughaloopthecodeisinterpretedandcon-verted to native code so that in subsequent passes the code will run at full nativespeeds.Another approach involves adaptive interpretation, such as in Suns Hotspot,in which the JVM dynamically determines where performance in a program isslow and then optimizes that section in local machine code. Such an approachcan actually lead to faster performance than C/C++ programs in some cases.Here are some other problems in applying Java to technical programming:rNo rectangular arrays Java 2D arrays are actually 1D arrays of references to other1D arrays. For example, a 4 4 sized 2D array in Java behaves internally like a single1D array whose elements point to four other 1D arrays:A[0] ==> B[0] B[1] B[2] B[3] B[4]A[1] ==> C[0] C[1] C[2] C[3] C[4]A[2] ==> D[0] D[1] D[2] D[3] D[4]A[3] ==> E[0] E[1] E[2] E[3] E[4]The B, C, D, and E arrays could be in widely separated locations in memory. This differsfromFortranorCinwhich2Darrayelementsarecontiguousinmemoryasinthis4 4 array:A(0,0) A(0,1) A(0,2) A(0,3) A(0,4)A(1,0) A(1,1) A(1,2) A(1,3) A(1,4)A(2,0) A(2,1) A(2,2) A(2,3) A(2,4)A(3,0) A(3,1) A(3,2) A(3,3) A(3,4)Therefore, with theJava arrays,moving fromone elementto the nextrequires extramemory operations as compared to simply incrementing a pointer as in C/C++. Thisslows the processing when the calculations require multiple operations on large arrays.rNo complex primitive type Numerical and scientic calculations often require imag-inary numbers but Java does not include a complex primitive data type (we discuss theprimitive data types in Chapter 2). You can easily create a complex number class, butthe processing is slower than if a primitive type had been available.rNo operator overloading For coding of mathematical equations and algorithms itwould be very convenient to have the option of redening (or overloading) the deni-tion of operators such as + and -. In C++, for example, the addition of two complexnumber objects could use c1 + c2, where you dene the + operator to properly addsuch objects. In Java, you must use method invocations instead. This lengthens the code12 Introductionsignicantly for nontrivial equations and also makes it more susceptible to bugs. (TheString class in Java does provide a + operator for appending two strings.)rFloating-point limitations The early versions of Java provided only 32- and 64-bitoating-point regardless of whether the host machine provided for greater precision.ThisinsuredthatforthesameprogramtheJVMsproducedexactlythesameresultonall machines. However, inJava1.2it becamepossibletouseawiderexponent(but not signicand) representation if available on the platform. The keyword modierstrictfp forces the oating-point calculations to follow the previous lower precisionmodetoensureexactlythesameresultsonallmachines. Wediscussoating-pointrepresentations and operations in Chapter 2.So for some types of intensive mathematical processing, such as those using verylarge arrays, it may be difcult to achieve the performance levels of C or Fortran,especially when that code has been optimized over many years of use. In suchcases, it may be advantageous to let Java provide a graphical user interface andnetworking tools, but keep the C/Fortran program as a calculation engine insidethe Java body. Chapter 22 discusses how to link Java with native code.1.6 Real-world Java applications in scienceand engineeringJava has been used extensively for several years nowto solve real-world program-ming challenges in numerous areas of endeavor. While applications in scienceand engineering may be less well known, there certainly are many and we presenta few examples here.A Java-based system called Maestro provided for data visualization, collabo-ration, and command and control services for the NASA JPL team in charge ofthe Mars rovers that landed on the Red Planet in January 2004. James Goslingcalled it the the coolest Java app ever [1]. The system provides an elaborate setof tools for analyzing images, 3Dmodeling of the terrain around a rover, and col-laborative planning for rover maneuvers and experimental operations. Figure 1.1shows a display of a special version of Maestro made available to the public forpersonal use. You can use it to create your own driving and science activities,using all of the rovers instruments to enact your own day of mission operations.Large sets of actual data and imagery can be downloaded for different periods ofthe mission [2].One of us is part of team working on a project known as SensorNet that isusing Java-based web services to enable the collection and archiving of data fromsensors that are distributed nationwide [3]. Web services involve the exchangeofdatainXML(ExtensibleMarkupLanguage)format viawebclient/serversystems.(WegiveanintroductiontoWebservicesinChapter21.)SensorNetuses web services and open standards so that sensor information is available to awide variety of users in a standard format. Java was chosen as the implementation1.6Real-world Java applications in science and engineering 13Figure 1.1 The Maestro program, written in Java, allows NASA operators of theMars rovers to analyze images, create stereo views and 3D terrain models, and planmaneuvers and experiments. The gure shows a screen capture of the publicversion of the program.languagebecauseof theportabilityandother featuresmentionedabovethatmake it an excellent software platform in general and for network programminginparticular. Furthermore, SunprovidesafreeJavaWebServicesDeveloperPack (JWSDP) that includes extensive tools and documentation for creating suchservices.TheAviationDigital DataService(ADDS), createdbyaconsortiumthatincludes the National Oceanic and Atmospheric Administration (NOAA), offersseveral Java tools to provide graphical displays of an assortment of meteorologicaldata of importance to the aviation community [4]. Another aviation-related Javaprogram is AirportMonitorTM. This commercial product is used by a number ofairports to provide near-live displays of air trafc arriving and departing fromtheir facilities. The data also includes ight ID, aircraft type, altitude, origin, anddestination [5].14 IntroductionFigure 1.2 The steps to create and run a Java standalone application program.The Swedish Institute of Space Physics uses a Java program to collect andviewdatafrominfrasound(acousticwavesinthe0.125Hzrange)detectorsdistributed in the north of the country. The infrasound system can detect distantevents such as Shuttle launches and meteors [6].The opensource programBioJava, developedat the Sanger Institute inGreat Britain, provides researchers in the eld of bioinformatics with an exten-sive toolkit for manipulating genomic sequences [7]. The large program (over1200classes andinterfaces) is nowusedat major laboratories aroundtheworld [8].The Web Course provides a resource section with links to sites that describemany other applications of Java in science and engineering. There are also linksto Java programming tools in numerical computing, data analysis, image process-ing, and other areas. In addition, we link to a small sample of the thousands ofapplets available on the Web that use Java graphics and animation techniques todemonstrate scientic principles and complex systems. Such simulations providepowerful tools for teaching technical subjects.1.7 The Java programming procedureFigure1.2illustratesthebasicstepstocreateandrunaJavaapplication, asstandalone Java programs are called. You rst create the source code with a texteditor and save it to a le with a .javale extension appended to the name.HeretheleHelloWorldApp.javaiscreated.Thelenamemustexactlymatch the class name in both spelling and case. (We dene class in Chapter 3.)1.7The Java programming procedure 15With the javac program, you compile this le to create a bytecode le (orles if the source code le included more than one class). The bytecode le endswith the .classextension appended. Here the output is HelloWorldApp.class. The bytecode consists of the instructions for the Java Virtual Machine(JVM).With the java program you run your class le. The JVM interprets the byte-codeinstructionsjustasifitwereaprocessorexecutingnativemachinecodeinstructions. (In Chapter 24 we discuss hardware processors that directly executeJava bytecode.)The platform independence of Java thus depends on the prior creation of aJVM for different platforms. The Java bytecode can then run on any platform onwhich a JVM is available and should perform the same regardless of platformdifferences. This Write Once, Run Anywhere ideal is a key goal of the Javalanguage. For applets the browser runs a JVM in the same manner that it runsother plug-in programs.1.7.1 Java toolsProgramming in Java typically involves two alternative approaches that we willcall manual and graphical:rManual Use your favorite text editor to create the java source code les (*.java)and use the command line tools in the Software Development Kit (SDK) to compileand run the programs. The SDK is provided by Sun and includes several tools, the mostimportant of which are:rjavac compiles Java language source les to bytecode lesrjava the JVM that executes java applicationsrappletviewer tests applets independently of a web browser.rGraphical Graphical user interface programming environments (or GUI builders) areelaborate programs that allowyou to edit Java programs and interactively build graphicalinterfaces in a WYSIWYG (What You See Is What You Get) manner. They also includea compiler and a JVM so that you can both create and run Java applets and applica-tionsallwithinoneenvironment. ThesearealsoknownasIntegratedDevelopmentEnvironments, or IDEs.During this course we recommend the manual approach so that you will learnrst hand the essential details of Java graphics programming. While it is ne touse the editor in the GUI builder or IDE, you should write all of the code yourselfrather than use the interactive user interface building tools. Otherwise, the GUIbuilder does most of the work and you learn very little.When you later begin developing programs for your own tasks that requiregraphical interfaces with many components, you may want to use a GUI builder.However, even then you will occasionally want to modify the graphics code by16 Introductionhand to debug a problem or tweak the appearance of a layout. You then obviouslyneed to understand the details of graphics programming.For editing the source code, we recommend a language sensitive editor thatcolor codes the Java text so that the language keywords and symbols are high-lighted. This helps to avoid simple spelling mistakes and assists with debugging.Chapter 1 in the Web Course provides links to several freeware and commercialeditors.TheappletviewerprogramthatcomeswiththeSDKprovidesanidealtool for applet debugging. As we discuss later, browsers do not provide a goodenvironment inwhichtodebugapplet code except near the endof the developmentprocess.1.7.2 DocumentationThe Java language elements available fromSun currently fall into these two broadcategories:rCore language This refers to the set of packages and classes that must be availablein the JVM for a particular edition (see Section 1.3) regardless of the platform.rOptional APIs A number of useful Application Programming Interfaces (APIs) areavailablefromSunforaudioandvideoapplications,3Dgraphics,andseveralotherareas. However, they are not part of the core language so may not be available for allplatforms.These elements nowinvolve an enormous number of packages, classes and meth-ods. So access to documentation is essential. Sun provides a large set of docu-mentation freely available on its site at http://java.sun.com.Ifyoudonot havecontinual onlinewebaccess, werecommendthat youdownload fromthe http://java.sun.com site a copy of the Java 2 Platform,Standard Edition API specications for the latest version of Java. This set of webpages provides detailed descriptions of all the packages, classes, and methodsin the core language. You will frequently refer to this documentation to nd outwhat exactly a given method does, what methods are available for a given class,and to obtain other useful information.Notethat theonlinedocumentationindicateswhat versionofJavaaclassor method appeared in the core language (where this is not explicit, assume itcame with Version 1.0). This is important if you want to write a program that isconsistent with, for example, version 1.1.1.7.3 Code compatibilityIn this course we primarily use code consistent with version 1.4 or higher. Wenote those places where we do not. Currently (circa 2004) many browsers in usestill only run applets with Java 1.1 compatibility. For such browsers, Sun provides1.8Getting started 17a Java plug-in that implements Java 2 features. Applet tags in the web page caninitiate the downloading of the plug-in, but the plug-in le is large and users onslow dial-up lines may refuse the download.If your goal is to write applets for the broadest audience, then you need towrite code limited to version 1.1 classes and methods. The Supplements sectionsin the Web Course provide alternative instruction in the 1.1 graphics techniques.So far, Java maintains strict backwards compatibility. The bytecode from aJava1.0compilerstillrunsinaJava1.4virtualmachine.AprogramwrittenaccordingtotheJava1.0specicationstill compilesinaJava1.4compiler,though the compiler will ag deprecated elements that are no longer consideredrecommended practice.Note, however, that you can in some cases run into problems if you mix codefrom different versions within the same program. For example, the handling ofevents, such as mouse clicks, changed signicantly from version 1.0 to 1.1. Aprogram can use either event-handling approach but it cannot contain both.1.8 Getting startedYou can quickly begin creating simple Java applets for the browser and applica-tions for the console by following the code in the examples given here. Initiallyyou do not need to understand all the elements of the language. We discuss themeaning of terms such as class and extends in the following chapters. Fornow it is important just to get the basic programming tools installed and learnhow to run them. The details will come later.1.8.1 Setup for Java programmingTo begin developing Java programs, follow these steps:1. Obtain the Java 2 Software Development Kit (SDK) for your platform:rThe SDK is available free from Sun Microsystems for Solaris, Linux, and Windowsplatforms. See the Resources page in the Web Course for links to sites that providekits for alternate platforms as well as kits from non-Sun sources.rThe SDK contains the essentials needed to create Java programs.rThe SDK includes:rJava executables such as javac (compiler) and java (the JVM)rClass packages, which correspond to code libraries.2. Install the SDK:rThe Sun SDKs now come with an installer application that does most of the workfor you. Just run this program and follow its instructions.3. Install the documentation:rIt is recommended that you have ready access to the Java 2 API Specication since itwill be very useful during programdevelopment. If you use the Sun SDK, you should18 Introductiondownload the current documentation set and install it following the directions avail-able at http://java.sun.com. If you use a third-party SDK, the documentationshould be available from the same source as the SDK itself.Thefollowingtwosectionsgiveanexampleofasimpleappletandasimpleapplication program. These illustrate the basics for creating such programs andprovide some initial experience with the SDK programming tools. The generalworkings of the code should be readily apparent so we wait until later chaptersto discuss the exact meaning and function of the various language keywords andstructures.1.8.2 First applicationStandalone programs in Java are referred to as applications. As mentioned pre-viously, Figure 1.2 shows the steps needed to create and run an application. Thecode for the standard Hello World application that prints a string to the consoleis shown here:public class HelloWorldApp{public static void main (String[] args){System.out.println ("Hello World!");}}Put this code into a le called HelloWorldApp.java. (A Java le name mustmatchexactlytheclassname, includingthecapitalization;thisistrueforallplatforms.) Compile the application as follows:> javac HelloWorldApp.javaThis creates the class le HelloWorldApp.class. Use the java commandto run the program:> java HelloWorldAppThis produces the outputHello World!in the console window.1.8Getting started 19Figure 1.3 The steps to create a Java applet and a web page to hold it. Loading theweb page in a browser or running it with the appletviewer program will display theapplet as shown in Figure 1.4.1.8.3 First appletFigure 1.3 shows the steps to create an applet. The following applet code displaysthe string Hello World! in a window on a browser page:public class HelloWorld extends java.applet.Applet{public void paint (java.awt.Graphics g){g.drawString ("Hello World!", 45, 30);}}PutthiscodeintoalecalledHelloWorld.java.(Again,thenameofthele, including the cases of the letters, must match exactly with the class name20 IntroductionHello World!Figure 1.4 Display of a very basic applet.HelloWorld.) Then compile the code with> javac HelloWorld.javaThis creates the class le HelloWorld.class.Applets are intended for display in browsers so you need to create a Web pagelewiththepropertagsthatindicatewherethebrowsershouldndtheclasscode and how big a window it should provide to display the applets graphicaloutput. (A brief tutorial on HTML coding for Web pages is available in the WebCourse Chapter 1: Supplements section.)Put the following code into a le called HelloWorld.html:

A Simple Applet

Withthis tagthelemust resideinthesamedirectoryas theHelloWorld.class le. Open the le HelloWorld.html in your browserand you should see something like that in Figure 1.4.1.8.4 Starter programsWe provide with the Web Course the codes for a number of programs that act astemplates into which you insert code to make them do something useful. Sincethe term template implies something else in object-oriented programming, wecall these starter programs. You can use themto begin a programwithout startingfrom scratch every time.A very simple application program, StartApp1.java, is shown here. Youcan insert code snippets, such as those to be discussed in Chapter 2, into the areaindicated.1.8Getting started 21public class StartApp1{public static void main (String[] args){// Put code between this lineInsert the example codes or your exercise codebetween these lines.// and this line.}}Follow the instructions above for compiling and running an application. Renametheclass for eachnewprogram. For example, intheabovestarter replaceStartApp1 with MyClassApp1 or just MyClass. (We indicate at the top ofeach demonstration program le on the Web Course the starter program that webegan with for that demo.) Remember that in the Java scheme the le name andthe class name must match exactly in both characters and case. Also, the namecannot begin with a number or punctuation character (. or ?, etc.).We also provide a starter for applets as shown below with StartApplet1.java. Applets are intended to present a graphics display of some sort in a browserwindow. However, at this early stage we do not discuss Java graphics so that wecan focus initially on the basics of the language. (We begin discussing graphics inChapter 6.) Other than painting a short message to the applet display window,wesendoutputviaprintstatementstothebrowsersJavaconsoleratherthanpaint text to the browser window. (A browsers Java console can be activated viathe browsers preferences or options settings.) This applet includes an init()method, which is called by the browser when the applet rst begins. The init()is a convenient place to put simple example code with print output.public class StartApplet1 extendsjava.applet.Applet{public void init (){// Put code between this line// and this line.}We learn later how appletsinherit the Java applet class.The browser always invokesthis initialization methodwhen the applet begins runningInsert example codes or yourexercise code between theselines.22 Introduction// Paint a message in the applet window.public void paint (java.awt.Graphics g){g.drawString ("Test", 20, 20);}}This line is a commentThis paints the string "Test"in the applet window.After inserting code into your applet, follow the same procedure as we discussedabove for the HelloWorld applet: compile the program, create a web page withthe appropriate applet tags, and place the web page and class le into the samedirectory.You can test the applet by loading the web page into a browser or you can usetheappletviewer program that comes with the SDK tools. If, for example,you put your applet into a web page named MyFirstApplet.html, you runappletviewer on it from the command line as follows:> appletviewer MyFirstApplet.htmlIt is usually more convenient to use the appletviewerduring debugging andtuning of your applets. Then once they work satisfactorily with appletviewer,you can examine how they appear in the browser. With the older JVMs that cameinstalled in the browsers, it could be difcult to force the browser to load a newclass le rather than use the old one in the cache. With Suns Java Plug-in, whichshould have been installed into your browsers when you installed the SDK andisalsoavailablefordownloadingfromwww.java.com,theconsolewindowallows for various commands to the JVM including the x command that clearsthe cache.We note here that we focus on applications in much of the course and evenshow later how you can add amain() method to an applet so that it can alsorun as an application. An applet has the inconvenient requirement that you needan HTML le containing the applet tags if you want to test it in a browser orappletviewer. We like applets, however, since they are pedagogically veryuseful for the Web Course. You can immediately see the applet running in a webpage and can compare its output to the source code, which is displayed for everyapplet. You can download the code, make modications, and test it. To avoid theneed to make a web page to test the applet, we use the trick of putting the tagswithin a comment block in all of our applet source code les as shown here forthe HelloWorld example:/* */public class HelloWorld {. . .1.9Changes in Java 2 Standard Edition 5.0 23The appletviewerprogramdoesnt require that a le be a legitimate HTMLle, only that it contains the applet tags. You can then run the applet with> appletviewer HelloWorld.javaToreducespace, wedontshowtheapplettagssectionintheappletcodelistingsinthebookbut it appearsinall thedownloadablecodeat theWebCourse.1.9 Changes in Java 2 Standard Edition 5.0We mentioned in Section 1.3 that Sun is introducing a newversion of the languagecalled Java 5.0. Most of the changes fall into the ease of development category.With a few important exceptions, the changes do not add new functionality butrather provide an easier way of doing the same things you could do before butwith less code and better compiler-time error detection. We provide here a briefrundown of the most important changes to the platform.1.9.1 Major themes in 5.0 DevelopmentRelease 5.0 revolves around ve major themes:rQuality, stability, and compatibility The designers of J2SE 5.0 considered quality,stability, andcompatibilitytobe the most important aspect of the newrelease. Release 5.0is the most tested release ever. Great efforts were made to ensure compatibility withprevious versions of Java. The Sun engineers have made a public plea for users world-wide to test their code with the 5.0 Beta releases and report any problems that appear,especially any code that works with earlier versions of Java but fails under 5.0.rPerformance and scalability Faster JVM startup time and smaller memory footprintwere important goals. These have been achieved through careful tuning of the softwareanduseofclassdatasharing. (Refertohttp://java.sun.com/j2se/1.5.0/docs/guide/vm/class-data-sharing.html for more information about classdata sharing and why it helps.)rEase of Development Most of us take the rst two themes for granted. We expectquality, stability, and compatibility, and the performance and scalability enhancementsare very nice to have. We applaud the extensive efforts Sun has made in those areas.However, the Ease of Development (EoD) theme and the two that follow are likely tobe the most important changes noticed by developers.ItisintheEoDareathatthemostsignicantchangesappear.Inmostcases,nonew functionality was added in the sense that almost anything you can do with 5.0 youcould do with 1.4, it just sometimes took a lot more boilerplate code (i.e. code that isrepeatedfrequently)todoit.Theexceptiontothisgeneralstatementhastodowiththe new multithreading and concurrency features that provide capabilities previouslyunavailable.24 IntroductionInmanycases, thenewEoDfeaturesareall about syntaxshortcutsthat greatlyreduce the amount of code that must be entered, making coding faster and more error-free. Some features enable improved compile-time type checking, thus producing fewerruntime errors.rMonitoringandmanageabilityThe5.0releaseincludestheabilitytoremotelymonitorandevenmanagearunningJavaapplication. Forexample, itisnowmucheasiertowatchmemoryusageanddetect andrespondtoalow-memorycondition.Manyofthesefeaturesarebuiltrightintothesystem, andyoucanaddadditionalmonitoring and managing features to your own code.rImproveddesktopclient The last great theme of the 5.0 release was an improved expe-rience on the desktop client. In addition to better performance because of a faster startuptime and smaller memory footprint, there is a new, improved Swing (see Chapter 6)look and feel called Ocean, and a new easy-to-customize skinnable look and feel calledSynth in which you can use XML conguration les to specify the appearance of everyvisualcomponentinthesystem.Inaddition,theGTKandXPlookandfeelsintro-duced in J2SE 1.4.2 have received further improvements. There is support for OpenGLand better performance on Unix X11 platforms. The Java Web Start and Java Plug-Intechnologies (both used to run Java applications downloaded over the Web) have beenimproved.OthernewfeaturesinJ2SE5.0includecoreXMLsupport, improvementstoUnicode, improvements to Javas database connectivity package known as JDBC,and an improved, high-compression format for JAR les that can greatly reducedownload times for applets and other networked applications.1.9.2 Major Ease of Development changes in J2SE 5.0We list below the most important of the many EoD improvements in Java 5.0,roughly in the order in which they are encountered in the rest of this book, not inthe order of importance. Most of these enhancements to the language can onlybe appreciated after having had experience with programming in Java. If you arecompletely new to Java, you might want to skip this section and come back to itafter you complete Part I.rAutoboxingandunboxingChapter2explainsthat Javahasprimitivetypeslikeint for integers, and Chapter 3 explains object types like Integer. The differencebetween the two types is very important as we will see. Previous versions of Java madeit necessary to explicitly convert between the primitive types and the object types. InChapter 3 we examine the so-called autoboxing and unboxing feature added with J2SE5.0 that removes the need for explicit conversions in most cases, and thus improves codereadability and removes boilerplate code and sources of errors.rEnhanced for loop Chapter 2 looks at the several types of looping structures in theJava language, one of which is the for loop (quite similar to the C/C++ for loop).Version 5.0 includes an enhanced for loop syntax that reduces code complexity and1.9Changes in Java 2 Standard Edition 5.0 25improves readability. We introduce the enhanced for loop in Chapter 2 and explain itin more detail in Chapter 10 after we have described the object types with which theenhanced for loop works.rMetadata In Chapter 4 we encounter the @Override annotation. It falls under thecategory of metadata or data about data. In this case, it is better thought of as dataabout code. The new metadata facility, also called the annotation facility, is designedto use an annotation in your code that greatly reduces much of the boilerplate codethat would be required in previous versions of Java.An annotation is a new5.0 language element that begins with @. Some annotationsare processed by the javac compiler and some require the new annotation processingtool apt. There are currently only three annotations in the beta release of version 5.0.However, now that the metadata framework is available, we anticipate the appearanceof many useful annotations and annotation processors in the future.rFormatted input and output and varargs In Chapter 5 we discuss how to formatnumerical output with Java. Version 5.0 nally adds the oft-requested ability to produceformatted output easily in the form of a printf() method that behaves very similarlyto the printf() function in the C/C++stdio library. There is also a new formattedinput feature that is described in Chapter 9.Both these features rely on another newfeature known as varargs, which stands forvariable argument list in which the number of parameters passed to a Java method isnot known when the source is constructed. Varargs is a useful new feature that can beof value in your own code, not just in the new printf() feature. Chapter 10 presentsanother EoDenhancement that provides for automatic format and output of the elementsof an array (see the java.util.Arrays class). This feature really has nothing to dowith printf or varargs, but we mention it here because it eases the amount of workthat was necessary in pre-5.0 releases to output all the elements in an array in a nicelyformatted style.rStatic import Release 5.0 includes a new technique for accessing Java static methodsand constants in another class without the need to include the full package and classname every time they are used. (We explain what the terms class, package, static, import,etc., mean in Chapters 35.) This new static import facility makes your code easierto write and, since theres less of it, less error-prone. We discuss static import in moredetail in Chapter 5 after discussing import in general.rNewpack200hyper-compressionJARformatChapter5discussesJAR(JavaArchive) les used to combine and compress Java class les. We also look at the newpack200 format that compresses JARles very tightly, reducing bandwidth and savingdownload time. (This is not really an EoD change, but more of an ease of deploymentchange.)rGraphics system improvements Release 5.0 includes numerous bug xes and minortweaks to Javas graphics subsystems known as AWT and Swing (see Chapters 6 and 7),including reduced memory usage. In the EoD area, perhaps the biggest improvement isthat it is no longer necessary to call getContentPane() when using Swing compo-nents (see Chapter 6 for details). Other enhancements include improved popup menu26 Introductionsupport, improved printing support for some graphics components, and the ability toquery for the mouse location on the desktop.rNew concurrency features Chapter 8 discusses Javas multithreading support, whichhas been present since version 1.0. Release 5.0 adds newcapabilities that greatly enhancethe multithreading features of Java. Some of these additions depend upon the genericsconcept (see next item), so we wait until Chapter 10 to introduce these important newcapabilities.rGenerics In Chapter 10 we introduce the new generics feature, a large and importantsubject that we do not have space to cover in detail in this book. Java is already a verytype-safe language, which simply means that every variable has a specic type and thatonly compatible types can be assigned to each other. However, the use of generics bringsan even greater amount of type safety to the Java language. Java includes a number ofobject containers, such as the ArrayList class, that can contain objects of manydifferent types. Whenretrievinganobject fromoneofthesecontainers, it must beretrieved as a very basic type and then converted back to the original type. If, however,an incorrect type is added to the container, then an error occurs at runtime during theconversion attempt. The use of generics makes it possible for the object containers torequire that only certain types can be placed into them, else a compile time error occurs.Since mistakes are found at compile time, runtime safety and correctness is improved. Inaddition, since the specialized containers only contain items of the desired type, retrievalof items from the containers is easier since no explicit conversion to the desired type isnecessary.YouarenotrequiredtousethegenericsapproachbutseethenoteattheendofSection 10.7 about using the 5.0 compiler with code that uses the older containers.rEnumerated types Chapter 10 presents a feature of C/C++that many programmershave missed in Java. Version 5.0 adds an enumerated type using theenum keyword.ThenewJavaenumeratedtypeincludesallthefeaturesofC/C++enumandmore,including type safety.rNewStringBuilder class We discuss this new class in Chapter 10, along withtheolder StringBufferclass. Bothareusedinthebuilding, concatenating, andappending of string types, but the new class has improved performance.rChanges to ease RMI development Chapter 18 explains the Remote Method Invoca-tion (RMI) techniques, including a simple but important change in J2SE 5.0 that makesRMI development simpler.We do not go into great depth in this book on these changes. To do so wouldrequire an entire book just for those changes. In fact, at least one book devotedentirelytoRelease 5.0is available at the time of this writing[9]. There is alsomuchdocumentationavailableonlineat http://java.sun.com, thoughreadingthat documentation is sometimes difcult. By the time this book is in your hands,there are sure to be more books devoted to Java Version 5.0 that explain all thenew features in more detail than we can provide here. We expect one of thoseReferences 27books to be the consistently good Java in a Nutshell series [10], the 5th editionof which should include coverage of J2SE 5.0.1.10 Web Course materialsThe Web Course Chapter 1: Supplements section covers a number of topics relatedto those mentioned here including the issue of interpretation versus compilation,the design of JVMs like those with Just-In-Time compilation, and options fordeploying your Java programs to users. It provides a list of web links to JVMs andcompilers produced by independent sources. It also provides further informationon J2SE 5.0.Some practical programming topics are also presented such as how to createweb pages with applets. For applets compatible only with version 1.2 or later,the Web Course gives instructions on how to set up the web page so that a Javaplug-in will automatically download if needed.The Web Course Chapter 1: Tech section discusses the benets and shortcom-ings of Java for technical applications. The Web Course Chapter 1: Physics sectionlooks similarly at the benets and shortcomings of Java for physics computationandsimulation.Itgivesexamplesofdifferentkindsofsimulationsofphysicsphenomena. It also emphasizes the benets of learning by coding in which theprocess of converting a physics theory into a simulation will help to deepen yourunderstanding of the phenomena.References[1] James Gosling, Java Technology and the Mission to Mars, Sun News, January 16, 2004,www.sun.com/aboutsun/media/features/mars.html.[2] Maestro and the Mars rover data sets are available athttp://mars.telascience.org.[3] SensorNet Project, www.sensornet.gov.[4] Aviation Digital Data Service, http://adds.aviationweather.gov/java/.[5] AirportMonitorTM, www.passur.com/am-airport.htm.[6] Infrasound viewer, Swedish Institute of Space Physics, Ume a, Sweden,www.umea.irf.se/ilfil/.[7] BioJava, www.biojava.org.[8] Steve Meloan, BioJava Java Technology Powers Toolkit for Deciphering GenomicCodes, Sun Developer Network, June 2004, http://java.sun.com/developer/technicalArticles/javaopensource/biojava/.[9] Brett McLaughlin and David Flanagan, Java 1.5 Tiger, A Developers Notebook,OReilly, 2004.[10] David Flanagan, Java in a Nutshell, 4th edn, OReilly, 2002. (Note: we expect that the5th edition, covering J2SE 5.0, will be published by the time you read this.)28 IntroductionResourcesCalvin Austin, J2SE 1.5 in a Nutshell, May 2004, http://java.sun.com/developer/technicalArticles/releases/j2se15/.Judith Bishop and Nigel Bishop, Java Gently for Scientists and Engineers, Addison-Wesley,2000.Stephen J. Chapman, Java for Engineers and Scientists, Prentice-Hall, 2000.Richard Davies, Java for Scientists and Engineers, Addison-Wesley, 1999.Ronald Mak, Java Number Cruncher: the Java Programmers Guide to NumericalComputing, Prentice-Hall, 2003.Grant Palmer, Technical Java: Applications for Science and Engineering, Prentice-Hall, 2003.Java Community Process Program www.jcp.com.Java resources at IBM Developerworks, www.ibm.com/developerworks/java.Java software development on the Apple Mac, http://developer.apple.com/java/.Java at Sun Microsystems, Inc., http://java.sun.com.Java 2 Standard Edition API Specication,http://java.sun.com/j2se/1.5.0/docs/api/.The Java Tutorial at Sun Microsystems,http://java.sun.com/docs/books/tutorial/.Chapter 2Language basics2.1 IntroductionIf you buy one of those do-it-yourself furniture kits, the best way to start is tojust dump all of those screws, nuts, planks, tools and other odd looking widgetson the oor, group them into piles of similar looking items, and then go read theinstructions. Even if you dont know what all of those widgets are for, it helps topick them up and look them over so that you become familiar with them and canrecognize them in the instructions.Soratherthandribblingthemoutoverseveralchapters,herewedumpoutmostofthebasicwidgetsneededtoconstructJavaprograms. Thegoalistostart to become familiar with Javas symbols, keywords, operators, expressions,and other building blocks of the language with which to construct programs. Weprovide examples and starter programs (on the Web Course) that allow you tobegin to write programs without needing to understand yet all of these languageelements at a deep level. You should refer back to this chapter as you proceedand as your understanding of the language increases.Note that in this chapter we occasionally mention the terms class, method, andobject. If you are new to object-oriented programming, do not worry about theseterms for now. We discuss them in detail in the following chapters.We begin with a listing of the basic elements and then outline the structure ofa generic program. We proceed through the individual elements of the languagebeginning with the Java reserved words, or keywords. We then discuss the basicdatatypesinJavacalledprimitives. Theseareusedinexpressionsandwithvarious operators to create statements.With regard to technical programming, we look at the oating-point represen-tations in Java and the various issues regarding them. We also discuss the mathfunctions available in the core language.2.2 Language elements and structuresLikeanycomputerlanguage,Javaconsistsofasetofbasicelementsthattheprogrammer arranges according to the syntax of the language to build a program.2930 Language basicsCharacters and symbols make up the keywords and the punctuation with which tobuild expressions, statements, and other higher-level structures. We rst brieylist these basic elements and structures here and then examine themin more detailin the rest of the chapter.2.2.1 Basic elementsJava codes consist of the following:rKeywords and symbols The programmer has wide latitude for the names of vari-ables and classes but Java reserves some words for itself. These keywords include, forexample,class, float, return, if, elseSymbols in java include, for example,{}; () //See Table A.1.1 and Table A.1.2 in Appendix 1 for listings of the Java keywords andJava reserved symbols, respectively.rData types Eight keywords name the eight kinds of basic data types in Java:rbyte, short, int, long four integer types, all signedrfloat, double two oating-point typesrboolean logical (true/false)rchar 2-byte Unicode character encoding (can be used for 2-byte unsigned integers)These data types do not use object representations but simply hold a data value in oneto eight bytes of memory. They are referred to as primitives.rOperators Java operators include the arithmetic operators (+,-,/,*,%), Booleanoperators (&&, ||, etc.), comparisons (==, javadoc TestApplet.javawill include this comment in the hypertext description of the class. Several specialcomment tags are also available to describe method parameters, return values, andother items. (Note that asterisks within the comments are ignored by javadocso we often use them to mark the left side of a block of javadoc comments.)See Chapter 6 in the Web Course for more about javadoc.2.5 Data types and Java primitivesHow numbers and other data, such as characters, are represented in memory isof great practical importance. Ideally a single memory representation, or type,could represent all numerical data. However, computer memory and transfer ratesare not innite and designers must strike a compromise among the demands fornumerical values to span the widest possible range of values while conservingmemory and maximizing program performance.Verylargenumbersandfractional numbersrequireaoating-point type.Floating-pointoperationsinvolvetheextracomplexityofdealingwithbothasignicandandanexponent. Therefore, integer datatypesnormallyprovidefasterperformanceforoperationswhereoating-pointisnotrequired.(Someprocessors dont do any oating-point arithmetic at all, only integer arithmetic.)A single universal numerical data type will not be efcient or sufcient for allsituations.Table 2.1 lists the eight primitive data types and shows the features of each.Four integer types provide for efcient use of memory for a given task. The bytetype (8-bit) is often useful for IO tasks while the long type (64-bit) is neededfor representing very large integer values. In between are the 16-bit short andthe 32-bit int types. The int type is the default for most integer operations inJava. The integer types use twos complement signed representations.34 Language basicsTable 2.1 Java primitive data types.Type Values Default Size Rangebyte signed integer 0 8-bit -128 to 127short signed integer 0 16-bit -32768 to 32767int signed integer 0 32-bit -2147483648 to 2147483647long signed integer 0 64-bit -9223372036854775808 to92233720368547