Index

Index................................................................................................................................................1 Chapter 1 : Java Technology........................................................................................................7 1.1 History of Java...................................................................................................................7 1.2 What is Java?.....................................................................................................................8 1.3 Versions of Java.................................................................................................................8 1.4 Code Compatibility..........................................................................................................10 1.5 Java 5.0 Improvements....................................................................................................11 1.6 Features of Java................................................................................................................12 1.7 Java Applets and Applications.........................................................................................14 1.8 Why Java is important to Internet?..................................................................................14 1.9 The Java Platform............................................................................................................15 1.10 What Can Java Technology Do? ...................................................................................16 1.11 Writing a Program..........................................................................................................16 1.12 Compiling the Program..................................................................................................17 1.13 Interpreting and Running the Program..........................................................................17 1.14 Comments in Java..........................................................................................................17 1.15 Application Structure and Elements..............................................................................18 Summary ...............................................................................................................................19 Chapter 2 : Data types, variables and Arrays...........................................................................20 2.1 Data Types ......................................................................................................................20 2.2 Literals.............................................................................................................................21 2.3 Java Character Encoding: UTF and Unicode...................................................................21 2.4 EscapeSequences.............................................................................................................22 2.5 Rules for naming an identifier.........................................................................................22 2.6 Java Language Keywords ...............................................................................................23 2.7 Variables .........................................................................................................................23 2.8 Declaring constants – Final variables..............................................................................24 2.9 Arrays...............................................................................................................................24 2.10 Multidimensional Arrays...............................................................................................26 2.11 Copying Arrays .............................................................................................................27 Summary................................................................................................................................28 Questions................................................................................................................................29 Chapter 3 : Operators.................................................................................................................33 3.1 Operands..........................................................................................................................33 3.2 Operator ..........................................................................................................................33 3.2.1 Arithmetic Operators ...................................................................................................34 3.2.2 Increment and Decrement Operators............................................................................36 3.2.3 Relational Operators.....................................................................................................36 3.2.4 Bitwise Operators .........................................................................................................38

1

3.2.5 Logical Operators .........................................................................................................40 3.2.6 Assignment Operators ..................................................................................................43 3.2.7 Ternary or Conditional operator...................................................................................44 3.2.8 The [ ] Operator............................................................................................................45 3.2.9 The . Operator..............................................................................................................45 3.2.10 The () Operator...........................................................................................................45 3.2.11 The (type) Operator.....................................................................................................46 3.2.12 The new Operator.......................................................................................................46 3.2.13 The instanceof Operator..............................................................................................46 3.3 Expressions......................................................................................................................46 3.4 Statements........................................................................................................................46 3.5 Operator Precedence........................................................................................................47 3.6 Type Conversion and Casting..........................................................................................49 3.7 Automatic Type Promotions............................................................................................52 Summary................................................................................................................................53 Questions................................................................................................................................53 Chapter 4 : Control flow statements..........................................................................................57 4.1 The while and do-while Statements ................................................................................57 4.2 The for Statement ............................................................................................................58 4.3 The if/else Statements .....................................................................................................60 4.4 The switch Statement ......................................................................................................63 4.5 Branching Statements......................................................................................................65 4.5.1 The break Statement.....................................................................................................65 4.5.2 The continue Statement.................................................................................................66 4.5.3 The return Statement.....................................................................................................68 4.6 Exception Handling Statements ......................................................................................68 Summary................................................................................................................................69 Questions................................................................................................................................69 Chapter 5 : Class Fundamentals and OOP...............................................................................73 5.1 What Is an Object? ..........................................................................................................73 5.2 What Is a Class? ..............................................................................................................74 5.3 What Is a Message?.........................................................................................................74 5.4 Features of Object Oriented Programming .....................................................................75 5.4.1 Encapsulation ...............................................................................................................75 5.4.2 Inheritance.....................................................................................................................76 5.4.3 Polymorphism...............................................................................................................77 5.4.4 Abstraction....................................................................................................................78 5.5 Defining Classes .............................................................................................................78 5.6 Creating Objects...............................................................................................................78 5.7 Defining Methods in a class.............................................................................................79 5.8 Declaring Variables in a Class.........................................................................................84 5.9 Instance and Class Members............................................................................................87 5.10 Static Initializer..............................................................................................................92 5.11 Variable Shadowing.......................................................................................................93 2

5.12 Pass by value and Pass by reference..............................................................................94 5.13 Access Control...............................................................................................................97 5.14 Constructors.................................................................................................................101 5.15 The this keyword..........................................................................................................103 5.16 Overloading..................................................................................................................103 5.17 Recursion.....................................................................................................................106 5.18 Native Methods............................................................................................................107 5.19 Arrays of Objects ........................................................................................................107 5.20 Nested and Inner Classes ............................................................................................108 5.21 Command-Line Arguments ........................................................................................113 5.22 Enumerated types.........................................................................................................114 5.23 Garbage Collection......................................................................................................117 Summary..............................................................................................................................118 Questions..............................................................................................................................119 Chapter 6 : Inheritance.............................................................................................................128 6.1 Inheritance Basics..........................................................................................................128 6.2 Understanding how Constructors are called..................................................................131 6.3 Overriding Methods ......................................................................................................135 6.4 Dynamic Method Dispatch............................................................................................139 6.5 Annotations ...................................................................................................................140 6.6 Hiding Member Variables..............................................................................................142 6.7 Abstract Classes.............................................................................................................143 6.8 Abstract Methods...........................................................................................................144 6.9 Final Classes..................................................................................................................146 6.10 Final Methods..............................................................................................................148 6.11 Access control and Inheritance....................................................................................149 6.12 Anonymous Inner Class...............................................................................................149 6.13 The Object class ..........................................................................................................151 Summary..............................................................................................................................154 Questions..............................................................................................................................155 Chapter 7 : Packages and Interfaces........................................................................................158 7.1 Packages ........................................................................................................................158 7.2 Using package members................................................................................................161 7.3 Interfaces .......................................................................................................................164 7.4 Static Import ..................................................................................................................169 7.5 strictfp............................................................................................................................171 Summary..............................................................................................................................172 Questions..............................................................................................................................172 Chapter 8 : Assertions and Exception handling.....................................................................175 8.1 What is an Exception? ..................................................................................................175 8.2 Types of Exceptions.......................................................................................................180 8.3 Catching and Handling Exceptions ...............................................................................182 8.4 The throw Statement .....................................................................................................187 3

8.5 The throws Clause..........................................................................................................189 8.6 Overriding methods that throw exceptions....................................................................190 8.7 Java’s built in exceptions...............................................................................................191 8.8 Chained Exceptions ......................................................................................................195 8.9 Creating Your Own Exception Classes .........................................................................198 8.10 Assertions.....................................................................................................................200 Summary..............................................................................................................................203 Questions..............................................................................................................................203 Chapter 9 : Multithreaded programming...............................................................................206 9.1 Multitasking...................................................................................................................206 9.2 What Is a Thread? .........................................................................................................206 9.3 The Thread class............................................................................................................209 9.4 Using the main thread....................................................................................................210 9.5 Creating a thread............................................................................................................211 9.6 The Java Thread Model.................................................................................................213 9.7 Thread priority...............................................................................................................215 9.8 Using the Thread yield method......................................................................................217 9.9 Stopping a Thread..........................................................................................................218 9.10 Determining When a Thread Has Finished..................................................................219 9.11 Thread Scheduling ......................................................................................................220 9.12 Thread Synchronization...............................................................................................222 9.13 Interthread Communication.........................................................................................229 9.14 Starvation and Deadlock .............................................................................................232 9.15 Suspending, Resuming & Stopping Threads ..............................................................232 9.16 ThreadGroup................................................................................................................235 Summary..............................................................................................................................236 Chapter 10 : String Handling...................................................................................................237 10.1 The String class............................................................................................................237 10.2 The StringBuffer Class................................................................................................248 10.3 The StringBuilder class................................................................................................257 Questions..............................................................................................................................257 Chapter 11 : I/O.........................................................................................................................259 11.1 I/O Streams .................................................................................................................259 11.2 Reading console input..................................................................................................265 11.3 Writing console output.................................................................................................266 11.4 System.out.printf().......................................................................................................267 11.5 File class.......................................................................................................................270 11.6 Using File Streams.......................................................................................................274 11.7 Scanning text with java.util.Scanner............................................................................278 11.8 Redirecting Standard I/O.............................................................................................281 11.9 Working with Random Access Files ...........................................................................282 11.10 Filter Streams.............................................................................................................284 11.11 Object Serialization ...................................................................................................287 4

Summary..............................................................................................................................291 Chapter 12 : API classes in java.lang package........................................................................292 12.1 Wrapper classes...........................................................................................................292 12.2 Autoboxing/Unboxing of Wrappers............................................................................297 12.3 Math class....................................................................................................................299 12.4 System class.................................................................................................................306 12.5 Runtime class...............................................................................................................308 12.6 Class class....................................................................................................................310 Summary..............................................................................................................................310 Questions..............................................................................................................................311 Chapter 13 : Utility & Legacy classes......................................................................................314 13.1 Enumeration interface .................................................................................................314 13.2 Vector class..................................................................................................................314 13.3 Stack class....................................................................................................................316 13.4 Dictionary class............................................................................................................318 13.5 Hashtable class.............................................................................................................318 13.6 Properties class.............................................................................................................319 13.7 Formatter class.............................................................................................................321 13.8 Date class.....................................................................................................................323 13.9 Calendar class..............................................................................................................324 13.10 GregorianCalendar class............................................................................................325 13.11 TimeZone and SimpleTimeZone classes...................................................................326 13.12 Locale class................................................................................................................328 13.13 StringTokenizer class.................................................................................................329 13.14 StreamTokenizer class...............................................................................................332 13.15 Random class.............................................................................................................334 13.16 BitSet class.................................................................................................................335 13.17 Timer and TimerTask classes....................................................................................335 13.18 Observable class ........................................................................................................337 13.19 Currency class............................................................................................................339 Chapter 14 : Regular Expression Processing..........................................................................340 14.1 What is a Regular Expression?....................................................................................340 14.2 Pattern class.................................................................................................................342 14.3 Matcher class...............................................................................................................342 14.4 String Class RegEx Methods.......................................................................................345 Chapter 15 : API classes in java.text........................................................................................346 15.1 DateFormat class..........................................................................................................346 15.2 SimpleDateFormat class..............................................................................................348 15.3 DateFormatSymbols class............................................................................................350 15.4 NumberFormat class....................................................................................................351 15.5 DecimalFormat class....................................................................................................353

5

15.6 Format class.................................................................................................................355 Summary..............................................................................................................................357 Chapter 16 : Collections Framework and Generics...............................................................358 16.1 What is a Collection?...................................................................................................358 16.2 Generics.......................................................................................................................358 16.3 What Is a Collections Framework?..............................................................................360 16.4 Collection Interfaces ...................................................................................................361 16.5 The Collection Interface .............................................................................................362 16.6 The Set Interface..........................................................................................................367 16.7 The List Interface ........................................................................................................371 16.8 The Queue Interface.....................................................................................................381 16.9 The Map Interface .......................................................................................................383 16.10 Object Ordering ........................................................................................................388 16.11 The SortedSet Interface..............................................................................................395 16.12 The SortedMap Interface...........................................................................................398 16.13 Relationships Among Generics .................................................................................398 16.14 Wildcard Types .........................................................................................................399 16.15 Defining and Using Generic Methods ......................................................................400 Answers.......................................................................................................................................402 Chapter 2..............................................................................................................................402 Chapter 3..............................................................................................................................403 Chapter 4..............................................................................................................................404 Chapter 5..............................................................................................................................405 Chapter 6..............................................................................................................................408 Chapter 7..............................................................................................................................410 Chapter 8..............................................................................................................................410 Chapter 10............................................................................................................................411 Chapter 12 ...........................................................................................................................411

6

Chapter 1 : Java Technology
1.1 History of Java
Around 1990 James Gosling , Bill Joy and others at Sun Microsystems began developing a language called Oak. They wanted it primarily to control microprocessors embedded in consumer items such as cable set-top boxes,VCR's, toasters, and also for personal data assistants (PDA). To serve these goals, Oak needed to be:
o o o

Platform independent (since multiple manufacturers involved) Extremely reliable Compact.

However, as of 1993, interactive TV and PDA markets had failed to take off. Then the Internet and Web explosion began, so Sun shifted the target market to Internet applications and changed the name of the project to Java. By 1994 Sun's HotJava browser appeared. Written in Java in only a few months, it illustrated the power of applets, programs that run within a browser, and also the capabilities of Java for speeding program development. Riding along with the explosion of interest and publicity in the Internet, Java quickly received widespread recognition and expectations grew for it to become the dominant software for browser and consumer applications. However, the early versions of Java did not possess the breadth and depth of capabilities needed for client (i.e. consumer) applications. For example, the graphics in Java 1.0 seemed crude and clumsy compared to mature software developed with C and other languages. Applets became popular and remain common but don't dominate interactive or multimedia displays on web pages. Many other "plug-in" types of programs also run within the browser environment. So Java has not succeeded at development of consumer applications. However, Java's capabilities grew with the release of new and expanded versions and it became a very popular language for development of enterprise, or middleware, applications such as on line web stores, transactions processing, database interfaces, and so forth. Java has also become quite common on small platforms such as cell phones and PDAs. Java is now used in several hundred cell phone models. Over 600 million JavaCards, smart cards with additional features provided by Java, have been sold as of the summer of 2004.

7

1.2 What is Java?
The term Java actual refers to more than just a particular language like C or Pascal. Java encompasses several parts, including :

A high level language – the Java language is a high level one that at a glance looks very similar to C and C++ but offers many unique features of its own. Java bytecode - a compiler, Sun's javac, transforms the Java language source code to bytecode that runs in the JVM. Java Virtual Machine (JVM) – a program, such as Sun's java, that runs on a given platform and takes the bytecode programs as input and interprets them just as if it were a physical processor executing machine code.

Sun provides a set of programming tools such as javac, java and others in a bundle that it calls a Java Software Development Kit for each version of the language and for different platforms such as Windows, Linux, etc.. Sun also provides a runtime bundle with just the JVM when the programming tools are not needed. Note that because of the open nature of Java any or all of these parts can be replaced by non-Sun components. For example, just as many different languages can create machine code for a given processor, compilers of other languages have been created that output bytecode to run in the JVM. Similarly, many JVMs have been written by groups outside of Sun. Java, Open or Closed? Java is not quite an open language but not quite a proprietary one either. All the core language products - compiler, virtual machines (VM), class packages, and other components - are free. Detailed specifications and source code are made openly available. The Java Community Process (JCP) leads the development of new standards for the language. Other companies and organizations can legally create a clean sheet compiler and/or a Virtual Machine as long as it follows the publicly available specifications. Microsoft did this with the Version 1.1 JVM that it used in its Internet Explorer browser. Sun, however, does still assert final say on the specifications and controls the copyrights to logos, and trademarks.

1.3 Versions of Java
Since its introduction, Sun has released a new version of the Java language every two years or so. These new versions brought enhancements, new capabilities and fixes to bugs. Until recently, the versions were numbered 1.x, where x reached up till 4. (Intermediate revisions were labeled with a third number - 1.x.y - as in 1.4.2.) The newest version, however, is called Java 5.0 rather than Java 1.5.

8

504 classes o Improvements include better event handling. of Java along with some of the new features that each one introduced.5): o 165 packages.0. of Java. or Standard Edition (SE). or editions.2991 classes o Improved IO. o Many browsers in use are still compatible only with 1. improved JVM. o Microsoft and other companies licensed Java.0 included Java 1. and hash maps. o Swing packages of greatly improved graphics became available during this time but not included with the core language. sets. over 3000 classes o Faster startup and smaller memory footprint o Metadata o Formatted output o Generics o Improved multithreading features • • • • • Other Editions of Java In the late 1990s.3: o 76 packages . 1999: Version 1. 2004: Version 5. embedded applications and the other for large scale middleware applications: Micro Java 9 .0-4. 2000: Version 1.2.Below is a timeline of the different versions of the basic. etc. inner classes.1: o 23 packages .1. based on Swing. also called the Java 2 Platform o 59 packages . One is aimed at small. o Collections API included support for various lists. This edition contains the core language packages (the name for code libraries in Java) and is aimed for desktop programming.1.0 (previously numbered 1.1842 classes o Performance enhancements including the Hotspot virtual machine. 2002: Version 1. Sun split off two other more specialized branches. XML support. o Microsoft developed its own 1. o 8 packages with 212 classes o Netscape 2. 1997: Version 1. now included with the core language.0 of the Java Development Kit (JDK) was released for free by Sun.1520 classes o Code and tools distributed as The Software Development Kit (SDK) o Java Foundation Classes (JFC). compatible Java Virtual Machine for the Internet Explorer.4: o 135 packages . for improved graphics and user interfaces. • 1995: Version 1.

the newer versions maintain compatibilty with older code.1.based on Java 1. This means substantially less disk space or no disk at all. Java 2 Platform. The Java 2 Enterprise Edition now provides a wide array of tools for building middleware software such as for database access applications.Java 2 Platform. Enterprise Edition With the Java 2 Platform came a separate version with enhanced resources targeted at enterprise applications. online storefronts.1 for 32 bit system with about 512kb each for ROM and RAM.Java 5. PersonalJava . however. The approach has been to add new features without subtracting any older features. Individual packages. such as the event handling system introduced in Java 1.1. and less of other types of nonvolatile memory.4 Code Compatibility Sun has maintained good compatibility among codes written with the different versions. Micro Edition (J2ME) .   JavaCard . The developer will choose from different configurations to suit the capacity of a given system.1 based systems (EmbeddedJava and PersonalJava but not JavaCard). It also usually means a smaller display or perhaps no display at all. classes and even methods in the core language can be thrown out to make room.0 . and other services.) 10 .8 for larger systems with 2MB ROM and more than 1MB RAM.based on Java 1. code using newer classes and techniques should not be mixed in the same program with older version code. (In some cases. Also. J2ME replaces the Java 1.extremely limited Java for systems with only 16kb nonvolatile memory and 512 bytes volatile EmbeddedJava . Generally. For such systems Sun offers slimmed down versions of Java. terms change such as Java Development Kit becoming Software Development Kit.and not worry about all these historical issues. you can just use the latest version . Naming Conventions All of these editions and version numbers can be a bit confusing for newcomers.based on the Java 2 Platform.   J2EE . 1.Embedded systems such as cell phones and device controllers typically offer reduced resources as compared to desktop PCs. For this course.

11 . it just sometimes took a lot more boilerplate code (i. Release 5.0) was launched as the official Java version by Sun on September 30.0 (J2SE 5. The most important changes to the platform include the following: Quality.) The bytecode from a Java 1. Many of these features are built right in to the system. and Compatibility The designers of J2SE considered quality. thus producing fewer runtime errors.4.0 will compile with a Java 5 compiler. (Though some obsolete methods will generate "deprecation" warning messages from the compiler. making coding faster and more error free. stability. the new EoD features are all about syntax shortcuts that greatly reduce the amount of code that must be entered.0 you could do with 1. For example. 1. Most of the changes fall into the ease of development (EoD) category. it is now much easier to watch memory usage and detect and respond to a low-memory condition.0 compiler will still run in a Java 5 virtual machine. Ease of Development It is in the EoD area that the most significant changes appear. especially any code that worked with earlier versions of Java but failed under 5. Monitoring and Manageability The 5.0 Improvements Java 2 Platform. the changes do not add new functionality but rather provide an easier way of doing the same things you could do before but with less code and better compiler-time error detection. In most cases.Thus far. Some features enable improved compile-time type checking. 2004. Great efforts were made to ensure compatibility with previous versions of Java. code that is repeated frequently) to do it. Stability. With a few important exceptions. These have been achieved through careful tuning of the software and use of class data sharing. The Sun engineers made a public plea for users worldwide to test their code with the 5. Performance and Scalability Faster JVM startup time and smaller memory footprint were important goals.0.0 release includes the ability to remotely monitor and even manage a running Java application.e. In many cases. and compatibility to be the most important aspect of the new release.0 Beta releases and to report any problems that appeared. no new functionality was added in the sense that almost anything you can do with 5. and you can add additional monitoring and managing features to your own code. Standard Edition 5. Java maintains backwards compatibility. A program written according to Java 1.5 Java 5. The exception to this general statement has to do with the new multithreading and concurrency features that provide capabilities previously unavailable.0 is the most tested release ever.

12 . The following figure illustrates how this works. Compilation happens just once.0 release was an improved experience on the desktop client. The Java Web Start and Java Plug-In technologies (both used to run Java applications downloaded over the Web) have been improved. first you translate a program into an intermediate language called Java bytecodes —the platform-independent codes interpreted by the interpreter on the Java platform. improvements to Unicode.2 have received further improvements. interpretation occurs each time the program is executed. improved Swing look and feel called Ocean. There is support for OpenGL and better performance on Unix X11 platforms. the GTK and XP look and feels introduced in J2SE 1. 1.Improved Desktop Client The last great theme of the 5. and an improved. The interpreter parses and runs each Java bytecode instruction on the computer.6 Features of Java The Java programming language is a high-level language that can be characterized by all of the following buzzwords:  Simple  Object oriented  Distributed  Interpreted  Robust  Secure  Architecture neutral  Portable  High performance  Multithreaded  Dynamic With most programming languages. improvements to Java's database connectivity package known as JDBC. you either compile or interpret a program so that you can run it on your computer. and a new easy-to-customize skinnable look and feel called Synth in which you can use XML configuration files to specify the appearance of every visual component in the system.4. The Java programming language is unusual in that a program is both compiled and interpreted. highcompression format for JAR files that can greatly reduce download times for applets and other networked applications.0 include core XML support. there is a new. In addition. Other new features in J2SE 5. In addition to better performance because of a faster startup time and smaller memory footprint. With the compiler.

Java bytecodes help make "write once. is an implementation of the Java VM. Java frees you from having to worry about many of the most common causes of programming errors. a Solaris workstation. It also checks the code at run-time. deallocation is completely automatic. Because Java is a strictly typed language. because Java provide Garbage Collection for unused objects. Java was designed to be easy for the professional programmer to learn and use effectively. The Java runtime system comes with an elegant yet sophisticated 13 . the same program written in the Java programming language can run on Windows 2000.You can think of Java bytecodes as the machine code instructions for the Java Virtual Machine (Java VM). or on an iMac. That means that as long as a computer has a Java VM. Java virtually eliminates the memory access by managing memory allocation and deallocation. The bytecodes can then be run on any implementation of the Java VM. Java supports multithreaded programming which allows you to write programs that do many things simultaneously. whether it's a development tool or a Web browser that can run applets. In fact. Every Java interpreter. it checks your code at compile-time. You can compile your program into bytecodes on any platform that has a Java compiler. run anywhere" possible.

14 .8 Why Java is important to Internet? Java provides a firewall between a networked application and your computer. because it handles TCP/IP protocols. Java Servlets are a popular choice for building interactive web applications. thus making Java architecture neutral. Write once run anywhere feature. Another reason why Java is important to Internet is due to its portability i. configuring or tailoring the server. For example. you can safely download Java applets without fear of viral infection or malicious intent. 1. though. A servlet can almost be thought of as an applet that runs on the server side. replacing the use of CGI scripts. Another specialized program is a servlet. mail servers. Java supports dynamic programming where small fragments of bytecode may be dynamically updated on a running system. A special kind of application known as a server serves and supports clients on a network. processor upgrades and changes in core system resources can all combine to make a program malfunction. Instead of working in browsers. Accessing a resource using a URL is not much different from accessing a file. e.7 Java Applets and Applications The most common types of programs written in the Java programming language are applets and applications. the Java platform is helping computer users to do things that were previously unimaginable. and print servers. With Java technology. Java is designed for the distributed environment of the Internet. An application is a standalone program that runs directly on the Java platform. Examples of servers are Web servers. users can securely access their personal information and applications when they're far away from the office by using any computer that's connected to the Internet. The Java designers made several hard decisions in the Java language and Java Virtual Machine in an attempt to alter this situation. An applet is an application designed to be transmitted over the Internet and executed by a Java-compatible Web browser. Servlets are similar to applets in that they are runtime extensions of applications. An applet is a program that adheres to certain conventions that allow it to run within a Java-enabled browser. 1. Coupled with the power of networking. servlets run within Java Web servers. Operating system upgrades. When you use a Java-compatible web browser. soon they'll be able to access tailored applications from a mobile phone based on the Java platform. or even use smart cards as a pass key to everything from the cash machine to ski lifts. the Internet and private networks become your computing environment. Java achieves this protection by confining a Java program to the Java execution environment and not allowing it access to other parts of the computer. proxy servers.solution for multiprocess synchronization that enables you to construct smoothly running interactive systems.

in many locations and on many different kinds of appliances and devices at home.easily and securely -. This interpreter takes your bytecode file and carries out the instructions by translating them into instructions that your computer can understand. lowers computing costs. The following figure depicts a program that's running on the Java platform. because it was designed for use on networks from the beginning. 15 . The Java API is a large collection of ready-made software components that provide many useful capabilities. The Java compiler and interpreter are case-sensitive. Businesses are using Java technology because it connects easily to existing computing systems. The compiler converts these instructions into a bytecode file. the Java API and the virtual machine insulate the program from the hardware. As the figure shows. 1. takes your source file and translates its text into instructions that the Java Virtual Machine (Java VM) can understand. The Java interpreter installed on your computer implements the Java VM. It also lets businesses use the Internet to securely connect to their customers. And consumers benefit from Java technology because it brings personal.9 The Java Platform A Java platform is the software environment in which a program runs. suppliers and partners. javac.Why Java technology? Networks require software that is portable. at work and on the road. and entertainment services to them -. The Java API is grouped into libraries of related classes and interfaces. The Java platform has two components: • • The Java Virtual Machine (Java VM) The Java Application Programming Interface (Java API) The compiler. these libraries are known as packages. and secure -. and speeds software development. such as graphical user interface (GUI) widgets. business.all areas where Java technology shines. modular.

public and private key management. threads. pay particular attention to the capitalization. using the text editor of your choice. create a text file with the following text. TCP (Transmission Control Protocol). and supporting files. and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability. and be sure to name the text file ExampleProgram. Networking: URLs. and IP (Internet Protocol) addresses. Java Database Connectivity (JDBCTM): Provides uniform access to a wide range of relational databases. Security: Both low level and high level. the Java platform can be a bit slower than native code. speech.println("I'm a Simple Program"). Software components: Known as JavaBeansTM. Applications are standalone programs. 1.11 Writing a Program The easiest way to write a simple program is with a text editor. including electronic signatures.java. well-tuned interpreters. Java programs are case sensitive. As a platform-independent environment. data structures. The Java platform also has APIs for 2D and 3D graphics. UDP (User Datagram Protocol) sockets. the Java platform core classes. Internationalization: Help for writing programs that can be localized for users worldwide. strings.10 What Can Java Technology Do? Every full implementation of the Java platform gives you the following features: • • • • • • • • The essentials: Objects. smart compilers. However. and so on. servers. collaboration. and certificates. So. so if you type the code in yourself. access control. can plug into existing component architectures.out. the compiled code runs on a specific hardware platform. Java 2 Runtime Environment (JRE) consists of the virtual machine. The Java 2 SDK includes the JRE and development tools such as compilers and debuggers. and more. input and output. animation. Object serialization: Allows lightweight persistence and communication via Remote Method Invocation (RMI). 1. Programs can automatically adapt to specific locales and be displayed in the appropriate language. date and time. } 16 . //A Very Simple Example class ExampleProgram { public static void main(String[] args){ System. telephony.Native code is code that after you compile it. system properties. accessibility. Applets: The set of conventions used by applets. numbers.

out.println("I'm a Simple Program"). or to generate API documentation.java 1. or interpret and run applets in any Web browser with a Java VM built in such as Netscape or Internet Explorer. Double Slashes Double slashes (//) are used in the C/C++ programming language. and tell the compiler to treat everything from the slashes to the end of the line as text. and doc comments. which converts the Java byte codes to platformdependent machine codes so your computer can understand and run the program. the Java language supports three kinds of comments: double slashes. to comment-out lines of code to isolate the source of a problem for debugging purposes. } } 17 .14 Comments in Java Code comments are placed in source files to describe what is happening in the code to someone who might be reading the file. you should see: I'm a Simple Program 1.13 Interpreting and Running the Program Once your program successfully compiles into Java bytecodes. To these ends. you can interpret and run applications on any Java VM.12 Compiling the Program A program has to be converted to a form the Java VM can understand so any computer with a Java VM can interpret and run the program The Java compiler is invoked at the command line on Unix and DOS shell operating systems as follows: javac ExampleProgram. The Java interpreter is invoked at the command line on Unix and DOS shell operating systems as follows: java ExampleProgram At the command line. //A Very Simple Example class ExampleProgram { public static void main(String[] args){ System. Interpreting and running a Java program means invoking the Java VM byte code interpreter.} 1. C-style.

and is the class name passed to the java interpreter command to run the application. there is no reason to generate API documentation. The difference between a class and a RECORD or struct is that a class also defines the methods to work on the data. } } With one simple class. 18 . This class is the entry point for the program. for example.println("I'm a Simple Program"). use the doc comments (/** */) to enclose lines of text for the javadoc tool to find. /* These are C-style comments */ class ExampleProgram { public static void main(String[] args){ System. store a text string in one field. API documentation makes sense when you have an application made up of a number of complex classes that need documentation. The javadoc tool locates the doc comments embedded in source files and uses those comments to generate API documentation. The tool generates HTML files (Web pages) that describe the class structures and contain the text enclosed by doc comments.15 Application Structure and Elements An application is created from classes.out. */ class ExampleProgram { public static void main(String[] args){ System. Methods that work on the data are called accessor methods.println("I'm a Simple Program").C-Style Comments Instead of double slashes. a very simple class might store a string of text and define one method to set the string and another method to get the string and print it to the console. 1. Every application needs one class with a main method. A class is similar to a RECORD in the Pascal language or a struct in the C language in that it stores related data in fields. where the fields can be different types.out. an integer in another field. /** This class displays a text string at * the console. So you could. you can use C-style comments (/* */) to enclose one or more lines of code to be treated as text. } } Doc Comments To generate documentation for your program. and a floating point in a third field. For example.

it has a main method. The public static void keywords mean the Java virtual machine (JVM) interpreter can call the program's main method to start the program (public) without creating an instance of the class (static). It can be used for embedded as well as mobile applications. Java is important because of its cross-platform functionality. Also Java is a secure language. Java is not only a programming language it’s a platform. Summary In this chapter you learnt the history of Java and how the Java language has evolved. Java can be used for simple as well as complex applications. and is the control point from which the controller class accessor methods are called to work on the data. but because it is the only class in the program. and the program does not return data to the Java VM interpreter (void) when it ends. It has no fields or accessor methods.The code in the main method executes first when the program starts. 19 .

and interfaces are reference types. is a reference to (an address of) the value or set of values represented by the variable.1 Data Types The Java programming language has two categories of data types: primitive and reference. positive value: 2-149 20 . or a boolean value. Min. You use the variable's name instead. in contrast to that of a primitive type. or a memory address in other languages. a character. classes. Range of primitive data types Primitive Type Size Range of Values byte 8 bit -27 to 27-1 short 16 bit -215 to 215-1 int 32 bit -231 to 231-1 long 64 bit -263 to 263-1 char 16 bit '\u0000' to '\uffff'(0 to 216-1 ) float 32 bit Max. variables and Arrays 2. Primitive Data Types Keyword byte short int long float double char boolean Description (integers) Byte-length integer Short integer Integer Long integer (real numbers) Single-precision floating point Double-precision floating point (other types) A single character A boolean value (true or false) Size/Format 8-bit two's complement 16-bit two's complement 32-bit two's complement 64-bit two's complement 32-bit IEEE 754 64-bit IEEE 754 16-bit Unicode character true or false You can put a literal primitive value directly in your code. A variable of primitive type contains a single value of the appropriate size and format for its type: a number. A reference is called a pointer. The value of a reference type variable.Chapter 2 : Data types. positive value: (2-2-23)*2127. Arrays. int anInt = 4. The Java programming language does not support the explicit use of addresses like other languages do.

the 'x' and the letters can be upper or lower case).g. The two boolean literals are simply true and false. positive value: 2-1074 2. 'L' is preferred as it cannot be confused with the digit '1'. Unicode characters are stored in two bytes 21 . 013042 (and obviously only digits 0-7 are allowed). You can specify a float by putting an 'f' or 'F' after the number. 0x23e4A (digits allowed are 0-9 and a to f. Min. Use \u followed by four hexadecimal digits representing the 16 bit unicode character e.g. Examples of Literal Values and Their Data Types Literal 178 8864L 37.77e3 'c' true false A series of digits with no decimal point is typed as an integer.g.266D 87.266 Data Type int long double double float double char boolean boolean 37. char x='\u1234' Java also supports certain escape codes for special characters such as '\n' for newline. A literal character value is any single Unicode character between single quote marks. Octal literals begin with zero e. 2. positive value: (2-2-52)*21023. These will be translated into values by the compiler and inserted into the byte code. Construct a literal value of char type using Java's unicode escape format for a specified character code. Constructing literal numeric values using octal and hexadecimal formats.3 Java Character Encoding: UTF and Unicode Java uses two closely related encoding systems UTF and Unicode. Java was designed from the ground up to deal with multibyte character sets and can deal with the vast numbers of characters that can be stored using the Unicode character set. Hexadecimal literals begin with zero and an 'x' e.363F 26. A series of digits with a decimal point is of type double.2 Literals A specific primitive value in a line of code is called a literal. You can specify a long integer by putting an 'L' or 'l' after the number.double 64 bit Max.

A convention that is sometimes adopted to make identifiers more readable is to use a capital letter to indicate the beginning of a new word. the underscore character ( _ ) or dollar character ($) they cannot start with a number they must not include spaces. 2. firstNumber. numbers. and just about any other character set known. This can result in a considerable saving by comparison with using Unicode where every character requires 2 bytes. other special characters or punctuation marks a Java keyword must not be used. e. this is sometimes called camel hump notation. The filename for the class code is the same as the name of the class. variables and attributes (attributes could be numbers.4 EscapeSequences \b \t \n \f \r \" \' \\ OctalEscape /* /* /* /* /* /* /* /* /* \u0008: backspace BS */ \u0009: horizontal tab HT */ \u000a: linefeed LF */ \u000c: form feed FF */ \u000d: carriage return CR */ \u0022: double quote " */ \u0027: single quote ' */ \u005c: backslash \ */ \u0000 to \u00ff: from octal value */ 2. There are rules which govern what is allowable. This means it can deal with Japanese Chinese. most of which can easily be stored within one byte. Note that Java is case sensitive so A1 and a1 are different identifiers. objects. Identifiers must be chosen according to certain rules: • • • • they can contain letters.java.g. classes. words or even objects).5 Rules for naming an identifier When we learn to program we have to give names or identifiers to things we create such as files. the code for the class JTRectangle is stored in the file JTRectangle.which allows for up to 65K worth of characters. for example: cubeRoot. identifiers and other text within programs. Most of the text data within a program uses standard ASCII. 22 . Although Unicode can represent almost any character you would ever likely to use it is not an efficient coding method for programming. For reasons of compactness Java uses a system called UTF-8 for string literals. Naming Conventions Class identifiers begin with a capital letter.

which generally looks like this: type name In addition to the name and type that you explicitly give a variable.7 Variables A variable is an item of data named by an identifier. on integer variables. You must explicitly provide a name and a type for each variable you want to use in your program. You can perform arithmetic operations. A variable's data type determines the values that the variable can contain and the operations that can be performed on it.Object identifiers start with a lowercase letter. abstract boolean break byte case catch char class const * continue default do enum**** double Else extends Final finally Float For goto * If implements import instanceof assert*** int interface long native new package private protected public return short static strictfp ** super switch synchronized this throw throws transient try void volatile while * indicates a keyword that is not currently used ** indicates a keyword that was added for Java 2 *** new in J2SE 1. 23 . Attributes identifiers start with a lowercase letter. a variable has scope. Integers can contain only integral values (both positive and negative). and null are not keywords but they are reserved words. false.6 Java Language Keywords true. To give a variable a type and a name. 2. Every variable must have a data type. The variable's type determines what values it can hold and what operations can be performed on it.0 2. such as addition. You use the variable name to refer to the data that the variable contains. The variable's name must be a legal identifier --an unlimited series of Unicode characters that begins with a letter. so you cannot use them as names in your programs either. you write a variable declaration.4 **** new in J2SE 5.

. if necessary. blankfinal = 0. Simply declare the local variable and initialize it later. The previous statement declares a final variable and initializes it. . 2. 24 . it cannot be set. The following variable declaration defines a constant named PI. You may. all at once. After creation. like this: isVisible. The value of a final variable cannot change after it has been initialized.Variable names begin with a lowercase letter. and each word after the first begins with an uppercase letter. To declare a final variable. The underscore character (_) is acceptable anywhere in a name.141592653589793. Again. and any later attempts to assign a value to blankfinal result in a compile-time error. Such variables are similar to constants in other programming languages. 2. A final local variable that has been declared but not yet initialized is called a blank final. the name of constant values are spelled in uppercase letters. use the final keyword in the variable declaration before the type: final int aFinalVar = 0. the words are joined together. whose value is pi.8 Declaring constants – Final variables You can declare a variable in any scope to be final.9 Arrays An array is a structure that holds multiple values of the same type. By convention. Subsequent attempts to assign a value to aFinalVar result in a compiler error. the ratio of the circumference of a circle to its diameter (3.141592653589793) and cannot be changed: final double PI = 3. like this: final int blankfinal. If a variable name consists of more than one word. . and class names begin with an uppercase letter. an array is a fixed-length structure. The length of an array is established when the array is created (at runtime). once a final local variable has been initialized. defer initialization of a final local variable. but by convention is used only to separate words in constants (because constants are all caps by convention and thus cannot be case-delimited).

where type is the data type of the elements contained within the array. you use the new operator. As with declarations for variables of other types. Declaring an Array This line of code from the sample program declares an array variable: int[] anArray. An array's type is written type[]. and [] indicates that this is an array. the declaration for an array variable does not allocate any memory to contain the array elements. when creating an array. // declare an array of integers Like declarations for variables of other types. Creating an Array You create an array explicitly using Java's new operator. Object[] anArrayOfObjects. Here are declarations for arrays that hold other types of data: float[] anArrayOfFloats. The sample program must assign a value to anArray before the name refers to an array. so the array called anArray will be used to hold integer data. plus the data type of the array elements. The sample program uses int[]. Remember that all of the elements within an array are of the same type. boolean[] anArrayOfBooleans.An array element is one of the values within an array and is accessed by its position within the array. anArray = new int[10]. new elementType[arraySize] 25 . plus the number of elements desired enclosed within square brackets ('[' and ']'). String[] anArrayOfStrings. an array declaration has two components: the array's type and the array's name. // create an array of integers In general. The next statement in the sample program allocates an array with enough memory for ten integer elements and assigns the array to the variable anArray declared earlier.

The length of the array is determined by the number of values provided between { and }. you append square brackets to the array name. length is a property provided by the Java platform for all arrays.out.. This part of the code shows that to reference an array element. false }. array indices begin at 0 and end at the array length minus 1. 2. Array Initializers The Java programming language provides a shortcut syntax for creating and initializing an array. false. or to access the value. Accessing an Array Element Now that some memory has been allocated for the array. the program assigns values to the array elements: anArray[2] = 10. Here's an example of this syntax: boolean[] answers = { true. true. true. you write arrayname. This doesn't work because length is not a method. Note that in Java.If the new statement were omitted from the sample program. System. an n-dimensional array or simply n-D array) is a collection of items which is accessed via n subscript expressions 26 .java:4: Variable anArray may not have been initialized.10 Multidimensional Arrays A multi-dimensional array of dimension n (i.length Be careful: Programmers new to the Java programming language are tempted to follow length with an empty set of parenthesis. the compiler would print an error like the following one and compilation would fail.print(anArray[2] + " "). ArrayDemo. Getting the Size of an Array To get the size of an array. Before initialization arrays are always set to contain default values wherever they are created. The value between the square brackets indicates (either with a variable or some other expression) the index of the element to access.e. either to assign a value to it.

The two Object arguments indicate the array to copy from and the array to copy to. The arraycopy method requires five arguments: public static void arraycopy(Object source. 'c'. 'a'. ArrayCopyDemo. 'f'. uses arraycopy to copy some elements from the copyFrom array to the copyTo array. 27 . support arrays of arrays. The three integer arguments indicate the starting location in each the source and the destination array. you need only specify the memory for the first (leftmost) dimension. It does. } } 2.11 Copying Arrays Use System's arraycopy method to efficiently copy data from one array into another. public class ArrayOfArraysDemo2 { public static void main(String[] args) { int[][] aMatrix = new int[3][]. You can allocate remaining dimensions separately.The Java programming language does not really support multi-dimensional arrays.6}. When you allocate memory for multidimensional array. int srcIndex. int length). 'f'. //populate matrix aMatrix[0]=new int[]{1}. however. aMatrix[2]=new int[]{4. Object dest. a two-dimensional array x is really an array of onedimensional arrays: int[][] x = new int[3][5]. aMatrix[1]=new int[]{2.int destIndex. and the number of elements to copy. 'e'.5.3}. 'e'. In Java. This diagram illustrates how the copy takes place: The following program. public class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd'.

'i'. the arraycopy method takes the "caffein" out of "decaffeinated". 'n'.println(new String(copyTo)). you use the type of object that the array can contain and brackets. The copy copies 7 elements: 'c'. classes. 'f'. Arrays. To declare an array.out. } } The arraycopy method call in this example program begins the copy at element number 2 in the source array. 'f'. 'e'. The value of a final variable cannot change after it's been initialized. An array is a fixed-length data structure that can contain multiple objects of the same type.'i'. and interfaces are reference types. System. char[] copyTo = new char[7]. 0. 'a'. Effectively. you explicitly set the variable's name and data type. 'a'. 2. like this: Note that the destination array must be allocated before you call arraycopy and must be large enough to contain the data being copied. so that the copy begins at the array element 'c'. System. You can declare a variable as final. 'd' }. The table in the Data Types section shows all of the primitive data types along with their sizes and formats. The arraycopy method call puts the copied elements into the destination array beginning at the first element (element 0) in the destination array copyTo. A variable of primitive type contains a value. 'e'. and 'n'. copyTo. The Java programming language has two categories of data types: primitive and reference. You can provide an initial value for a variable within its declaration by using the assignment operator (=). An array can contain any type of object. Summary When you declare a variable. 28 . including arrays. 't'. 7). Recall that array indices start at 0.arraycopy(copyFrom.

The length of the array must be specified when it is created. // 5 A compile-time error is generated at which line? a. use the arraycopy method in the System class. f. class MCZ11 { } public static char a char b char c char d char e } void main (String[] args) { = '\c'. b. 1 2 3 4 5 None of the above 29 . // 1 = '\r'. d. To get the length of the array. // 4 = '\''. or you can use an array initializer. the size of the array cannot change. An element within an array can be accessed by its index. you use the length attribute. // 2 = '\"'.You can use the new operator to create an array. To copy an array. Once created. // 3 = '\b'. e. Questions 1. c. Indices begin at 0 and end at the length of the array minus 1.

h. $i5. class GRC4 {public static void main(String[] args) {}} // 1 class GRC5 {public static void main(String []args) {}} // 2 class GRC6 {public static void main(String args[]) {}} // 3 What is the result of attempting to compile and run the above programs? a. j. 8i. An attempt to run GRC6 from the command line fails. e. Which of these words belongs to the set of Java keywords? a. _i2. c.2. g. l. value virtual xor None of the above 4. k. f. None of the above 3. class Identifiers { } Compile-time errors are generated at which lines? a. f. An attempt to run GRC5 from the command line fails. #i4. e. h. g. g. b. c. d. An attempt to run GRC4 from the command line fails. Compile-time error at line 3. %i6. d. i_3. b. 1 2 3 4 5 6 7 8 30 . b. i$7. Compile-time error at line 2. c. f. // // // // // // // // 1 2 3 4 5 6 7 8 e. d. Compile-time error at line 1. qualified record repeat restricted int int int int int int int int i1. label to type until i.

5. e. d. '\u0000' to '\u7fff' '\u0000' to '\uffff' 0 to 32767 0 to 65535 -32768 to 32767 -65536 to 65535 31 . b. Which of the following represent the full range of type char? a. c. f.

3. 4 e.{4.6 Compile-time error Run-time error None of the above 32 .2.3}.8.5}.print(a1[0][2]+". // 4 int[] a5 = new int[5]{1.5. e. 2 7. // 3 int []a4 = {1. 1 b. b. class MWC101 { } } public static void main(String[] args) { int[] a1 = new int[]. // 2 int[] a3 = new int[]{1.6}.2.2}.2}. 5 public static void main(String[] args) { int[][] a1 = {{1.4. Prints: 3. System."+a1[1][0]+".8 Prints: 7. // 5 Compile-time errors are generated at which lines? a.10}}. // 1 int a2[] = new int[5].4.9. c. d.out."+a1[2][1]). 3 d.{7.6.2. } } What is the result of attempting to compile and run the program? a. class MWC201 { c.

For example. The unary operators support either prefix or postfix notation.integer. And finally. For example. or string. which in numeric operations is treated as an unsigned two byte integer 3. For example. you get an integer back. An operator that requires two operands is a binary operator. return numbers-the result of the arithmetic operation. which perform basic arithmetic operations such as addition and subtraction. which means that the operator appears between its operands: op1 operator op2 //infix notation The ternary operator is also infix. the arithmetic operators.2 Operator An operator performs a function on one. an operator returns a value. An operator that requires one operand is called a unary operator. An operation is said to evaluate to its result. a ternary operator is one that requires three operands. or three operands.Chapter 3 : Operators 3. = is a binary operator that assigns the value from its right-hand operand to its left-hand operand. an array element. Prefix notation means that the operator appears before its operand: operator op //prefix notation Postfix notation means that the operator appears after its operand: op operator //postfix notation All of the binary operators use infix notation. boolean value. floating point or character any primitive type variable . The return value and its type depend on the operator and the type of its operands. "a[2]" char primitive.1 Operands An operand can be: • • • • • • a numeric variable .numeric value. ?:. each component of the operator appears between operands: op1 ? op2 : op3 //infix notation In addition to performing the operation. 33 . which is a short-hand if-else statement.numeric and boolean reference variable to an object a literal . ++ is a unary operator that increments the value of its operand by 1. The data type returned by an arithmetic operator depends on the type of its operands: If you add two integers. The Java programming language has one ternary operator. two.

22.out. //adding numbers 34 .(subtraction). then infinity returned if op1 is not zero otherwise NaN if op1 is zero. % op1 % op2 Computes the remainder of dividing op1 by op2 If floating point arithmetic and op2 = 0. public class ArithmeticDemo { public static void main(String[] args) { //a few numbers int i = 37. System.out. double x = 27..out. double y = 7.println(" x = " + x).0. The following table summarizes the binary arithmetic operations in the Java programming language.. / (division).").1 Arithmetic Operators The Java programming language supports various arithmetic operators for all floating-point and integer numbers. These operators are + (addition). System. then NaN returned ArthmeticException thrown if op1 & op2 are integer types and op2 is zero. ArthmeticException thrown if op1 & op2 are integer types and op2 is zero. * (multiplication).println(" i = " + i). Operator + * / op1 op1 op1 op1 Use + – * / op2 op2 op2 op2 Description Adds op1 and op2 Subtracts op2 from op1 Multiplies op1 by op2 Divides op1 by op2 If floating point arithmetic and op2 = 0. System.0 or infinity.out. System.475. int j = 42. System.2. .println(" y = " + y). and % (modulo).out.We divide the operators into these categories: • • • • • • • Arithmetic Operators Increment and decrement operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Conditional or ternary operator 3.println(" j = " + j).println("Variable values.

println(" x % y = " + (x % y)). System. The integer is implicitly converted to a floating-point number before the operation takes place.out.j)).. Data Type of Result long int double float Data Type of Operands Neither operand is a float or a double (integer arithmetic). //computing the remainder resulting from dividing numbers System..out.out.").System."). //multiplying numbers System.. System.. System. System.out.out. based on the data type of the operands.. System. System.println(" i + j = " + (i + j)). //subtracting numbers System.out.out.out.println(" i / j = " + (i / j)). System.println(" i % j = " + (i % j)).println("Multiplying.. at least one operand is a long.println(" i * j = " + (i * j)).out.out.println(" i * x = " + (i * x)).out. At least one operand is a double.y = " + (x .println("Dividing. System. neither operand is a long.println(" j + y = " + (j + y))."). At least one operand is a float. Neither operand is a float or a double (integer arithmetic).out.println("Adding.println(" x . } } Note that when an integer and a floating-point number are used as operands to a single arithmetic operation.println(" x / y = " + (x / y))."). The necessary conversions take place before the operation is performed.println("Computing the remainder.println("Mixing types.out.println("Subtracting.println(" i .out.. each of these operators has unary versions that perform the following operations: Operator Use Description 35 .out..println(" x + y = " + (x + y)). The following table summarizes the data type returned by the arithmetic operators..y))..out.println(" x * y = " + (x * y)). //dividing numbers System.out. System. System.out. neither operand is a double."). //mixing types System.j = " + (i . In addition to the binary forms of + and -.. the result is floating point. System.. System.").

. The postfix version.. op++/op--. evaluates to the value of op after it was incremented op-. evaluates to the value of op before it was decremented --op Decrements op by 1."). Operator ++ ++ --- Use incremented Description op++ Increments op by 1. evaluates to the value of op after it was decremented 3. For example.println(" i = " + i). != returns true if the two operands are unequal. and decrement operator (--)decrements its operand by 1.2 Increment and Decrement Operators Increment operator (++) increments its operand by 1. Either ++ or -. or char -op Arithmetically negates op 3. int j = 42. ++op/--op. short. evaluates to the value of the operand after the increment/decrement operation.2.println("Variable values.out.can appear before (prefix) or after (postfix) its operand. 36 .2.println(" j = " + j). The prefix version. System.Decrements op by 1. System. This table summarizes the relational operators: Operator > >= < <= == != Use op1 > op1 >= op1 < op1 <= op1 == op1 != op2 op2 op2 op2 op2 op2 Returns true if op1 is greater than op2 op1 is greater than or equal to op2 op1 is less than op2 op1 is less than or equal to op2 op1 and op2 are equal op1 and op2 are not equal public class RelationalDemo { public static void main(String[] args) { //a few numbers int i = 37. evaluates the value of the operand before the increment/decrement operation.out. System. int k = 42. evaluates to the value of op before it was ++op Increments op by 1.3 Relational Operators A relational operator compares two values and determines the relationship between them.out.+ - +op Promotes op to int if it's a byte.

println(" k < j = " + (k < j)).println(" k != j = " + (k != j)). System..System.println(" i > System.println(" k >= j = or equal to. System.println(" i != j = " + (i != j)).out..out.println(" k == j = " + (k == j))."). " + (i >= j)).println("Less than.println("Equal to.out.out..out. always evaluates op1 and op2 37 .. } } //false //true //true //false Relational operators often are used with conditional operators to construct more complex decision-making expressions.println("Less than or System.out. The Java programming language supports six conditional operators-five binary and one unary--as shown in the following table.. //less than or equal to System.println(" j <= i = System..println(" j < i = " + (j < i)). System. they are equal //false //true //greater than or equal to System.println(" i <= j = System.out.out.out. than.out. " + (j <= i)).println(" j >= i = System.println(" j > System.out.out..println(" k = " + k).out. System. System.println(" k > //false.println("Greater System.println(" i == j = " + (i == j))."). Operator && || ! & Use op1 && op2 op1 || op2 ! op op1 & op2 Returns true if op1 and op2 are both true.").println("Greater than System. //false " + (j >= i)).. conditionally evaluates op2 op is false op1 and op2 are both true. //greater than System. i = " + (j > i)). //not equal to System. System..out.println(" k <= j = equal to. conditionally evaluates op2 either op1 or op2 is true."). //true //less than System.out.println(" i < j = " + (i < j)).out.out..println("Not equal to.out.out.out. //true //false //false //true //false //true //equal to System. System..println(" i >= j = System.out.").out. j = " + (k > j)). //true " + (k >= j)).out.. " + (k <= j))."). " + (i <= j)). j = " + (i > j)).

or 6 in decimal. For example. Operator >> << >>> Use Operation op1 >> op2 shift bits of op1 right by distance op2 op1 << op2 shift bits of op1 left by distance op2 op1 >>> op2 shift bits of op1 right by distance op2 (unsigned) Each operator shifts the bits of the left-hand operand over by the number of positions indicated by the right-hand operand. always evaluates op1 and op2 if op1 and op2 are different--that is if one or the other of the operands is true but not both 3. The left-hand bits are filled with 0s as needed. op1 op2 0 0 1 1 0 1 0 1 Result 0 0 0 1 38 .2.4 Bitwise Operators A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left. This table summarizes the shift operators available in the Java programming language. The result of the shift operation is 1101 shifted to the right by one position-110. The binary representation of the number 13 is 1101.| ^ op1 | op2 op1 ^ op2 either op1 or op2 is true. The following table shows the four operators the Java programming language provides to perform bitwise functions on their operands: Operator & | ^ ~ Use op1 & op2 op1 | op2 op1 ^ op2 ~op2 Operation bitwise and bitwise or bitwise xor bitwise complement When its operands are numbers. the following statement shifts the bits of the integer 13 to the right by one position: 13 >> 1. as shown in the following table. The AND function sets the resulting bit to 1 if the corresponding bit in both operands is 1. the & operation performs the bitwise AND function on each parallel pair of bits in each operand. The shift occurs in the direction indicated by the operator itself.

Among other things. the | operator performs the inclusive or operation. the AND function sets the resulting bit to 1. Inclusive or means that if either of the two bits is 1. you can see that the two high-order bits (the two bits farthest to the left of each number) of each operand are 1. 39 . To set the "visible" flag when something became visible you would use this statement: flags = flags | VISIBLE. EDITABLE = 8. The following table shows the results of an exclusive or operation. and ^ performs the exclusive or (XOR) operation. The low-order bits evaluate to 0 because either one or both bits in the operands are 0. like this: 13 & 12. and the binary representation of 13 is 1101. otherwise. Thus. the complement operator inverts the value of each bit of the operand: if the operand bit is 1 the result is 0 and if the operand bit is 0 the result is 1. int flags = 0. So. When both of its operands are numbers. bitwise manipulations are useful for managing sets of boolean flags. The following table shows the results of inclusive or operations: op1 op2 0 0 1 1 0 1 0 1 Result 0 1 1 1 Exclusive or means that if the two operand bits are different the result is 1. static static static static final final final final int int int int VISIBLE = 1. otherwise the result is 0. the resulting bit is 0. DRAGGABLE = 2.Suppose that you were to AND the values 13 and 12. The result of this operation is 12 because the binary representation of 12 is 1100. the resulting bit in the result is also 1. 1101 & 1100 -----1100 //13 //12 //12 If both operand bits are 1. the result is 1. op1 op2 0 0 1 1 0 1 0 1 Result 0 1 1 0 And finally. when you line up the two operands and perform the AND function. SELECTABLE = 4.

5 Logical Operators The relational operators you've learned so far (<. DRAGGABLE = 2. <=. you could then write: if ((flags & VISIBLE) == VISIBLE) { . !=.. if ((flags & EDITABLE) == EDITABLE) { System. public static void main(String[] args) { int flags = 0. } } } 3. } } flags = flags | EDITABLE. However what if a particular action is to be taken only if several conditions are true? You can use a sequence of if statements to test the conditions. } A program example is given below: public class BitwiseDemo { static static static static final final final final int int int int VISIBLE = 1.").println("Flags are Visible and Draggable.out.To test for visibility."). >=.println("Flags are now also Editable. if ((flags & VISIBLE) == VISIBLE) { if ((flags & DRAGGABLE) == DRAGGABLE) { System.out.println("Both conditions are true.. flags = flags | DRAGGABLE. EDITABLE = 8.2. >. flags = flags | VISIBLE. SELECTABLE = 4. as follows: if (x == 2) { if (y != 2) { System.out. } } 40 . ==) are sufficient when you only need to check one condition.").

so Java doesn't bother checking the value of c. Java provides an easy way to handle multiple conditions: the logic operators. // b is false c = !(2 > 3). } The Order of Evaluation of Logic Operators When Java sees a && operator or a ||. boolean b. || combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true. || and !. For instance && boolean b. // b is now false is logical or. // b is true These operators allow you to test multiple conditions more easily. b = !(3 > 2). // b is false b = !(2 > 3). however. // b is true 3 || 5 < 7. b = !(3 > 2).out. For example. Thus if b is true !b is false. it first checks whether b is true. // c is true d = b && c. the expression on the left side of the operator is evaluated first. // d is false When Java evaluates the expression d = b && c. For instance || boolean b = 3 > b = 2 > b = 2 > b. && combines two boolean values and returns a boolean which is true if and only if both of its operands are true. b = 3 > 2 && 5 < 7. Here b is false. so b && c must be false regardless of whether c is or is not true.. It reverses the value of a boolean expression. // b is still true 3 || 5 > 7. Fortunately. c. // b is true b = 2 > 3 && 5 < 7. is hard to write and harder to read. For instance the previous example can now be written as if (x == 2 && y != 2) { System. &&. If b is false !b is true. It only gets worse as you add more conditions. // now b is false The last logic operator is ! which means not.This."). is logical and. 41 . consider the following: boolean b.println("Both conditions are true. 2 || 5 < 7. There are three logic operators. d.

This isn't a perfect solution though because m may be 0 or it may be negative. Take the following example. because the left hand side is always evaluated first. the overall calculation will show up as true because only one evaluation must return true to return an overall true. If m is negative and n is zero then m/n is negative infinity which is less than two. The Java approach makes sense if you consider that for an AND. then m/n is very undefined.println("Not equal! "+Output). } else { System. If n is zero then the left hand side is true and there's no need to evaluate the right hand side. boolean b = (n == 0) || (m/n > 2). you decide that what you really want to know is whether m/n is finite and greater than zero you should use a line like this boolean b = (n != 0) && (m/n > 0). if((b1==true) && ((Output+=10)==20)) { System. if the first operand is false it doesn't matter what the second operand evaluates to. For instance consider this code. public class MyClass1{ public static void main(String argv[]){ int Output=10. And if m is also zero. if the first operand has turned out true. If.out. the overall result will be false. Also for a logical OR. Therefore if there's a real chance your program will have a divide by zero error think carefully about what it means and how you should respond to it. } } } 42 . boolean b1 = false.out. The short circuit effect with logical operators The logical operators (&& and ||) have a slightly peculiar effect in that they perform "shortcircuited" logical AND and logical OR operations. This can have an effect with those clever compressed calculations that depend on side effects. Still it's possible to force them.On the other hand when faced with an || Java short circuits the evaluation as soon as it encounters a true value since the resulting expression must be true. Even if n is zero this line will never cause a division by zero.println("We are equal "+Output). upon reflection. Mathematically this makes sense because m/0 is in some sense infinite which is greater than two. This short circuit evaluation is less important in Java than in C because in Java the operands of && and || must be booleans which are unlikely to have side effects that depend on whether or not they are evaluated.

x operation= y is equivalent to x = x operation y x and y must be numeric or char types except for "=". & and | also have a meaning for numeric types which is completely different from their meaning for booleans. You can shorten this statement using the shortcut operator +=. However make sure you use these only on boolean expressions. x must be of the same type of class or interface as y. but it can be an unexpected side effect if you are not completely familiar with it. Suppose you wanted to add a number to a variable and assign the result back into the variable. Unlike && and ||. the rules for mixed types in expressions apply. like this: i += 2. This illustrates that the Output +=10 calculation was never performed because processing stopped after the first operand was evaluated to be false.6 Assignment Operators You use the basic assignment operator.The output will be "Not equal 10". If mixed floating-point and integer types. 3. or bitwise operation and an assignment operation all with one operator. The two previous lines of code are equivalent. The following table lists the shortcut assignment operators and their lengthy equivalents: Operator += -= *= /= op1 op1 op1 op1 Use += -= *= /= op2 op2 op2 op2 Equivalent to op1 op1 op1 op1 = = = = op1 op1 op1 op1 + * / op2 op2 op2 op2 43 . which allows x and y also to be object references. to assign one value to another. The Java programming language also provides several shortcut assignment operators that allow you to perform an arithmetic.. shift. like this: i = i + 2. This may be handy sometimes when you really don't want to process the other operations if any of them return false.2. then you can use & and | instead of && and ||. Avoiding Short Circuits If you want all of your boolean expressions evaluated regardless of the truth value of each. If you change the value of b1 to true processing occurs as you would expect and the output is "We are equal 20". =. In this case.

or b.2. b. In Java you might write if (a > b) { max = a. is returned. (a the second value. and access array elements Used to form qualified names Delimits a comma-separated list of parameters Casts (converts) a value to the specified type Creates a new object or a new array Determines whether its first operand is an instance of its second operand 3. is an expression which returns one of two values.%= &= |= ^= <<= >>= >>>= op1 %= op2 op1 &= op2 op1 |= op2 op1 ^= op2 op1 <<= op2 op1 >>= op2 op1 >>>= op2 op1 = op1 % op2 op1 = op1 & op2 op1 = op1 | op2 op1 = op1 ^ op2 op1 = op1 << op2 op1 = op1 >> op2 op1 = op1 >>> op2 Other Operators Operator ?: [] . } Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it. a > b). The condition. If it is true the first value. Using the conditional operator you can rewrite the above example in a single line like this: max = (a > b) ? a : b. For instance one common operation is setting the value of a variable to the maximum of two quantities. ( params ) ( type ) new instanceof Description Shortcut if-else statement. } else { max = b. ?:. Conditional or ternary operator Used to declare arrays. a. the conditional operator. is 44 . is tested. The value of a variable often depends on whether a particular boolean expression is or is not true and on nothing else. create arrays. (a > b) ? a : b. If it is false.7 Ternary or Conditional operator The ?: operator is a conditional operator that is short-hand for an if-else statement: op1 ? op2 : op3 The ?: operator returns op2 if op1 is true or returns op3 if op1 is false.

) operator accesses instance members of an object or class members of a class. Whichever value is returned is dependent on the conditional test.println("Laugh"). Operator The dot (. or in some other way that indicates the type of its second and third arguments. The conditional operator only works for assigning a value to a variable.2. 3.8 The [ ] Operator You use square brackets to declare arrays. to create arrays.10 The () Operator 45 .out.println("Give back child"). using a value in a method invocation. Here's an example of an array declaration: float[] arrayOfFloats = new float[10]. consider the following if (name. The previous code declares an array that can hold ten floating point numbers. } This may not be written like this: name.9 The . no assignment is present to indicate the type that is expected for the second and third arguments (though you know void must be wrong).println("Laugh"). 3.returned.out.2. a > b. Note that array indices begin at 0.2.out.out. Secondly. You can never use a void method as an argument to the ? : operator. For example. The condition can be any expression which returns a boolean value. The first argument to the conditional operator must have or return boolean type and the second and third arguments must return values compatible with the value the entire expression can be expected to return. 3.println("Give back child") : System.equals("Rumplestiltskin") ? System. and to access a particular element in an array.equals("Rumplestiltskin")) { System. } else { System. both the second and third arguments are void. First of all. Here's how you would access the 7th item in that array: arrayOfFloats[6].

When declaring or calling a method.3 *(4. 46 . Here's an example of creating a new Integer object from the Integer class in the java. declares a variable x and then assigns the value 1 to it.12 The new Operator You use the new operator to create a new object or a new array. For example. then k is incremented by 1 : logical "less than" comparison.1 / Math. This statement x = 5. You can specify an empty argument list by using () with nothing between them.lang package: Integer anInteger = new Integer(10). 3. 2 or 3 operands.cos (0. Examples include: • • • • i = 2 k++ : the assignment puts 2 into the i variable and returns the value 2 : returns k.2.2. 3. x < y i | j Expressions involve at least one operator. you list the method's arguments between ( and ). 3.3 Expressions An expression produces a result and returns a value.13 The instanceof Operator The instanceof operator tests whether its first operand is an instance of its second. op1 3. as well as multiple sub-statements. the statement int x = 1. An object is considered to be an instance of a class if that object directly or indirectly descends from that class.2*y)).2. A single operator can have 1.4 Statements A statement is essentially any complete sentence that causes some action to occur. 3.11 The (type) Operator Casts (or "converts") a value to the specified type. op1 instanceof op2 must be the name of an object and op2 must be the name of a class. It can encompass multiple operators and operands. returns a Boolean true or false value : returns the value of a bitwise OR operation on bits in the two variables.

You must subtract 32 from the Fahrenheit temperature before you multiply by 5/9. 3.5 Operator Precedence Highest Precedence () ++expr --expr +expr -expr ~ ! * / % + << >> >>> < > <= >= instanceof == != & ^ | && || ?: = += -= *= /= %= &= ^= |= <<= >>= >>>= Lowest Precedence Overriding Operator Precedence Parenthesis is used to override operator precedence.multiplication. division. a method call to a math function . // Print a Fahrenheit to Celsius table class FahrToCelsius { public static void main (String args[]) { // lower limit of temperature table double lower = 0. the formula to change a Fahrenheit temperature to a Celsius temperature is C = (5/9) (F .0.0.32) where C is degrees Celsius and F is degrees Fahrenheit.consists of several expressions . Sometimes the default order of evaluation isn't what you want. For instance. // upper limit of temperature table double upper = 300. The next program prints a table showing the conversions from Fahrenheit and Celsius between zero and three hundred degrees Fahrenheit every twenty degrees. // step size 47 . You can use parentheses to adjust the order much as they are used in the above formula.but is still considered a single statement. not after.

48 .8889 140 60 160 71.out. } } } Here's the output: 0 -17.556 260 126. Operator Associativity The following operators have Right to Left associativity. fahr = fahr + step.0.66667 40 4.889 Everything inside the parentheses will be calculated before anything outside of the parentheses is calculated.7778 20 -6. All other operators (see precedence table above) are evaluated left to right. while (fahr <= upper) { double celsius = (5.778 300 148. double fahr = lower.6667 100 37.44444 60 15.0 / 9.7778 120 48.5556 80 26.0) * (fahr-32. System.0).println(fahr + " " + celsius).444 240 115.3333 220 104.667 280 137.double step = 20.2222 200 93.1111 180 82.

put the type BB name in parentheses in front of the type AA data: AA a = aData. the lowest order byte in the int value will be copied to the byte value. the upper bytes will be truncated. i=(int)j. // Cast int as float Expressions can promote to a wider type without an explicit cast: int i=1. That is. as in an int value converted to a short. such as an int value to a byte variable. // Literals are int types so require L suffix j=i. // cast type AA to type BB For example. long j=3L. an explicit cast is required or the compiler will flag an error. // Error in assigning long to int // OK So a data type with lower precision (fewer bits) can be converted to a type of higher precision without explicit casting. If a conversion results in the loss of precision. Note that when you cast a value of a wider type down to a more narrow type. you can not assign a value to a more narrow type without an explicit cast: i=j. however.= *= /= %= += -= <<= >>= >>>= &= ^= |= ?: new (type cast) ++x --x +x -x ~ 3. To convert a higher precision type to a lower precision. 49 .6 Type Conversion and Casting Converting one type of data into another must follow the rules of casting. then the compiler will issue an error message unless an explicit cast is made. BB b = (BB)a. // OK However. to convert integer data to floating point: int i=0. float f. f=(float)i. To convert type AA data into type BB data.

N indicates that the conversion is not allowed.i=3. the other is converted to long. if either operand is of type long.Primitive Type Conversion Table Below is a table that indicates to which of the other primitive types you can cast a given primitive data type. the other is converted to float. Otherwise. for example. The program below uses both ints and doubles. both operands are converted to type int. // OK since i will be promoted to float j= i*y. This result then must be cast if it goes to a lower precision type: float x. The Java VM specification states the following rules for promotion in an expression of two operands. as in x+i: • • • • If either operand is of type double. x= i*y. The symbol A indicates that the precision is increasing so an automatic cast occurs without the need for an explicit cast.y=3. if either operand is of type float. int long float double char byte short boolean int C C C A A A N long A C C A A A N float A* A* C A A A N double A A* A A A A N char C C C C C C N byte C C C C C C N short C C C C C A N boolean N N N N N N N - The * asterisk indicates that the least significant digits may be lost in the conversion even though the target type allows for bigger numbers. int j. The symbol C indicates that an explicit cast is required since the precision is decreasing. Otherwise. Otherwise. // Error since result is a float value j= (int)(i*y) // OK The process of converting a value to a wider or higher precision integer or floating point type is called "numeric promotion". class IntAndDouble { 50 . the other is converted to double. a large value in an int type value that uses all 32 bits will lose some of the lower bits when converted to float since the exponent uses 8 bits of the 32 provided for float values. the lower precision or narrower value operand is converted to a higher precision or wider type. Mixed Types in an Expression If an expression holds a mix of types. For example.

println("i k = i .out.5.5 25 7. 1.75 51 .out.println("i is " + i).5 = 1. especially integer and floating point types.0 3. For example.0 / 2.5 4 0.5 * 1.75 3.out. .5 * 1 / 2 = 1.75 1 / 2.0 / 2 * 3.out.out.75 3.0 / 2 = 1.i is / x is / i is 12.x is . k = i + x. System. / i is " + k).75 You cannot assume that the usual mathematical laws of commutativity apply when mixing data types.0 * 3. This program produces the following output: i x i i i x i x is 10 is 2.println("i k = x . double k. * x is " + k).i.5 -7. System.println("x is " + x).75 3.5 = 0.5 + x is * x is . System.out. 1 / 2 * 3.i is " + k).5 * 1.println("x k = i / x.println("i k = x / i. System. System.public static void main (String args[]) { int i = 10. System.5 / 2 = 1. / x is " + k).25 Order can make a difference when data types are mixed. System.0 = 1.5 = 1.println("i k = i * x.out.println("x } } + x is " + k). double x = 2.x is " + k).x. . System.out.

If neither is a float or a double but one is a long. The basic rule is that if either of the variables in a binary operation (addition. When it's necessary to force a value into a particular type.7 Automatic Type Promotions An int divided by an int is an int. 52 . the fractional part of the floating point number is truncated (rounded toward zero). In an assignment statement. However when it does there will be no warning or error message. multiplication. It can also be hard to find since everything may work perfectly 99 times out of a hundred and only on rare occasions will the rounding become a problem. Therefore the result will be a double. Anything except a double can fit in a float. remainder) are doubles then Java treats both values as doubles. use a cast. and bytes can fit inside ints. floats or longs.0/4. Finally if there are no doubles. float. If the integer is small enough to fit in the left hand side. then Java treats both values as an int. float. subtraction. then Java treats both values as longs. When a value is cast down before assignment. int or long) on the right hand side can fit in the type on the left hand side.2E18 will be a perfectly valid double but much too big for any int. Java compares the type of the left hand side to the final type of the right hand side.0). After all 3 * 54. A cast lets the compiler know that you're serious about the conversion you plan to make. but what about an int divided by a double or a double divided by an int? When doing arithmetic on unlike types Java tends to widen the types involved so as to avoid losing information.e. In fact it's so troublesome the compiler won't let you do it unless you tell it you really mean it with a cast. If neither value is a double but one is a float. then the integer is set to the largest possible value of its type. If the right hand side can fit inside the left hand side. For instance: int i = (int) (9. series of operations takes place to chop the right hand side down to size. For a conversion between a floating point number and an int or a long. This can be a nasty bug in your code. addition. the assignment takes place with no further ado. shorts. On the other hand if the number is too large. Any integral type can fit in a long. if there's an equals sign. even if there aren't any ints in the equation. Assigning long values to int variables or double values to float variables can be equally troublesome. This produces an integer. Anything can fit in a double. then Java treats both values as floats. but a float or a double can't. but it will check to make sure that the value it has (double. If the floating point number is too small the integer is set to the smallest possible value of its type. and ints. To cast a variable or a literal or an expression to a different data type just precede it with the type in parentheses. and a double divided by a double is a double. i. long or int depending on the types of the arguments. It won't change the type of the left hand side. the assignment is completed.3. You need to be very careful when assigning floating point values to integer types.

0 Prints: 0.3 Prints: 3. c.print(a + ". Questions 1. // 3 char d = 0x0031. int c = 1 || (2 ^ (3 && 5)).Summary This chapter discussed the operators that you can use in Java to manipulate the values of variables.3. } 53 . // 4 char e = '\u0031'. Run-time error f.0. the relational operators.0 Prints: 0. Prints: null 2. None of the above } public static void main (String[] args) { int a = 1 || 2 ^ 3 && 5. Finally it discussed the concept of operator precedence that defined the rules by which the order of operators is evaluated. None of the above 3.0 Prints: 3. and the shift operators. Prints an undefined value.out.println(x+y+z). int b = ((1 || 2) ^ 3) && 5. the bit-wise operators. } What is the result of attempting to compile and run the program? a.out.3. Compile-time error g.0. Prints nothing.z. h.0. Run-time error j.0 Prints: 3. d. It included all the standard arithmetic operators. class MCZ24 { public static void main (String[] args) { char a = 061. the increment and decrement operators. c. class EBH201 { d. class GFM11{ } public static void main (String[] args) { int x. Compile-time error k.3. System." + c). // 5 System. b. Prints: 0 e.print(""+a+b+c+d+e).y. System. } What is the result of attempting to compile and run the program? a. g.3 e.out." + b + ". f. Prints: 0. Prints: 3. // 2 char c = '\061'.3 i.3.0. b.3 Prints: 0. // 1 char b = '\61'.

c. d. e. f. b. 1 2 3 4 5 None of the above 54 .} A compile-time error is generated at which line? a.

4.true c. None of the above 6. Prints: 10 f. class EBH106 { public static void main(String args[]) { int a = 1.").println(b<<33). Prints: 7 f. Prints: -1 b. Compile-time error h. } } What is the result of attempting to compile and run the program? a.print((y % x) + ".true e. Prints: true. class EBH007{ } public static void main (String[] s) { byte b = 5. 55 . Prints: 0 c. class EBH014 { public static void main (String[] args) { byte x = 3. Prints: 3 b. Prints: 6 e. } } What is the result of attempting to compile and run the above program? a. Prints: 5 e.out. Compile-time error h.false d. System. Prints: false. Prints: 4 c. Prints: 1 d. None of the above 7. class EBH012 { public static void main (String[] args) { byte x = 3. Run-time error f. Prints: 5 d. System.out. Run-time error g. a += ++a + a++."+(-y == ~y + 1)). Prints: true.print(a). Run-time error g. y = 5. None of the above 5.false b.out. System. System. y = 5. Compile-time error g.print((-x == ~x + 1)+".out. } What is the result of attempting to compile and run the program? a. Prints: false.

What is the result of attempting to compile and run the program? a.print(y == ((y/x)*x + (y%x))).} } System.println(m1(b1) + m1(b2) + m1(b3)). k. Prints: FFF Prints: FFT Prints: FTF Prints: FTT e. Run-time error Compile-time error None of the above 56 . None of the above 8.false e. class EBH023 { static String m1(boolean b){return b?"T":"F". } } What is the result of attempting to compile and run the program? a.true b. System. Prints: 1. c. Prints: 1. Run-time error f.false d.out. Prints: TFF Prints: TFT Prints: TTF Prints: TTT i. boolean b3 = ((false?false:true)?false:true)?false:true. Compile-time error g.true c. Prints: 2. boolean b2 = false?false:(true?false:(true?false:true)). g. j. Prints: 2. f. d.out. h.} public static void main(String [] args) { boolean b1 = false?false:true?false:true?false:true. b.

return try-catch-finally. } } 57 . to repeatedly execute a block of statements. sequential flow of control.out. the while statement evaluates expression. and to otherwise change the normal. you will see the following notation to describe the general form of a control flow statement: control flow statement details { statement(s) } Technically. because the code is easier to read and it helps to prevent errors when modifying code. the interpreter executes these statements in the order they appear in the file from left to right. You can use control flow statements in your programs to conditionally execute statements. throws. top to bottom. { and }. while (x != 0) { System. do-while . public class WhileDemo { public static void main(String[] args) { int x=10.Chapter 4 : Control flow statements Without control flow statements.println(x--). for if-else. the braces. then the while statement executes the statement(s) associated with it. we recommend that you always use { and }. are not required if the block contains only one statement. which must return a boolean value. However. label:. continue. 4. The while statement continues testing the expression and executing its block until the expression returns false. switch-case break.1 The while and do-while Statements You use a while statement to continually execute a block of statements while a condition remains true. Statement Type looping decision making branching exception handling Keyword while. If the expression returns true.throw In the sections that follow. The general syntax of the while statement is: while (expression) { statement } First.

the loop terminates. } } This program prints numbers from 10 to 0 in the descending order 4. . All these components are optional. 58 . } while(x != 0). increment) { statement } The initialization is an expression that initializes the loop-it's executed once at the beginning of the loop.println(x--). increment is an expression that gets invoked after each iteration through the loop.. The general syntax of the do-while is: do { statement(s) } while (expression). When the expression evaluates to false. assigning values to its elements. do-while evaluates the expression at the bottom.. The general form of the for statement can be expressed like this: for (initialization.} This program prints numbers from 10 to 1 in the descending order The Java programming language provides another statement that is similar to the while statement--the do-while statement. The termination expression determines when to terminate the loop. Finally. to write an infinite loop. Thus the statements associated with a do-while are executed at least once. In fact. do { System. termination. This expression is evaluated at the top of each iteration of the loop. Instead of evaluating the expression at the top of the loop. public class DoWhileDemo { public static void main(String[] args) { int x=10. you omit all three expressions: for ( . ) { .out. The for loop uses anArray.2 The for Statement The for statement provides a compact way to iterate over a range of values. } // infinite loop The for loop in the sample program iterates over each element of anArray.length to determine when to terminate the loop.

// declare an array of integers anArray = new int[10]. The scope of this variable extends from its declaration to the end of the block governed by the for statement so it can be used in the termination and increment expressions as well.out. } } for(int i = 0 . public class ForDemo { public static void main(String[] args) { int[] arrayOfInts = { 32. 87. declaring them within the for loop initialization expression limits their life-span and reduces errors.print(anArray[i] + " "). that creates the array. i++) { for (int j = 0. i < 3 . and k are often used to control for loops.out. j < 5 . puts some values in it.Here's a simple program. for(int i = 0 . i++) { System. } } Note that you can declare a local variable within the initialization expression of a for loop. 12. 2000. j. i < anArray. The names i. The expression x[i] selects the ith one-dimensional array. 127 }.out. i++) { 59 . and displays the values. // create an array of integers // assign a value to each array element and print for (int i = 0. it's best to declare the variable in the initialization expression. 622. 3. public class ArrayDemo { public static void main(String[] args) { int[] anArray. i++) { anArray[i] = i. j++) { x[i][j] = k++. i < arrayOfInts. 8.println().length . } System. for (int i = 0.out.length. } System. 1076. called ArrayDemo. the expression x[i][j] selects the jth element from that array. public class ArrayofArraysDemo1 { public static void main(String args[]) { int [] [] x = new int [3][5].println().length. 589. If the variable that controls a for loop is not needed outside of the loop. or the characters in a string. } } Often for loops are used to iterate over the elements in an array. i < x. int k=0. System.print(arrayOfInts[i] + " ").

out. 4. If it isn't raining then you don't.for (int j = 0. All programming languages have some form of an if statement that tests conditions. 589. 622.. This is quite common in real life. } } } Enhanced for loop (added with Java 5..0) for (type value : container) statement This for statement was created especially for collections and arrays.length . 1076. This is the simplest version of the if statement: The block governed by the if is executed if a condition is true. 8. 127 }. j++) { System. They test a condition and operate differently based on the outcome of the test.out. } System. 87.println(). 3.print(element + " "). } } You can read the for statement in the preceding snippet like this: For each int element in arrayOfInts. the simple form of if can be written like this: if (expression) { statement(s) } 60 . Generally. 12. for (int element : arrayOfInts) { System. An example to print all elements in the array. j < x[i].out. public class ForEachDemo { public static void main(String[] args) { int[] arrayOfInts = { 32. 2000.3 The if/else Statements All but the most trivial computer programs need to make decisions.out.println(). For instance you stick your hand out the window to test if it's raining. If it is raining then you take an umbrella with you.print(x[i][j] + ‘\t’). } System.

that is something that evaluates to true or false.out. if (b = false) { System.The arguments to a conditional statement like if must be a boolean value. you are not allowed to use == and = in the same places. Integers are not permissible. Using the else statement class HelloProgram { public static void main(String args[]) { int x=10. if(x%10 == 0) { System. } To avoid this. } Since you can't assign to a literal.println(“Number is divisible by 10”). It's not uncommon for even experienced programmers to write == when they mean = or vice versa. Therefore the compiler can catch your mistake and make you fix it before you can run the program.out.println("b is false").println("b is false").println(“Number is divisible by 10”).out. some programmers get in the habit of writing condition tests like this: boolean b = true. } } } In Java numerical greater than and lesser than tests are done with the > and < operators respectively. You can test whether a number is less than or equal to or greater than or equal to another number with the <= and >= operators. if (false = b) { System. Fortunately in Java. if(x%10 == 0) { System. } else { System. class HelloProgram { public static void main(String args[]) { int x=10.println(“Number is not divisible by 10”).out. this causes a compiler error if you misuse the = sign when you mean to write ==. } } 61 . However there is one way you can still get into trouble: boolean b = true.out.

Some forms are given below 1.out.. if(condition){ // code to run if(condition){ // code to run } } else{ // other code to run } 3.else statement into an if block or an else block. boolean flag = true. if (flag) { int flag2 = 1. } else { System. if (flag2 < 0) { // Do something! } else { // Do something! } } else { // Do something! } Example: if (i == j) { if (j == k) System.out.. } 62 .println("i equals k")..else statement. There can be any level of nested if.println("i doesn't equal j").} Nested if/else statements Nested if. if(condition){ // code to run if(condition){ // code to run } else { // other code to run } } 2.else statement is writing an if.

case 4: System. switch (month) { case 1: System. case 12: System.out.println("July").4 The switch Statement Use the switch statement to conditionally perform statements based on an integer expression.out. break.println("May"). break..println("October"). } else if (testscore >= 80) grade = 'B'. public class SwitchDemo { public static void main(String[] args) { int month = 8.println("June"). case 8: System. case 6: System.out. break. An if statement can have any number of companion else if statements but only one else. char grade. } System. break.println("August"). public class IfElseDemo { public static void main(String[] args) { int testscore = 76. case 11: System.println("Grade = { { { } } " + grade).println("April").out.out.println("September"). if (testscore >= 90) { grade = 'A'. case 9: System. } else { grade = 'F'. } else if (testscore >= 70) grade = 'C'.println("January").else if ladder The else block is executed if the if part is false. 4.out. executes a statement based on another expression.println("March"). break. Another form of the else statement.println("December"). break.out. break. case 3: System.out.out.out. } } } 63 . break.out. case 2: System. } else if (testscore >= 60) grade = 'D'.if.println("February"). break.println("November"). break. break. case 10: System. break. else if. case 5: System.out. case 7: System.out.

That is. switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31. Another point of interest in the switch statement is the break statement after each case. . // and so on Deciding whether to use an if statement or a switch statement is a judgment call. case 2: if (((year % 4 == 0) && !(year % 100 == 0)) 64 .println("January"). } else if (month == 2) { System. . Also. in this case the value of month. control will flow sequentially through subsequent case statements. the value provided to each case statement must be unique. You can decide which to use. int month = 8.The switch statement evaluates its expression.out. without an explicit break. and executes the appropriate case statement. case 4: case 6: case 9: case 11: numDays = 30. whereas a switch statement can make decisions based only on a single integer value. if (month == 1) { System. An if statement can be used to make decisions based on ranges of values or conditions. break. the case statements fall through.println("February"). public class SwitchDemo2 { public static void main(String[] args) { int month = 2. The break statements are necessary because without them. Each break statement terminates the enclosing switch statement. int year = 2000. break. and the flow of control continues with the first statement following the switch block. } . based on readability and other factors.out. int numDays = 0.

|| (year % 400 == 0) ) numDays = 29; else numDays = 28; break;

} }

} System.out.println("Number of Days = " + numDays);

Technically, the final break is not required because flow would fall out of the switch statement anyway. However, we recommend using a break for the last case statement just in case you need to add more case statements at a later date. This makes modifying the code easier and less error-prone. Finally, you can use the default statement at the end of the switch to handle all values that aren't explicitly handled by one of the case statements. The variable or expression in the switch statement can be of only int or byte or short or char data types.

4.5 Branching Statements
The Java programming language supports three branching statements: • The break statement • The continue statement • The return statement label is an identifier placed before a statement. The label is followed by a colon (:): statementName: someJavaStatement;

4.5.1 The break Statement
The break statement has two forms: unlabeled and labeled. An unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. You can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop.
public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int searchfor = 12; int i = 0; boolean foundIt = false; for ( ; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true;

65

} }

break;

if (foundIt) { System.out.println("Found "+ searchfor +" at index "+ i); } else { System.out.println(searchfor + "not in the array"); } } }

The break statement terminates the labeled statement; it does not transfer the flow of control to the label. The flow of control transfers to the statement immediately following the labeled (terminated) statement.
public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i = 0; int j = 0; boolean foundIt = false; search: for ( ; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } if (foundIt) { System.out.println("Found "+searchfor+" at "+i+", " + j); } else { System.out.println(searchfor + "not in the array"); } } }

4.5.2 The continue Statement

66

You use the continue statement to skip the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop, basically skipping the remainder of this iteration of the loop. The labeled form of the continue statement skips the current iteration of an outer loop marked with the given label. A continue statement returns to the beginning of the innermost enclosing loop without completing the rest of the statements in the body of the loop. If you're in a for loop, the counter is incremented. For example this code fragment skips even elements of an array
for (int i = 0; i < m.length; i++) { if (m[i] % 2 == 0) continue; // process odd elements... }

The continue statement is rarely used in practice, perhaps because most of the instances where it's useful have simpler implementations. For instance, the above fragment could equally well have been written as
for (int i = 0; i < m.length; i++) { if (m[i] % 2 != 0) { // process odd elements... } }

continue with label
public class ContinueWithLabelDemo { public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n-- != 0) { if (searchMe.charAt(j++) != substring.charAt(k++)) { continue test; } } foundIt = true;

67

break test; } System.out.println(foundIt ? "Found it" : "Didn't find it"); } }

Here is the output from this program:
Found it

4.5.3 The return Statement
You use return to exit from the current method. The flow of control returns to the statement that follows the original method call. The return statement has two forms: one that returns a value and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword:
return ++count;

The data type of the value returned by return must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value:
return;

4.6 Exception Handling Statements
The Java programming language provides a mechanism known as exceptions to help programs report and handle errors. When an error occurs, the program throws an exception. It means that the normal flow of the program is interrupted and that the runtime environment attempts to find an exception handler--a block of code that can handle a particular type of error. The exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a gentle exit from the program. Three statements play a part in handling exceptions:
• •

The try statement identifies a block of statements within which an exception might be thrown. The catch statement must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the try block. The finally statement must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block.

Here's the general form of these statements:

68

try { statement(s) } catch (exceptiontype name) { statement(s) } finally { statement(s) }

Summary
For controlling the flow of a program, the Java programming language has three loop constructs, a flexible if-else statement, a switch statement, exception-handling statements, and branching statements. Use the while statement to loop over a block of statements while a boolean expression remains true. Use the do-while statement to loop over a block of statements while a boolean expression remains true. The expression is evaluated at the bottom of the loop, so the statements within the do-while block execute at least once. The for statement loops over a block of statements and includes an initialization expression, a termination condition expression, and an increment expression The Java programming language has two decision-making statements: if-else and switch. The more general-purpose statement is if; use switch to make multiple-choice decisions based on a single integer value. Some branching statements change the flow of control in a program to a labeled statement. You label a statement by placing a legal identifier (the label) followed by a colon ( :) before the statemen. Use the unlabeled form of the break statement to terminate the innermost switch, for, while, or do-while statement. Use the labeled form of the break statement to terminate an outer switch, for, while, or do-while statement with the given label. A continue statement terminates the current iteration of the innermost loop and evaluates the boolean expression that controls the loop. The labeled form of the continue statement skips the current iteration of the loop with the given label. Use return to terminate the current method. You can return a value to the method's caller, by using the form of return that takes a value.

Questions
1. class Black {

}

public static void main(String args[]) { int[] i = {1,2,3,4,5}; long[] l = new long[5]; for (int j = 0; j < l.length(); j++) { l[j] = i[j]; } }

// // // //

1 2 3 4

69

A compile-time error is generated at which line? a. b. c. d. e. 1 2 3 4 None of the above

70

2. class MWC206 {

}

public static void main (String[] args) { int[][] a1 = {{1,2,3},{4,5,6},{7,8,9}}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(a1[j][i]); } } }

What is the result of attempting to compile and run the program? a. Prints: 123456789 b. Prints: 147258369 c. Prints: 321654987
3. class JMM102 {

d. Prints: 369258147 e. Run-time error f. Compile-time error

g. None of the above

public static void main(String args[]) { for (int i = 0; i<5 ;i++) { switch(i) { case 0: System.out.print("v ");break; case 1: System.out.print("w "); case 2: System.out.print("x ");break; case 3: System.out.print("y "); case 4: System.out.print("z ");break; default: System.out.print("d "); } } } }

What is the result of attempting to compile and run the program? a. Prints: v w x y z b. Prints: v w x y z d c. Prints: v w x x y z z
4. class JMM105 {

d. Prints: v w w x y y z d e. Prints: d d d d d d f. Run-time error
{

g. Compile-time error h. None of the above

public static void main(String args[]) int x = 6; int success = 0; do { switch(x) { case 0: System.out.print("0"); case 1: System.out.print("1"); case 2: System.out.print("2"); case 3: System.out.print("3"); case 4: System.out.print("4");

x += 5; break; x += 3; break; x += 1; break; success++; break; x -= 1; break;

71

case 5: System.out.print("5"); x -= 4; break; case 6: System.out.print("6"); x -= 5; break; } } while ((x != 3) || (success < 2)); } }

What is the result of attempting to compile and run the program? a. Prints: 60514233 b. Prints: 6152433 c. Prints: 61433 d. Prints: 6143 e. Run-time error f. Compile-time error

72

A method is a function (subroutine) associated with an object. of the object. an object can be easily passed around in the system. 73 .Chapter 5 : Class Fundamentals and OOP 5. A particular object is called an instance. The access level determines which other objects and classes can access that variable or method. Also. The following illustration is a common visual representation of a software object: Everything that the software object knows (state) and can do (behavior) is expressed by the variables and the methods within that object. Encapsulating related variables and methods into a neat software bundle is a simple yet powerful idea that provides two primary benefits to software developers: • • Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Software objects are modeled after real-world objects in that they too have state and behavior. The object can maintain private information and methods that can be changed at any time without affecting the other objects that depend on it. Methods surround and hide the object's nucleus from other objects in the program.1 What Is an Object? The real-world objects share two characteristics: They all have state and behavior. Information hiding: An object has a public interface that other objects can use to communicate with it. The object diagrams show that the object's variables make up the center. or nucleus. A software object implements its behavior with methods. Packaging an object's variables within the protective custody of its methods is called encapsulation This conceptual picture of an object-a nucleus of variables packaged within a protective membrane of methods-is an ideal representation of an object and is the ideal that designers of object-oriented systems strive for. You can represent real-world objects by using software objects. A software object maintains its state in one or more variables.

The next figure shows the three parts of a message: 74 . Object is an instance of the class. when you want to change gears on your bicycle. When object A wants object B to perform one of B's methods. or prototype. Your bicycle hanging from a hook in the garage is just a bunch of metal and rubber. Sometimes. that defines the variables and the methods common to all objects of a certain kind.2 What Is a Class? A class is a blueprint. all Java code occurs within a class.5. the bicycle is incapable of any activity. Software objects interact and communicate with each other by sending messages to each other. by itself. Instead. programmers achieve higher-order functionality and more complex behavior. There is no concept of free standing code and even the most simple application involves the creation of a class.3 What Is a Message? A single object alone is generally not very useful. Through the interaction of these objects. for example. the receiving object needs more information so that it knows exactly what to do. an object usually appears as a component of a larger program or application that contains many other objects. you have to indicate which gear you want. The role of classes in Java Classes are the heart of Java. 5. object A sends a message to object B (see the following figure). This information is passed along with the message as parameters. The bicycle is useful only when another object (you) interacts with it (pedal).

and minimising it makes for more reusable and maintainable classes.1 Encapsulation Encapsulation is the principal of keeping the internal details of a classes state and behaviours hidden from the other classes that use it. 5.4. The interconnectness between pieces of code is called 'coupling'. Objects don't need to be in the same process or even on the same machine to send and receive messages back and forth to each other. No other information or context is required. without breaking compatibility.4 Features of Object Oriented Programming There are four features of OOP. Messages provide two important benefits. You do not want to 75 .   An object's behavior is expressed through its methods. This allows you to change those details where necessary. The expectated behaviour of a class or method is referred to as its 'contract'. so (aside from direct variable access) message passing supports all possible interactions between objects.• • • The object to which the message is addressed (YourBicycle) The name of the method to perform (changeGears) Any parameters needed by the method (lowerGear) These three components are enough information for the receiving object to perform the desired method.  Encapsulation  Inheritance  Polymorphism  Abstraction 5.

Similarly. To achieve good encapsulation. and tandems are all subclasses of the bicycle class. and in all likelyhood.4. and tandems are all kinds of bicycles. make everything have the tightest possible access control so if something should not be used in a given context. road bikes. Encapsulation involves hiding data of a class and allowing access only through a public interface. road bikes. road bikes. for example. Also. and tandems share some states: cadence.if the internal details of a class are exposed and used.2 Inheritance Generally speaking. In object-oriented terminology. each subclass inherits methods from the superclass. mountain bikes. limit the access to prohibit it. and tandems share some behaviors: braking and changing pedaling speed. the bicycle class is the superclass of mountain bikes. 5.expose any more than the minimum required to support the contract. 76 . Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. Even if you don't know what a penny-farthing is. speed. handle bars. mountain bikes. or you can end up with tangled interdependent code with poor maintainabilty. objects are defined in terms of classes. You know a lot about an object by knowing its class. you would know that it had two wheels. Each subclass inherits state and behavior from the superclass. and the like. and pedals. For example. This relationship is shown in the following figure. Mountain bikes. if we tell you it was a bicycle. Encapsulation also aids polymorphism and inheritance . road bikes. Mountain bikes. road bikes. and tandems. poor quality. it is very hard to substitute a different implementation of the same contract.

and each class is its descendant (directly or indirectly). Subclasses can also override inherited methods and provide specialized implementations for those methods. you would require three different sets of stack routines. A variable of type Object can hold a reference to any object. it might be convenient to make it a subclass of the bicycle class — after all." It allows one interface to be used for a general class of action. This helps 77 . and make updating or improving the tricycle class difficult. with each set using different names. This means that it is possible to design a generic interface to a group of related activities. Other programmers fill in the details with specialized subclasses. it's unwise to publicly tie the two classes together. can be as deep as needed. both tricycles and bicycles have a current speed and cadence — but because a tricycle is not a bicycle. However. The Object class is at the top of class hierarchy. The algorithm that implements each stack is same. the farther down in the hierarchy a class appears. such as an instance of a class or an array. but much of the class is undefined and unimplemented. The specific action is determined by the exact nature of the situation. Object provides behaviors that are required of all objects running in the Java Virtual Machine. Programmers can implement superclasses called abstract classes that define "generic" behaviors. programmers can reuse the code in the superclass many times. In general. One stack is used for integer values. Inheritance offers the following benefits:  Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Note: Class hierarchies should reflect what the classes are. If we implemented a tricycle class. The abstract superclass defines and may partially implement the behavior. In an non-object-oriented-programming language. Subclasses can add variables and methods to the ones they inherit from the superclass.4. the more specialized its behavior. multiple methods”.3 Polymorphism The word polymorphism comes from the Greek for "many forms. or class hierarchy. Methods and variables are inherited down through the levels. because of polymorphism. subclasses are not limited to the state and behaviors provided to them by their superclass.  5. in Java you can specify a general set of stack routines that all share same names. The concept of polymorphism is expressed by the phrase “one interface.However. make the tricycle class have methods (such as "change gears") that it doesn't need. Consider a stack. even though the data being stored is different. The inheritance tree. It could confuse users. one for floating point values and one for characters. Through the use of inheritance. You might have a program that requires three types of stacks.

5. such as: 78 . class MyClassName{ . The declared type is an interface which the object's class implements: MyInterface myObject = new MyClass().5 Defining Classes The general syntax for defining a class in Java is shown below. For example. Abstraction is hiding the irrelevant details and knowing only the relevant ones. . You can also declare a variable on its own line.4 Abstraction Humans manage complexity through abstraction.6 Creating Objects Declaring a Variable to Refer to an Object The declared type matches the class of the object: MyClass myObject = new MyClass(). } //End of class definition. This syntax defines a class and creates a new type named MyClassName. 5. They think of it as a well defined object with its own unique behavior. You do not need to make the selection manually. Polymorphism in Java is implemented with Method Overloading and Overriding. transmission. and braking systems work.4. The declared type is a parent class of the object's class: MyParent myObject = new MyClass(). This abstraction allows people to use a car to drive to the grocery store without being overwhelmed by the complexity of thje parts that form the car. They can ignore the details of how the engine. 5. Instead they are free to utilize the object as a whole.e method) as it applies to each situation. You need only remember to utilize the general interface. .reduce complexity by allowing the same interface to be used to specify a general class of action. people do not think of a car as a set of tens of thousands of individual parts. It is the compiler’s job to select the specific action (i.

When you create an object. you can think of the two as being synonymous. variable declaration alone does not actually create an object. the object is unreachable after the statement in which the new operator appears finishes executing. the value of myObject will be automatically set to null until an object is actually created and assigned to it. its return type must be void. Note: The phrase "instantiating a class" means the same thing as "creating an object". The new operator requires a single.MyClass myObject. postfix argument: a call to a constructor. If the method does not return a value.7 Defining Methods in a class Classes usually consists of two things: instance variables and methods. If the method has no parameters. The parameter-list is a sequence of type and identifier pairs separated by commas. Often. then the parameter list will be empty. This can be any valid type. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. Instantiating a Class The new operator instantiates a class by allocating memory for a new object. including class types that you create. This can be any legal identifier other than those already used by other items within the current scope. The name of the method is specified by name. Method Declaration Elements Function (Optional) Access level for the method (Optional) Declares a class method Element accessLevel static 79 . A variable in this state. The general form of a method is as follows: type name (parameter-list) { // body of method } The type specifies the return type of the method. 5. The constructor initializes the new object. is said to hold a null reference. you are creating an instance of a class. The name of the constructor provides the name of the class to instantiate. The new operator returns a reference to the object it created. this reference is assigned to a variable of the appropriate type. If the reference is not assigned to a variable. which currently references no object. therefore "instantiating" a class. Remember. When you use this approach.

abstract final native synchronized returnType methodName ( paramList ) throws exceptions

(Optional) Indicates that the method is not implemented (Optional) Indicates that the method cannot be overridden (Optional) Indicates that the method is implemented in another language (Optional) The method requires a monitor to run The method's return type and name The list of arguments to the method (Optional) The exceptions thrown by the method

Each element of a method declaration can be further defined and is discussed as indicated in the following list: accessLevel As with member variables, you control which other classes have access to a method using one of four access levels: public, protected, package, and private
static

As with member variables, static declares this method as a class method rather than an instance method.
abstract

An abstract method has no implementation and must be a member of an abstract class.
final

A final method cannot be overridden by subclasses
native

If you have a significant library of functions written in another language, such as C, you may wish to preserve that investment and to use those functions from a program written in the Java programming language. Methods implemented in another language are called native methods and are declared as such using the native keyword
synchronized

Concurrently running threads often invoke methods that operate on the same data. Mark these methods with the synchronized keyword to ensure that the threads access information in a thread-safe manner. returnType A method must declare the data type of the value that it returns. If your method does not return a value, use the keyword void for the return type. methodName A method name can be any legal identifier. You need to consider code conventions, name overloading, and method overriding when naming a method.
( paramlist )

You pass information into a method through its arguments.

80

throws exceptionList

If your method throws any checked exceptions, your method declaration must indicate the type of those exceptions. Two of these components comprise the method signature: the method's name and the parameter list. Methods that have return type other than void return a value to the calling routine using the following form of return statement: return value; Here, value is the value returned. Let’s add a method to a Box class.
class Box { double width, height, depth; void volume() { System.out.println(“Volume is :”+ (width * depth * height)); } } class BoxDemo { public static void main(String args[]) { Box mybox1 = new Box(); mybox1.width = 10; mybox1.height = 20; mybox1.depth = 30; mybox1.volume(); } }

Naming a Method Although a method name can be any legal identifier, code conventions restrict method names. In general, method names should be verbs and should be in mixed case, with the first letter in lowercase and the first letter of each internal word in uppercase. Here are some examples:
toString compareTo isDefined setX getX

81

The JavaBeans architecture naming conventions further describe how to name methods for setting and getting properties. Passing information to a method The declaration for a method declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:
public double computePayment(double loanAmt, double rate, double futureValue, int numPeriods) { double I, partial1, denominator, answer; I = rate / 100.0; partial1 = Math.pow((1 + I), (0.0 - numPeriods)); denominator = (1 - partial1) / I; answer = ((-1 * loanAmt) / denominator) - ((futureValue * partial1) / denominator); return answer; }

This method takes four arguments: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. As with this method, the set of arguments to any method or constructor is a comma-separated list of variable declarations, where each variable declaration is a type/name pair. As you can see from the body of the computePayment method, you simply use the argument name to refer to the argument's value. Argument Types You can pass an argument of any data type into a method. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as classes and arrays. Here's an example of a factory method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from a list of Points (assume that Point is a class that represents an x, y coordinate):
public Polygon polygonFrom(Point[] listOfPoints) { ... }

The Java programming language doesn't let you pass methods into methods. But you can pass an object into a method and then invoke the object's methods. Argument Names

82

When you declare an argument to a method, you provide a name for that argument. This name is used within the method body to refer to the data. The name of an argument must be unique in its scope. It cannot be the same as the name of another argument for the same method or constructor, the name of a local variable within the method or constructor, or the name of any parameter to a catch clause within the same method or constructor. An argument can have the same name as one of the class's member variables. If this is the case, the argument is said to shadow the member variable. Shadowing member variables can make your code difficult to read and is conventionally used only within methods that set a particular member variable. For example, consider the following Circle class and its setOrigin method:
public class Circle { private int x, y, radius; public void setOrigin(int x, int y) { ... } }

The Circle class has three member variables: x, y, and radius. The setOrigin method accepts two arguments, each of which has the same name as one of the member variables. Each method argument shadows the member variable that shares its name. So using the simple names x or y within the body of the method refers to the argument, not to the member variable. To access the member variable, you must use a qualified name. Returning a Value from a Method You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value and cannot contain a return statement. Any method that is not declared void must contain a return statement. Let's look at the isEmpty method in the Stack class:
public boolean isEmpty() { if (items.size() == 0) { return true; } else { return false; } }

The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean. The declared return type for the isEmpty method is boolean, and the implementation of the method returns the boolean value true or false, depending on the outcome of a test.

83

The isEmpty method returns a primitive type. A method can return a reference type. For example, Stack declares the pop method that returns the Object reference type:
public Object pop() { if (top == 0) { throw new EmptyStackException(); } Object obj = items[--top]; items[top]=null; return obj; }

When a method uses a class name as its return type, such as pop does, the class of the type of the returned object must be either a subclass of or the exact class of the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number, which is in turn a subclass of Object, as illustrated in the following figure.

Now suppose that you have a method declared to return a Number:
public Number returnANumber() { ... }

The returnANumber method can return an ImaginaryNumber but not an Object. ImaginaryNumber is a Number because it's a subclass of Number. However, an Object is not necessarily a Number — it could be a String or another type. You also can use interface names as return types. In this case, the object returned must implement the specified interface.

5.8 Declaring Variables in a Class
Stack

uses the following line of code to define its variables:
class Stack { int top; }

This code declares member variable and not other types of variable, such as local variable, because the declaration appears within the class body but outside any methods.

84

Element
accessLeve l static final transient volatile type name

Variable Declaration Elements Function (Optional) Access level for the variable (Optional) Declares a class variable (Optional) Indicates that the variable is a constant (Optional) Indicates that the variable is transient (Optional) Indicates that the variable is volatile The type and name of the variable

Each component of a member variable declaration is further defined and discussed in later sections of this chapter, as follows: accessLevel Lets you control what other classes have access to a member variable by specifying one of four access levels: public, protected, package, and private.
static

Declares this is a class variable rather than an instance variable.
final

Indicates that the value of this member cannot change.
transient

Marks member variables that should not be serialized.
volatile

Prevents the compiler from performing certain optimizations on a member type Like other variables, a member variable must have a type. You can use primitive type names such as int, float, or boolean. Or you can use reference types, such as array, object, or interface names. name A member variable's name can be any legal identifier and, by convention, begins with a lowercase letter. A member variable cannot have the same name as any other member variable in the same class.

Automatic local variables Automatic variables are method variables. They come into scope when the method code starts to execute and cease to exist once the method goes out of scope. As they are only visible within the

85

method they are typically useful for temporary manipulation of data. If you want a value to persist between calls to a method then a variable needs to be created at class level. Variable Initialization Local variables and member variables can be initialized with an assignment statement when they're declared. Local variables have to explicitly initialized before their use. The data type of the variable must match the data type of the value assigned to it.
char aChar = 'S'; boolean aBoolean = true;

Parameters and exception-handler parameters cannot be initialized in this way. The value for a parameter is set by the caller. Variable Scope A variable's scope is the region of a program within which the variable can be referred to by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable. Scope is distinct from visibility, which applies only to member variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an access modifier. The location of the variable declaration within your program establishes its scope and places it into one of these four categories:
• • • •

member variable local variable method parameter exception-handler parameter

A member variable is a member of a class or an object. It is declared within a class but outside of any method or constructor. A member variable's scope is the entire declaration of the class. However, the declaration of a member needs to appear before it is used when the use is in a member initialization expression.

86

You declare local variables within a block of code. In general, the scope of a local variable extends from its declaration to the end of the code block in which it was declared. The scope of each variable in that program extends from the declaration of the variable to the end of the main method --indicated by the first right curly bracket } in the program code. Parameters are formal arguments to methods or constructors and are used to pass values into methods and constructors. The scope of a parameter is the entire method or constructor for which it is a parameter. Exception-handler parameters are similar to parameters but are arguments to an exception handler rather than to a method or a constructor. The scope of an exception-handler parameter is the code block between { and } that follow a catch statement.
if (...) { int i = 17; ... } System.out.println("The value of i = " + i);

// error

The final line won't compile because the local variable i is out of scope. The scope of i is the block of code between the { and }. The i variable does not exist anymore after the closing }. Either the variable declaration needs to be moved outside of the if statement block, or the println method call needs to be moved into the if statement block.

5.9 Instance and Class Members
When you declare a member variable such as aFloat in MyClass:
class MyClass { float aFloat; }

you declare an instance variable. Every time you create an instance of a class, the runtime system creates one copy of each the class's instance variables for the instance. Instance variables are in constrast to class variables (which you declare using the static modifier). The runtime system allocates class variables once per class regardless of the number of instances created of that class. The system allocates memory for class variables the first time it encounters the class. All instances share the same copy of the class's class variables. You can access class variables through an instance or through the class itself. Methods are similar: your classes can have instance methods and class methods. Instance methods operate on the current object's instance variables but also have access to the class variables. Class methods, on the other hand, cannot access the instance variables declared within the class (unless it creates a new object and accesses them through the object). Also, class methods can be invoked on the class, you don't need an instance to call a class method.

87

System. anotherX. "But". all instances of AnIntegerNamedX share the same implementation of x() and setX(). These copies are associated with the new object. It creates two different objects of type AnIntegerNamedX. . a member declared within a class is an instance member. . } public void setX(int newX) { x = newX. you get a new copy of each of the class's instance variables.x directly.x = " + myX. Within an instance method. every time you instantiate a new AnIntegerNamedX object from the class.x = " + anotherX.x()).x = 2. The class defined below has one instance variable--an integer named x--and two instance methods--x() and setX()--that let other objects set and query the value of x: class AnIntegerNamedX { int x. you get a new copy of x that is associated with the new AnIntegerNamedX object. So. } } Every time you instantiate a new object from a class. Notice that the code used setX() to set the x value for myX but just assigned a value to anotherX.println("myX. x() and setX(). unless otherwise specified. the name of an instance variable refers to the current object's instance variable (assuming that the instance variable isn't hidden by a method parameter). then displays them: . AnIntegerNamedX myX = new AnIntegerNamedX(). Suppose that this code snippet was in another object's method. Note that both methods.out. . The output produced by this code snippet is: myX.x = 2 88 . .By default. System. All instances of a class share the same implementation of an instance method. myX. Objects outside of AnIntegerNamedX that wish to access x must do so through a particular instance of AnIntegerNamedX. sets their x values to different values. the code is manipulating two different copies of x: the one contained in the myX object and the one contained in the anotherX object.println("anotherX.x()). "if all instances of AnIntegerNamedX share the same implementation of x() and setX() isn't this ambiguous?" The answer is no.out. you ask. Either way. .setX(1). public int x() { return x. refer to the object's instance variable x by name. AnIntegerNamedX anotherX = new AnIntegerNamedX().x = 1 anotherX.

use the static keyword in the method declaration. public int x() { return x. let's change the AnIntegerNamedX class such that its x variable is now a class variable: class AnIntegerNamedX { static int x. When you invoke setX() on either instance. } public void setX(int newX) { x = newX. you can specify that a method is a class method rather than an instance method. myX. } } Now the exact same code snippet from before that creates two instances of AnIntegerNamedX. use the static keyword.showing that each instance of the class AnIntegerNamedX has its own copy of the instance variable x and each x has a different value. Similarly. and then displays them produces this. you change the value of x for all instances of AnIntegerNamedX. Class methods can only operate on class variables and cannot access the instance variables defined in the class.x = 2 The output is different because x is now a class variable so there is only one copy of the variable and it is shared by all instances of AnIntegerNamedX including myX and anotherX. You use class variables for items that you need only one copy of and which must be accessible by all objects inheriting from the class in which the variable is declared. The system creates a single copy of a class variable the first time it encounters the class in which the variable is defined. Let's change the AnIntegerNamedX class such that its member variable x is once again an instance variable. when declaring a method. To specify that a member variable is a class variable. sets their x values. For example. and its two methods are now class methods: class AnIntegerNamedX { 89 . For example. output. You can. you can specify that method to be a class method rather than an instance method. To specify that a method is a class method. different. Similarly. specify that the variable is a class rather than an instance variable.x = 2 anotherX. class variables are often used with final to define constants (this is more memory efficient as constants can't change so you really only need one copy). Class methods can only operate on class variables--they cannot access the instance variables defined in the class. when declaring a member variable. All instances of that class share the same copy of the class variable.

java:7: Can't make a static reference to nonstatic variable x in class AnIntegerNamedX. } } Now the class will compile and the same code snippet from before that creates two instances of AnIntegerNamedX. Let's fix AnIntegerNamedX by making its x variable a class variable: class AnIntegerNamedX { static private int x. static public int x() { return x.} private int x. ^ AnIntegerNamedX. x = newX. Another difference between instance members and class members is that class members are accessible from the class itself. and then prints the x values produces this output: myX. You don't need to instantiate a class to access its class members. return x. Let's rewrite the code snippet from before to access x() and setX() directly from the AnIntegerNamedX class: 90 . you will get compiler errors: AnIntegerNamedX. sets their x values. } static public void setX(int newX) { x = newX. static public int x() { return x.x = 2 Again. changing x through myX also changes it for other instances of AnIntegerNamedX.java:4: Can't make a static reference to nonstatic variable x in class AnIntegerNamedX. } static public void setX(int newX) { x = newX. ^ 2 errors This is because class methods cannot access instance variables unless the method created an instance of AnIntegerNamedX first and accessed the variable through it. } When you try to compile this version of AnIntegerNamedX.x = 2 anotherX.

AnIntegerNamedX.out. . . .0f 0. class CheckInit { // field variable static int i. .println(" Local array ref: " + a[3]). Local variables (method or constructor variables) are not automatically initialized. // local variable int[] a = new int[5]. Notice that you no longer have to create myX and anotherX.println(" Local variable: " + j). You can access class variables and methods either from an instance of the class or from the class itself. System. you can only invoke instance methods from an object and can only access instance variables from an object. Arrays.x = " + AnIntegerNamedX.out. static void myMethod(){ int j. You cannot do this with instance members.out. // local variable array // causes compile error if not explicitly initialized j = 10. } public static void main(String[] args) { System. are automatically initialized to the default values of their declared type. whether field or local variables. System.println("Field variable i: " + i).setX(1). You can set x and retrieve x directly from the AnIntegerNamedX class. // field array reference variable static String[] s = new String[10].x()). System.out. . 91 .0d null based on Array type Field variables (class members) are automatically initialized to default values.println("AnIntegerNamedX.. Default Values of Variables Type boolean byte char short int long float double Object Array Default value false 0 '\u0000' 0 0 0l 0.

7. 2. Because it is executed automatically when the class is loaded. a static initializer block cannot contain a return statement. 5. Like a constructor. It doesn't need a name. } // Static initializer block static { System. and no return type. parameters don't make any sense. 4. so a static initializer block doesn't have an argument list. The following code illustrates the use of a static initializer block: 1. } // Main routine to test the class public static void main(String[] args) { 92 .out. static { } Static initializers are blocks of code within a class that are outside the scope of a method. public class TestStaticInitializer { static String str = "Default". when the class is loaded. 10. because there is no need to refer to it from outside the class definition. public TestStaticInitializer() { System.println("2::str = " + str). 6.out. str = "Static". } } Output of CheckInit: Field Field Local Local variable i: 0 array ref: null variable: 10 array ref: 0 // default value of int // default value for String[] // explicit value // default value of int[] 5.out. it doesn't need to specify a return type. 8. 9.println("1::str = " + str). The code is executed in the same order as it is declared in the class. Therefore. 11. no arguments. 15. 14. 13. myMethod().println(" Field array ref: " + s[2]). The code in a static initializer block is executed only once.10 Static Initializer A static initializer block resembles a method with no name. 12.System. The code in a static initializer block is executed by the virtual machine when the class is loaded. 3.

lines 9-12 are executed before the constructor is called. 93 .x = " + TestShadowing. a static initializer block prints the string out and resets it to the value "Static" on Lines 8-12. 17. As one is found.out. System. The static initializer blocks will be executed in the order in which they appear in the code. Static initializer blocks may be used for executing code that initializes the state of the object or for providing debugging functionality. // local variable System. A static string is declared on Line 2 and set to "Default. int x = 0. The constructor on Lines 4-6 merely prints the variable out.11 Variable Shadowing A field declaration can be shadowed by a local variable declaration class TestShadowing { static int x = 1.println("TestShadowing. Multiple static initializer blocks You may include any number of static initializer blocks in your class definition. 5. // field variable public static void main(String[] args) { int x = 0. } } TestStaticInitializer tsi = new TestStaticInitializer().out. However. the simple identifier name x is assumed to be within scope as a local variable. overuse of this feature can lead to complex and unreadable code.x = 1 because the identifier x is used within a code block main() a search is made for a declaration of x within the body of main(). Only static members can be referenced within static initializer." Next. 18.println("x = " + x). The output of this program is: 2:: str = Default 1:: str = Static When the class is loaded (because it was constructed) on line 17.x) } } Output: x = 0 TestShadowing. The code in static initializer blocks is always executed when the class is loaded and before any method in the class is executed.16.

. For example. int i = 1. i's value passes to j i = 2. . That is. The following shows code on top that creates an instance of AClass and invokes the aMethod with an int argument. That is. int i = 2. int m = i.x 5. // Now j holds "1" // that is. // m = i = 2 not 5 . } } The value in variable i in the code on the left will be passed to variable k in the aMethod argument list. a data value passes and not a reference or pointer to a data location. Changes to the passed value do not affect the variable in the calling code. The code on the bottom shows the AClass definition and the aMethod. k = 5.To access the field variable x.. a1. // j still holds "1" Similarly. When that method assigns a value of 5 to k. primitive variables pass by value. AClass a1 = new AClass ().12 Pass by value and Pass by reference Primitive data type operations deal only with value. j = k * 10. the following code shows that assigning primitive data variable i to another named j simply passes a copy of the value in i into j. void aMethod (int k) { int i = 10 * k.. you must use its fully-qualified name TestShadowing.. it has no affect whatsoever on variable i the code on the left. int j = i. a copy is made and passed to the method.aMethod (i). Modify Reference Variables 94 . in method arguments. class AClass { int j = 1.

the reference itself passes by value.. a. Note that assigning a new object to the "a" variable orphans the original object that "a" pointed to previously. in the following code. AClass a. a = b..j = 4.j = 400. a. and then assign new values to the "j" variable for each object: . However. } } // a now references same // object as does the b variable.. That is. If an object is no longer referenced by any other variables. So both the "a" and "b" variables now reference the same object. void aMethod (int k) { int i = 10*k. int x = b.b. k = 5. then the garbage collector will eventually reclaim the memory that it occupies. the JVM makes a copy of the internal memory pointer and the copy of the pointer goes into the argument value.j = 40. we create two instances of the AClass. The methods and data of that object can be accessed and modified by the method. a = new AClass (). that will have no affect on the reference variable in the calling method. . Then we assign the "b" object to the "a" reference with the a=b. So if the reference variable in the method is set to a new object. 95 .You can always assign a new object to a reference variable. statement. public class AClass { public int j = 1.. j = k * 10. References in Method Arguments The argument list of a method can include object references.j. b. b = new AClass (). For example. "a" and "b". // x = 400 since a and b now // reference same object.

. 96 . BClass b. In that method. the test if (a == b).. the argument variable is assigned to a new instance of the BClass.. AClass a. a. However.// j = 20 not 5 or 100 . simply tests whether a and b point to the same object. } Since reference variables only hold pointers. b.j.j = 20. not if the referenced objects have equal data values. } } class BClass { int j = 0. in the following code.j = 5.. j = b. b = new BClass (). a reference to a BClass object passes to the method of a AClass object..aMethod (b). the original reference remains unaffected. class AClass { void aMethod (BClass bb) { bb. many classes provide an "equals()" method such that a. bb. when the process returns to the calling code.For example. bb= new BClass ().. a = new AClass (). If you need to test whether two objects hold the same data values.equals(b) returns true if the object b data matches that in object a.. int i = 2.j = 100.

those variables are gone and any changes to them lost. greenValue. and blue values of a color in RGB space: public class RGBColor { public int red. } Now we can rewrite getRGBColor so that it accepts an RGBColor object as an argument.green = greenValue. The getRGBColor method returns the current color of the pen by setting the red. 5. because aColor is a reference to an object that exists outside the scope of the method.. } } This simply does not work. This method is attempting to return three values by setting the values of its arguments: public class Pen { private int redValue. } } The changes made to the RGBColor object within the getRGBColor method persist after the method returns. blue. and blue variables exist only within the scope of the getRGBColor method. int blue) { red = redValue.13 Access Control Access or visibility rules determine whether a method or a data variable can be accessed by another method in another class or subclass.. that can hold the red.blue = blueValue. green. green = greenValue. and blue member variables of its RGBColor argument: public class Pen { private int redValue. blue = blueValue. The red..red = redValue. aColor. public void getRGBColor(int red. we need a new type of object. aColor. blueValue. int green. Let's rewrite the getRGBColor method so that it does what was intended. green. Java provides for 4 access modifiers : 97 . blueValue.. public void getRGBColor(RGBColor aColor) { aColor. RGBColor. . When that method returns.Let's look at a method called getRGBColor within a class called Pen. greenValue. green. . //This method does not work as intended. green. First.

4. protected May be accessed by other classes in the same package or from any subclasses of the class in which they are declared. when you write a class. Second. By making some of your data and methods private. May only be accessed from within the package in which they are declared. private no modifier 98 . protected . such as the classes in the Java platform.accessible only within the class. you need to decide what access level every member variable and every method in your class should have. you can change or eliminate these private attributes and methods without worrying that these changes will affect the subclasses.1. Also.access by any other class anywhere. Access levels affect you in two ways.(also known as "package private") accessible to classes in the same package but not by classes in other packages. Methods and Field variables may be accessed from wherever their class is accessed. For example. These access rules allow one to control the degree of encapsulation of your classes. public . You need to put as much effort into deciding the access level for a member as you put into making other decisions about your class's API. One way of thinking about access levels is in terms of the API: access levels directly affect the public API of a class and determine which members of the class can be used by other classes. Even methods in subclasses in the same package do not have access. First. when you use classes that come from another source. you may distribute your class files to other users who can make subclasses of them. 3. Constructors. access levels determine which members of those classes your classes can use. Inner Classes. even if these are subclasses. if you distribute new versions of your classes at a later point. Default . May be accessed only from within the class in which they are declared. Modifier public Used with Classes Interfaces Constructors Inner Classes Methods Field variables Constructors Inner Classes Methods Field variables Constructors Inner Classes Methods Field variables Classes Interfaces Constructors Inner Classes Methods Description A Class or Interface may be accessed from outside its package. such as naming methods. private .accessible by the package classes and any subclasses that are in other packages . 2. you can prevent the subclass code from interfering with the internal workings of your classes.

b.iEnc = 20. }//End of main } If the constructors are declared private then the object of that class can be created only in that class. public void setEnc(int iEncVal){ if(iEncVal < 1000){ iEnc=iEncVal. If you define more than one non inner class in a file with the keyword public the compiler will generate an error. Only one non inner class in any file can be defined with the public keyword. class Base{ private int iEnc=10. } else { System. This allows a variable to be insulated from being modified by any methods except those in the current class. Using the public modifier with a variable makes it available from anywhere. }//End if } public static void main(String args[]) { Base b=new Base(). A public class has global scope. b. } } class Enc{ public static void main(String argv[]){ Base b = new Base(). //compile-time error b.iEnc = 20. It cannot be created outside the class definition.println("Enc value must be less than 1000"). and an instance can be created from anywhere within or outside of a program. 99 . It is used as follows. This means they are NOT visible within sub classes.out.Field variables Private Private variables are only visible from within the same class as they are created in. public int myint =10. Public The public modifier can be applied to a variable (field) or a class.setEnc(20). It is the first modifier you are likely to come across in learning Java.

An aside note: the use of get and set in the naming of these methods is more significant than just programmer convenience and is an important part of the Javabeans system. System. The name of the class file should be same as that of the public class. The public classes should be stored in separate class files. the same package but not elsewhere. A variable defined with no access modifier is said to have default visibility. The visibility modifiers are a key part of the encapsulation mechanism for java.iNoEnc=2. b. but not from sub-classes that is not in the same package. The naming convention for these methods are setFoo to change a variable and getFoo to obtain the contents of a variable. }//End of main } One . and thus protected classes will be visible.println(b. Encapsulation generally takes form of methods to retrieve and update the values of private class variables. The qualification that it is visible from the same package can give more visibility than you might suspect. You can then access it using the dot notation similar to that used when calling a method. These methods are known as a accessor and mutator methods.iNoEnc). Any class in the same directory is considered to be in the default package. This is a key concept of the Object Oriented paradigm.java file can contain multiple classes but only one public class. 100 . Protected A protected variable is visible within a class.out. Encapsulation allows separation of the interface from the implementation of methods. Default visibility means a variable can be seen within the class. Encapsulation allows separation of the interface from the implementation of methods. The accessor (or get) method retrieves the value and the mutator changes (or sets) the value.If you want to create a variable that can be modified from anywhere you can declare it as public. Access Modifiers and encapsulation The visibility modifiers are part of the encapsulation mechanism for Java. Take the example where you had a variable used to store the age of a student. The benefit of this is that the details of the code inside a class can be changed without it affecting other objects that use it. This means that a protected variable is more visible than a variable defined with no access modifier. class Base { public int iNoEnc=77. and in sub classes. } class NoEnc{ public static void main(String argv[]){ Base b = new Base(). and from elsewhere within the same package.

The empty constructor is called the default constructor. You are asked to put in code to check for these error conditions. The default constructor initializes all non-initialized fields and variables to zero. However when they come back to you with the requirement to do more and more validation on the iAge field you can do it all in these methods without affecting existing code that uses this information. 101 . can be changed whilst the way it looks to the outside world (the interface) remains the same. public void setAge(int iStudentAge){ iAge = iStudentAge. } At first this seems a little pointless as the code seems to be a long way around something that could be done with simple variable manipulation. is to create methods that access a private field containing the age value. The Object Oriented approach to this problem using encapsulation. (the actual lines of program code). with names like setAge and getAge.You might store it simply with a public integer variable int iAge. Note: If you do not write your own constructor. you write if statements that check for the range. later when your application is delivered you find that some of your students have a recorded age of more than 200 years and some have an age of less than zero. By this approach the implementation of code.14 Constructors Classes have a special method called a constructor that is called implicitly when a class instance is created. if(iAge > 70){ //do something } if (iAge <3){ //do something } In the process of doing this you miss some code that used the iAge variable and you get called back because you have a 19 year old student who is on your records has being 190 years old. } public int getAge(){ return iAge. The class constructor always has the same name as the class and no return type. So wherever your programs change the age value. 5. the compiler adds an empty constructor. The setAge method might take an integer parameter and update the private value for Age and the getAge method would take no parameter but return the value from the private age field. which calls the no-arguments constructor of its parent class.

//Warning: will not compile. If you then try to create an instance of the class without passing any parameters (i. System.println(retrievedText). Thus as soon as you create any constructors for a class you need to create a zero parameter constructor. invoking the class with a zero parameter constructor). Because Base has an integer constructor the zero parameter constructor is not available and a compile time error occurs. When the compiler checks to create the instance of the Base class called c it inserts a call to the zero parameter constructor.println("single int constructor"). } public static void main(String[] args){ LessonTwoD progInst = new LessonTwoD(). } } public class Cons { public static void main(String argv[]){ Base c = new Base(). } //Accessor method String getText(){ return text.If you create constructors of your own. String retrievedText = progInst.getText(). class Base{ Base(int i){ System. Java does not supply the default zero parameter constructor class LessonTwoD { String text.out. } } //This will compile 102 .out. The following example illustrates code that will not compile. //Constructor LessonTwoD(){ text = "I'm a Simple Program".e. you will get an error. This can be fixed by creating a "do nothing" zero parameter constructor in the class Base. } } As soon as you create any constructors of your own you loose the default no parameter constructor.

this. you can use the same name for all the drawing methods but pass a different type of argument to each method. saturation. which means that multiple methods in the same class can share the same name if they have different parameter lists. each of which takes a different type of argument. abstract. In the Java programming language.15 The this keyword Within an instance method or a constructor. so this constructor must refer to the object's member variables through this: public class HSBColor { private int hue. 5. int brightness) { this. 5. drawString. } Base(){} } public class Cons { public static void main(String argv[]){ Base c = new Base(). you have to think of a new name for each method. synchronized or final.saturation = saturation. this is a reference to the current object — the object whose method or constructor is being called. the data drawing class might declare three methods named draw. In other languages. the following constructor for the HSBColor class initializes the object's member variables according to the arguments passed into the constructor. For example. and so on. and so on) and that contains a method for drawing each data type. 103 .brightness = brightness. The most common reason for doing so is that a member variable is hidden by an argument to the method or the constructor. drawInteger. You can refer to any member of the current object from within an instance method or a constructor by using this. int saturation.16 Overloading The Java programming language supports name overloading for methods.println("single int constructor"). Each argument to the constructor hides one of the object's member variables. static. Suppose that you have a class that can draw various types of data (strings. } } this keyword cannot be used in a static reference. this.out. } } Constructors cannot be native. integers. for example. drawFloat. Thus.class Base{ Base(int i){ System.hue = hue. brightness. public HSBColor (int hue.

You cannot declare more than one method with the same name and the same number and type of arguments... Overloading is a one of the ways in which Java implements one of the key concepts of Object orientation. polymorphism. } } Overloaded methods are differentiated by the number and the type of the arguments passed into the method.. Polymorphism is a word constructed from Poly meaning "many" and "morphism" implying meaning.. because the compiler cannot tell them apart.public class DataArtist { ... In the code sample. 104 . Thus a overloading allows the same method name to have multiple meanings or uses. } public void draw(float f) { . Thus imagine you were designing the interface for a system to run mock Java certification exams. public void draw(String s) { . markanswerboolean(boolean answer){ } markanswerint(int answer){ } markanswerString(String answer){ } This would work but it means that future users of your classes have to be aware of more method names than is strictly necessary.. } public void draw(int i) { . draw(String s) and draw(int i) are distinct and unique methods because they require different argument types. The method call is resolved during the compile-time hence it uses static or early binding. a boolean or a text string. so you cannot declare two methods with the same signature even if they have a different return type. You could create a version of the method for each parameter type and give it a matching name thus. An answer may come in as an integer. The compiler does not consider return type when differentiating methods. It would be more useful if you could use a single method name and the compiler would resolve what actual code to call according to the type and number of parameters in the call..

Thus changing one of the above to have an int return value will still result in a compile time error. class Test { int i. type and order of parameters. Test(int j. b = a. } Test(int j) { i = j. boolean a) { i = j. } int get() { return i.The following is not an example of overloading and will cause a compile time error indicating a duplicate method declaration. Overloaded methods do not have any restrictions on what exceptions can be thrown. void markanswer(String answer){ } void markanswer(String title){ } The return type does not form part of the signature for the purpose of overloading. A second constructor passes an initial value to just one of the variables. Overloaded methods are differentiated only on the number. not on the return type of the method Overloading Constructors You can define multiple constructors to provide optional ways to create and initialize instances of the class. boolean b=true. That is something to worry about with overriding. but this time indicating that a method cannot be redefined with a different return type. } 105 . } This constructor initializes the two properties to the values passed as arguements.

int width. So for the class shown above. this. will generate a compiler error stating that no such constructor exists.. height. } This class contains a set of constructors. 106 . y. based on the number and the type of arguments. int y. height). As before. an explicit constructor invocation must be the first line in the constructor. A method that calls itself is said to be recursive. private int width. you can also use the this keyword to call another constructor in the same class. the java compiler does not create the default constructor. 0). 0.17 Recursion Recursion is a process of defining something in terms of itself. } public Rectangle(int x. int height) { this. the compiler determines which constructor to call. //A simple example of recursion class Factorial { //this is a recursive function int fact(int n) { int result. the code Test ex = new Test(). Use of this() From within a constructor. using 0s as default values. this. Doing so is called an explicit constructor invocation.. If present.width = width. 5. 0. For example. public class Rectangle { private int x. Recursion is an attribute that allows a method to call itself. width.Note that if a class includes one or more explicit constructors. this. The constructors provide a default value for any member variable whose initial value is not provided by an argument. } . int height) { this(0. Each constructor initializes some or all of the rectangle's member variables. public Rectangle() { this(0. } public Rectangle(int width.x = x. 0.height = height.y = y. the no-argument constructor calls the four-argument constructor.

"String Two".println(anArray[i]. System. This brings us to a potential stumbling block. However. return result. 5. often encountered by new programmers. you can create an array without putting any elements in it.} } if(n == 1) return 1. Another reason is where greater performance is required. A native method ends with a semicolon rather than a code block. Here's a small program.out. result = fact(n-1) * n. class Recursion { public static void main(String args[]) { Factorial f = new Factorial().19 Arrays of Objects Arrays can hold reference types as well as primitive types.println(“Factorial of 3 is “+f. Consider this line of code: 107 . } } 5. Thus the following would call an external routine. You create such an array in much the same way you create an array with primitive types.out. } } } This program creates and populates the array in a single statement. The implementation of native is out of the scope of this course. written perhaps in C++. public native void fastcalc(). for (int i = 0.length. "String Three" }.toLowerCase()). ArrayOfStringsDemo that creates an array containing three string objects then prints the strings in all lower case letters.fact(3)). when using arrays that contain objects.18 Native Methods The native modifier is used only for methods and indicates that the body of the code is written in a language other than Java such as C or C++. i++) { System. Native methods are often written for platform specific purposes such as accessing some item of hardware that the Java Virtual Machine is not aware of. i < anArray. public class ArrayOfStringsDemo { public static void main(String[] args) { String[] anArray = { "String One".

println(anArray[i].print(cartoons[i][0] + ": "). "Velma". j < cartoons[i].print(cartoons[i][j] + " "). i < cartoons. "George". "Judy".length. j++) { System. { "Scooby Doo Gang".20 Nested and Inner Classes You can define a class as a member of another class.out. i++) { // ERROR: the following line gives a runtime error System. the array called anArray exists and has enough room to hold 5 string objects. and so on. for (int i = 0. After this line of code is executed. i < anArray. "Pebbles". This might seem obvious.out. However. } Arrays of Arrays ArrayOfArraysDemo creates an array and uses an initializer to populate it with four sub-arrays.String[] anArray = new String[5]. 5. public class ArrayOfArraysDemo { public static void main(String[] args) { String[][] cartoons = { { "Flintstones". for (int i = 0. "Fred". the array doesn't contain any strings yet. "Daphne" } }. The program must explicitly create strings and put them in the array. many beginners assume that the previous line of code creates the array and creates 5 empty strings in it. “Astro" }. "Rosie". { "Jetsons". "Wilma". "Dino" }.out. } System. Thus they end up writing code like the following. cartoons[1]. i++) { System.length.out. "Betty". which generates a NullPointerException: String[] anArray = new String[5]. "Shaggy". } } } Notice that the sub-arrays are all of different lengths.toLowerCase()).println(). It is empty. for (int j = 1. "Fred". "Barney". Such a class is called a nested class and is illustrated here: 108 . "Elroy". { "Rubbles". "Bam Bam" }. "Scooby Doo". "Jane". however. The names of the sub-arrays are cartoons[0].length.

this just follows the normal naming convention for static members of a class. } class InnerClass { .) Suppose that the WireFrameModel class contains a static nested class. Of course. You should define a class within another class when the nested class makes sense only in the context of its enclosing class or when it relies on the enclosing class for its function. class ANestedClass { . The access specifiers restrict access to members for classes outside the enclosing class. double x1. z1. . like this: public class WireFrameModel { . (Such models are used to represent three-dimensional objects in graphics programs.class EnclosingClass { ..y2. // other members of the WireFrameModel class static public class Line { // Represents a line from the point (x1.y1.Line. 109 .. } } You use nested classes to reflect and to enforce the relationship between two classes. y2. double x2. z2. Then.. in outline.. A static nested class is called just that: a static nested class. A nonstatic nested class is called an inner class. the Line class would be referred to as WireFrameModel.. this special privilege isn't really special at all.z1) // to the point (x2. a nested class can be declared static (or not). that represents a single line. As a member of its enclosing class. outside of the class WireFrameModel. Line.z2) in 3-dimensional space. } } For example. static class StaticNestedClass { .. . The definition of the WireFrameModel class with its nested Line class would look. It is fully consistent with the meaning of private and the other access specifiers. The nested class is inside its enclosing class so that it has access to its enclosing class's members. y1. a text cursor might make sense only in the context of a text component.. suppose a class named WireFrameModel represents a set of lines in threedimensional space. even if they are declared private. a nested class has a special privilege: It has unlimited access to its enclosing class's members. However. Like other members. class EnclosingClass { .. For example...

a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference. The name of the class file for Line will be WireFrameModel$Line. syntactically. which we call class methods and variables. Even though the definition of Line is nested inside WireFrameModel. Consider the following classes: class EnclosingClass { . an inner class is associated with an instance of its enclosing class and has direct access to that object's instance variables and methods.Line()" would be used. The next figure illustrates this idea.. 110 . To help further differentiate the terms nested class and inner class. because an inner class is associated with an instance. it cannot define any static members itself. "new WireFrameModel.class. it's that an instance of InnerClass can exist only within an instance of EnclosingClass and that it has direct access to the instance variables and methods of its enclosing instance. since it lets you give one class access to the private members of another class without making those members generally available to other classes. // other members of the WireFrameModel class } // end WireFrameModel Inside the WireframeModel class. This can be another motivation for declaring a nested class. As with static methods and variables. two class files will be created. In contrast. . A static nested class has full access to the members of the containing class.. And like class methods. Outside the class. Rather.. a Line object would be created with the constructor "new Line()". it's useful to think about them in the following way.} // end class Line . } } The interesting feature about the relationship between these two classes is not that InnerClass is syntactically defined within EnclosingClass. Also. the code for one class appears within the code of another. a static nested class is associated with its enclosing class. even to the private members. When you compile the above class definition. The term nested class reflects the syntactic relationship between two classes. that is.. . the term inner class reflects the relationship between objects that are instances of the two classes. class InnerClass { . the compiled Line class is stored in a separate file. As with instance methods and variables.

In order to create an object that belongs to a non-static nested class.Any non-static member of a class is not really part of the class itself (although its source code is contained in the class definition).) The nested class object is permanently associated with the containing class object. This copy has access to all the instance methods and instance variables of the object. Two copies of the nested class in different objects differ because the instance variables and methods they refer to are in different objects. private int pot.NestedClassName. and there it can be referred to by its simple name. 111 . where variableName is a variable that refers to the object that contains the class. . In fact. the object "this" is used implicitly. class Player { // Represents one of the players in this game. It's as if each object that belongs to the containing class has its own copy of the nested class. From outside the containing class. . The same is true -. it might as well be static. a non-static nested class has to be referred to as variableName. This class might include a nested class to represent the players of the game. you must first have an object that belongs to the containing class. .for non-static nested classes. (When working inside the class. and will hopefully convince you that non-static nested classes are really very natural. This is true for non-static nested classes. } // end class Player private Deck deck. Looking at an example will help. . The non-static members of a class specify what will be contained in objects that are created from that class. A non-static nested class is generally used only inside the class in which it is nested. This structure of the PokerGame class could be: class PokerGame { // Represents a game of poker. however. just as it is for any other non-static part of a class. . and it has complete access to the members of the containing class object. Consider a class that represents poker games. // A deck of cards for playing the game. // The amount of money that has been bet.at least logically -. Otherwise. This is actually rather rare. make it non-static. the rule for deciding whether a nested class should be static or non-static is simple: If the class needs to use any instance variable or instance method. .

or the current this object is not an instance of the outer class. the syntax in the second line is the one you use when you already have an instance of the outer class. In an an instance method of a PokerGame object. constructs an instance of Inner where Inner is a nested class defined in the current class. Outer. Write code in a non-static method of the outer class to construct an instance of the nested class. on the other hand. Each PokerGame object has its own deck and pot and Players. a new Player object would be created by saying "new Player()". Players of that poker game use the deck and pot for that game. Outer. Outer x = new Outer(). playes of another poker game use the other game's deck and pot. then. (A Player object could be created outside the PokerGame class with an expression such as "new game.new Inner().} // end class PokerGame If game is a variable of type PokerGame. it would represent the general idea of a poker player. The following example creates the Outer instance on a separate line. You must create an instance of the outer class first. just as for any other class. game contains its own copy of the Player class.new Inner().Inner y = new Outer(). Inner x = new Inner(). Again. If Player were a static nested class. You may encounter nested classes of both kinds in the Java platform API and be required to use them. but it had to construct an instance of Outer first. conceptually. however. this is rather rare.Player()". containing a nested class Inner: Outer. A Player object represents a player of one particular poker game. independent of a particular poker game. If Inner is static. you can use: 112 . That's the effect of making the Player class non-static. This is the most natural way for players to behave. Write code to construct an instance on a nested class where either no this object exists. Given a class. The above creates an instance of Inner called y.Inner y = x. To define a non-static nested class either in a class or method scope: Place the class definition (for the nested class) inside another class definition (the outer class) or a method.) The Player object will have access to the deck and pot instance variables in the PokerGame object.

Command-line arguments allow the user to affect the operation of an application for one invocation. now gets executed if and only if the length of the args array is greater than zero. Arrays have lengths and you can access that length by referencing the variable arrayname. } } } System. This is done using the command-line argument -verbose. In Java. The code inside the braces.println("Hello " + args[0]). like the Mac OS.out. For example. an application might allow the user to specify verbose mode--that is.println(args[0]) was wrapped in a conditional test.Inner I= new Outer. So the Java runtime system does not pass the class name you invoke to the main method.length.length You test the length of the args array as follows. Purity Tip: Programs that use command-line arguments are not 100% Pure Java because some systems.println(args[0]). Consider using properties instead so that your programs fit more naturally into the environment. don't normally have a command line or command-line arguments.length > 0) { }. System.out. it passes only the items on the command line that appear after the class name.length > 0) { System. consider the following statement. For example.Inner(). Rather. you always know the name of the application because it's the name of the class in which the main method is defined.out.21 Command-Line Arguments A Java application can accept any number of arguments from the command line.Outer. which is used to invoke a Java application: java diff file1 file2 The following simple application displays each of its command-line arguments on a line by itself: public class Echo { public static void main (String[] args) { 113 . You can derive the number of command-line arguments with the array's length attribute: numberOfArgs = args. specify that the application display a lot of trace information. if (args. 5. // This is the Hello program in Java class Hello { public static void main (String args[]) { if (args.

parseInt(args[0]).out. you would join them by enclosing them within double quotation marks. to a number. and so on--have parseXXX methods that convert a String representing a number to an object of their type. Tuesday.length. 5. South. Double. 114 . } } Here's an example of how to invoke the application. and Java--on a line by itself.0. i < args. parseInt throws a NumberFormatException if the format of args[0] isn't valid. Friday. WEDNESDAY.length > 0) firstArg = Integer. it must convert a String argument that represents a number. All of the Number classes--Integer. TUESDAY. Float. For example. Common examples include compass directions. such as "34". THURSDAY. If you want Drink. if (args.for (int i = 0. Here's a code snippet that converts a command-line argument to an int: int firstArg. i++) System. MONDAY. java Echo "Drink Hot Java" Drink Hot Java Parsing Numeric Command-Line Arguments If your program needs to support a numeric command-line argument. Monday. This is because the space character separates command-line arguments.22 Enumerated types Enumerated types is a new feature introduced in J2SE 5. An enumerated type is a type whose legal values consist of a fixed set of constants. you would specify a days of the week enumerated type as: enum Days { SUNDAY. you define an enumerated type by using the enum keyword. which take the values Sunday. You enter the words that are shown here in a different font: java Echo Drink Hot Java Drink Hot Java Note that the application displays each word--Drink. In the Java programming language. Thursday.println(args[i]). Hot. East and West and days of the week. and Java to be interpreted as a single argument. and Saturday. Hot. which take the values North. Wednesday.

(5. Java programming language enumerated types are much more powerful than their counterparts in other languages. command line flags. which are just glorified integers. and so on. They are Comparable and Serializable.0268e7).3972e6). A Planet has constant mass and radius properties. public enum MERCURY VENUS EARTH MARS JUPITER SATURN URANUS NEPTUNE PLUTO Planet { (3.688e+26. 7. implement interfaces. (1.   In the following example. They provide implementations of all the Object methods. SATURDAY }. 2. and the serial form is designed to withstand changes in the enum type. (1. //in kilograms double radius. (4. 2.mass double mass. The enum declaration defines a class (called an enum type). 6.9e+27. (5. double radius) { = mass. (8. Notice that by convention the names of an enumerated type's values are spelled in uppercase letters. rounding modes. They exist in their own namespace. Each enum constant is declared with values for the mass and radius parameters that are passed to the constructor when it is created. That includes natural enumerated types such as the planets in our solar system. (6.303e+23. They have a static values method that returns an array containing all of the values of the enum type in the order they are declared.686e+25. You should use enumerated types any time you need to represent a fixed set of constants. Planet is an enumerated type that represents the planets in the solar system. and more.1492e7). private final private final Planet(double this.FRIDAY. These are the most important properties of enum types:       Printed values are informative. //in meters mass. and the suits in a deck of cards as well as sets where you know all possible values at compile time. for example the choices on a menu. 2. 115 .27e+22. the days of the week.5559e7). the compiler displays an error message. Note that the constructor for an enum type is implicitly private. 6. The set of constants is not required to stay fixed for all time. 1. If you attempt to create a public constructor for an enum type.869e+24. 3.976e+24.4397e6).421e+23. 6. (1. You can switch on an enumeration constant.137e6).0518e6).4746e7). This method is commonly used in combination with the for-each construct to iterate over the values of an enumerated type. You can provide methods and fields.024e+26. They are typesafe.37814e6).

surfaceGravity().printf("Your weight on %s is %f%n". double mass = earthWeight/EARTH.207413 on PLUTO is 11.out. } //universal gravitational constant (m3 kg-1 s-2) public static final double G = 6. 116 .values()) { System.279007 on JUPITER is 442.397260 on NEPTUNE is 199. it's not possible for one enum type to extend another enum type.552719 on URANUS is 158.847567 on SATURN is 186.surfaceWeight(mass)). Enumerated types in switch statement An example of using enumerated type in switch statement.radius = radius. Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. } } Here's the output: java Your Your Your Your Your Your Your Your Your Planet weight weight weight weight weight weight weight weight weight 175 on MERCURY is 66. } public double mass() { return mass.703031 There's one limitation of enum types: although enum types are classes.this.374842 on EARTH is 175.67300E-11. } public double radius() { return radius. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit): public static void main(String[] args) { double earthWeight = Double. you cannot define a hierarchy of enums. public double surfaceGravity() { return G * mass / (radius * radius). p. p. for (Planet p : Planet. } } In addition to its properties.parseDouble(args[0]).107583 on VENUS is 158.000000 on MARS is 66. } public double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(). In other words.

The Java platform allows you to create as many objects as you want (limited. case FEBRUARY: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29. SEPTEMBER. int numDays = 0. 117 . MARCH. by what your system can handle). NOVEMBER.23 Garbage Collection Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. JULY. AUGUST. int year = 2000. break. MAY. JUNE. APRIL. break. else numDays = 28. switch (month) { case JANUARY: case MARCH: case MAY: case JULY: case AUGUST: case OCTOBER: case DECEMBER: numDays = 31. This process is called garbage collection. } System.public class SwitchEnumDemo { public enum Month { JANUARY. case APRIL: case JUNE: case SEPTEMBER: case NOVEMBER: numDays = 30. } 5. break. Managing memory explicitly is tedious and error prone. The Java runtime environment deletes objects when it determines that they are no longer being used. default: numDays=0. DECEMBER } public static void main(String[] args) { Month month = Month.FEBRUARY.out. break. OCTOBER. and you don't have to worry about destroying them. of course. FEBRUARY.println("Number of Days = " + numDays).

in some situations. your implementation of the method should call super. all references to an object must be dropped before the object is eligible for garbage collection. Most programmers don't have to worry about implementing the finalize method. If you override finalize. Summary A class definition has two parts: a class declaration and a class body. Or. methods. You access instance variables and methods through objects. For instance. This process is known as finalization. and constructors for the class. Finalization Before an object gets garbage-collected. A class method or class variable is associated with a particular class. 118 . although. a programmer might have to implement a finalize method to release resources.finalize as the last thing it does. A class uses member variables to contain state and uses methods to implement behavior. which is the top of the Java platform's class hierarchy and a superclass of all classes. The runtime system allocates a class variable once per class. you can explicitly drop an object reference by setting the variable to the special value null.An object is eligible for garbage collection when there are no more references to that object. such as native peers. The garbage collector does its job automatically. You access class variables and methods through the class. you might want to run the garbage collector after a section of code that creates a large amount of garbage or before a section of code that needs a lot of memory. References that are held in a variable are usually dropped when the variable goes out of scope. Every time you create an object. you may want to run the garbage collection explicitly by calling the gc method in the System class. however. the new object gets a copy of every instance variable defined in its class. The finalize method is a member of the Object class. that aren't under the control of the garbage collector. no matter how many instances exist of that class. Remember that a program can have multiple references to the same object. An instance method or instance variable is associated with a particular object (an instance of a class). the garbage collector gives the object an opportunity to clean up after itself through a call to the object's finalize method. A class can override the finalize method to perform any finalization necessary for objects of that type. The Garbage Collector The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. In rare cases. The class body contains member variables.

Compile-time error at line 2. such as private or public.methodName(argumentList) or objectReference. which must be accessed through an instance reference. An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private. Instance variables and methods that are accessible to code outside of the class that they are declared in can be referred to by using a qualified name. Class variables are shared by all instance of a class and can be accessed through the class name. You can assign the reference to a variable or use it directly. Questions 1. An object is unused if the program holds no more references to it. 119 . class GRC7 {public void main(String[] args) {}} // 1 class GRC8 {public void main(String []args) {}} // 2 class GRC9 {public void main(String args[]) {}} // 3 What is the result of attempting to compile and run the above programs? a. The garbage collector automatically cleans up unused objects. A nonstatic nested class is called an inner class.member. Compile-time error at line 1. Like other members of a class. Compile-time error at line 3.methodName() Constructors initialize a new instance of a class and have the same name as the class. You can explicitly drop a reference by setting the variable holding the reference to null. The new operator returns a reference to the object that was created. in the member's declaration. b. A class controls access to its instance variables and methods by using the Java platform’s access mechanism. a nested class can be declared static or not.variableName The qualified name of a method looks like this: objectReference. Instances of a class get their own copy of each instance variable. You create an object from a class by using the new operator and a constructor. The qualified name of an instance variable looks like this: objectReference. A class defined within another class is called a nested class. You can control access to member variables and methods in the same way: by using an access specifier. c.

An attempt to run GRC1 from the command line fails. 2. e. f. b. An attempt to run GRC8 from the command line fails. static int d. Run-time error g. Compile-time error at line 2. static short b. Prints: 00000 c. public static void main(String[] args) { System. System. Prints: 00000null b. Compile-time error at line 4. static char c. Compile-time error at line 3. An attempt to run GRC3 from the command line fails. static long e.d. System. Compile-time error at line 5. An attempt to run GRC2 from the command line fails. class GRC1 {public static void main(String[] args) {}} // 1 class GRC2 {protected static void main(String[] args) {}} // 2 class GRC3 {private static void main(String[] args) {}} // 3 What is the result of attempting to compile each of the three class declarations and invoke each main method from the command line? a.println(a+b+c+d+e+s). Compile-time error at line 3.println("x="+x).out. Compile-time error at line 1. c. e. public static void main(String[] args) { int y.out. Prints: 0null 120 . static String s. f. An attempt to run GRC7 from the command line fails.println("y="+y). e. class GFM12 { Compile-time error at line 1. class GFM13 { static byte a. b. } } // 1 // 2 // 3 // 4 // 5 What is the result of attempting to compile and run the program? a. 3. d. None of the above 4. } } What is the result of attempting to compile and run the program? a. An attempt to run GRC9 from the command line fails. static int x.out. d. c. f. Compile-time error at line 2.

f.d. e. Prints: 0 Prints: null Compile-time error Run-time error None of the above 121 . g. h.

if (i1 > 0) {i3 = i1 + i2.out. int i2) { int i3.} return i3. class GFM16 { static int m1 (int i1. } public static void main(String[] args) { System. d. Prints: 0 Prints: 1 Compile-time error Run-time error None of the above 122 . b.2)). c. } } What is the result of attempting to compile and run the program? a. e.println(m1(1.5.

Run-time error g. Prints: B C D f. class GFC301 { private String name. Compile-time error f."+ m(b1)). 123 .setName("Bird"). System.out.} public static void main (String[] args) { int a1 = 1.double e.} public String getName() {return name.name = name. Prints: double.double c.} public static void m1(GFC301 r1. Prints: C D E g.name = name.print(m(a1)+".float d. long b1 = 2.} static String m(double i) {return "double". Prints: float. class GFC215 { } static String m(float i) {return "float". } public static void main (String[] args) { GFC301 pet1 = new GFC301("Dog"). class GRC10 { public static void main (String[] s) { System. Prints: CDE d. } } java GRC10 A B C D E F What is the result of attempting to compile and run the program using the specified command line? a. Run-time error i.float b. Prints: float.} public void setName(String name) {this. Prints: double.out. } What is the result of attempting to compile and run the program? a. None of the above 8. Compile-time error h. Prints: BCD c. Prints: A B C e. GFC301 r2) { r1. None of the above 7. Prints: ABC b. GFC301 pet2 = new GFC301("Cat"). r2 = r1. public GFC301(String name) {this.6.print(s[1] + s[2] + s[3]).

Compile-time error g. Run-time error f.getName() + ". f. e. Prints: Bird. System.println(pet1.Bird e. None of the above 9. // 3 a = c + a. c. // 5 } } A compile-time error is generated at which line? a.Cat d." + pet2. class Maroon { public static void main (String[] args) { int a = 1. Prints: Dog. Prints: Dog.getName()). b.out.} } m1(pet1. What is the result of attempting to compile and run the program? a. 1 2 3 4 5 None of the above 124 .Bird c. // 2 long c = 1. d. // 1 short b = 1. Prints: Bird.pet2). // 4 c = b + a.Cat b.

f. i1 = i2. System.1 d.3 c. m1(i1. // 7 byte b6 = 1.out. None of the above 11. Run-time error f.0d. i2). i2 = i3. c. Prints: 1. // 3 byte b2 = c1. Compile-time error g. // 1 final char c1 = 1. } } What is the result of attempting to compile and run the program? a. g.3 e. class GFC304 { static void m1(int[] i1. 1 2 3 4 5 6 7 8 125 . } public static void main (String[] args) { int[] i1 = {1}. class GFC100 { public static void main(String[] args) { final short s1 = 1.0. Prints: 1. // 8 } } Compile-time errors are generated at which lines? a. // 5 byte b4 = 1L. Prints: 3. h. i2 = {3}. // 6 byte b5 = 1. // 2 byte b1 = s1. Prints: 3." + i2[0]). // 4 byte b3 = 1.1 b. e.print(i1[0] + ". d. int[] i2) { int[] i3 = i1. b.10.

} // 1 // 2 // 3 } What is the result of attempting to compile and run the program? a. return c1. System. e. b.12. d. Prints: 13 Prints: 4 Compile-time error at 1 Compile-time error at 2 Run-time error None of the above 126 . } static byte m2(final char c2) {return c2. c.print(""+m1()+m2(c3)).out. f. class JSC201 { static byte m1() { final char c1 = '\u0001'.} public static void main(String[] args) { char c3 = '\u0003'.

127 .

We'd like to add the ability to represent the position of a circle without losing any of the existing functionality of the Circle class.cy.Chapter 6 : Inheritance 6.0 centered at point 0. commissioned and hourly employees.1 Inheritance Basics Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. public double area() { return Math. The generic class is known as the parent (or superclass or base class) and the specific classes as children (or subclasses or derived classes). instead. Suppose. An example of where this could be useful is with an employee records system. class Circle { double radius. that we want to represent circles that have both a size and a position. Circle. This is done by defining PlaneCircle as a subclass of Circle. // Distance from center double distance = Math. For example. The concept of inheritance greatly enhances the ability to reuse code as well as making design a much simpler and cleaner process. a circle of radius 1. You could create a generic employee class with states and actions that are common to all employees.0 in the Cartesian plane is different from the circle of radius 1. so that PlaneCircle inherits the fields and methods of its superclass. // New instance fields that store the center point of the circle double cx. } } public class PlaneCircle extends Circle { // We automatically inherit the fields and methods of Circle. cy. Then more specific classes could be defined for salaried. double y) { double dx = x .2. Java uses the extends keyword to set the relationship between a child class and a parent class.PI * radius * radius.cx. // so we only have to put the new stuff here.sqrt(dx*dx + dy*dy). which we'll call PlaneCircle. dy = y . we need a new class. To do this. 128 . The Circle is a simple class that distinguishes circle objects only by their radii. // // // // The area() method is inherited from Circle A new instance method that checks whether a point is inside the circle Note that it uses the inherited instance field radius public boolean isInside(double x.0 centered at point 1.

0.println(“Point 60.radius = 10. pc. System. and so on. // Returns true or false public static void main(String args[]) { PlaneCircle pc=new PlaneCircle(). the following two declarations of class "MyClass" are equivalent: public class MyClass{ } public class MyClass extends Object { } As depicted in the following figure. For example. The Object class.isInside(60. then.println(“Area of the circle :” + pc. 129 . that the item was not inherited at all. Normally.0.60 is inside the circle “). pc. This becomes important when using an inner class. One might say. But the item is inherited. } else { System. the inheritance from the Object class is implicit.cy = 40.cx = 50. defines and implements behavior that every class needs.60) is within the circle if(pc. forming a hierarchy of classes. which does have access to its enclosing class's private members.out.} // Pythagorean theorem return (distance < radius).out. many classes derive from those classes. //check whether a point (60.60 is outside the circle“). However. the subclass might not have access to an inherited member variable or method. } } } A subclass inherits all the member variables and methods from its superclass. defined in the java.0.out.area()).60)) { System. many classes derive from Object. Note that constructors are not members and so are not inherited by subclasses. a subclass cannot access a private member inherited from its superclass.lang package. Therefore. when a class is defined in Java. pc.println(“Point 60.

The term superclass refers to a class's direct ancestor or to any of its ascendant classes. } public class RedDwarf extends Star { String subtype. A subclass derives from another class. Java was designed without multiple inheritance. Example of Multi-level Inheritance public class AstronomicalObject { double magnitude. the singly rooted hierarchy (with Object as the ultimate ancestor of all classes) and Java interfaces solves most problems that are commonly solved using multiple inheritance in C++. } Using superclass variable to access subclass object A superclass variable upwards in the hierarchy of Inheritance till the Object class can be used to used to assign the subclass object. Classes near the bottom of the hierarchy provide more specialized behavior. } public class Star extends AstronomicalObject { double surfaceTemperature. Star rd = new RedDrawf().At the top of the hierarchy. AstronomicalObject rd = new RedDrawf(). 130 . Every class has one and only one immediate superclass. The overall design of Java supports the solution of problems commonly solved with multiple inheritance in other ways. For example. In particular. Object rd = new RedDrawf(). in the above code the object of RedDwarf can be created as follows: RedDwarf rd = new RedDrawf(). Object is the most general of all classes.

} } class Cheese { Cheese() { System.out.java // Order of constructor calls class Meal { Meal() { System.println("Lettuce()"). A derived class has access to its own members only. It will silently call the default constructor if you don’t explicitly call a base-class constructor in the derived-class constructor body. (In the case where a class has no constructors. the compiler will complain. } } class Lettuce { Lettuce() { System. This makes sense because the constructor has a special job: to see that the object is built properly. Only the base-class constructor has the proper knowledge and access to initialize its own elements. and not to those of the base class (whose members are typically private). If there is no default constructor.println("Meal()").} } class PortableLunch extends Lunch { PortableLunch() { System.out.out. } } class Bread { Bread() { System. Therefore.) Let’s take a look at an example that shows the effects of composition. } } 131 . it’s essential that all constructors get called. inheritance.out.2 Understanding how Constructors are called A constructor for the base class is always called in the constructor for a derived class. } } class Lunch extends Meal { Lunch() { System. That’s why the compiler enforces a constructor call for every portion of a derived class. otherwise the entire object wouldn’t be constructed properly.println("PortableLunch()"). and polymorphism on the order of construction: // Sandwich.println("Lunch()").println("Bread()").6. chaining upward so that a constructor for every base class is called.out.println("Cheese()"). the compiler will automatically synthesize a default constructor.out.

When you inherit. etc. Cheese c. 2. The important class is Sandwich. Inside the constructor. and each class has a constructor that announces itself. Member initializers are called in the order of declaration. This means that you must be able to assume that all the members of the base class are valid when you’re in the derived class.class Sandwich extends PortableLunch { Bread b. you must be able to assume that all members that you use have been built.out. Lettuce l. which reflects three levels of inheritance (four. System. construction has already taken place. until the most-derived class is reached. however. The base-class constructor is called. so all the members of all parts of the object have been built. 3. followed by the next-derived class. the output is: Meal() Lunch() PortableLunch() Bread() Cheese() Lettuce() Sandwich() This means that the order of constructor calls for a complex object is as follows: 1. The only way to guarantee this is for the base-class constructor to be called first. The order of the constructor calls is important. This step is repeated recursively such that the root of the hierarchy is constructed first. } } This example creates a complex class out of other classes. c = new Cheese(). if you count the implicit inheritance from Object) and three member objects. you know all about the base class and can access any public and protected members of the base class. l = new Lettuce(). } public static void main(String[] args) { new Sandwich().. The body of the derived-class constructor is called. Then when you’re in the derived-class constructor.println("Sandwich()"). all the members you can 132 . When a Sandwich object is created in main( ). Sandwich() { b = new Bread(). In a normal method.

you should initialize all member objects (that is. // Calls the constructor of Object class m_x = 10. whenever possible. m_y = 20. //============ Constructor (same as in above example) public Point() { super(). grandparent class. you don't explicitly write the constructor for your parent class. all the way up to the root class Object. int m_y. there is no need to make a call to it because it will be supplied automatically. If you are satisfied with the default constructor in the superclass. you will help ensure that all base class members and member objects of the current object have been initialized. c.: b. It's necessary to initialize all fields. Use of super keyword You can also use super within a constructor to invoke a superclass's constructor. //============ Constructor public Point() { m_x = 10. } Normally. You want to call a parent constructor which has parameters (the default construct has no parameters). If you follow this practice. therefore all constructors must be called! The Java compiler automatically inserts the necessary constructor calls in the process of constructor chaining. The Java compiler inserts a call to the parent constructor (super) if you don't have a constructor call as the first statement of you constructor. m_y = 20. “Knowing that all members are valid” inside the constructor is also the reason that.g. An object has the fields of its own class plus all fields of its parent class. objects placed in the class using composition) at their point of definition in the class (e. or you can do it explicitly. public class Point { int m_x. but there are two cases where this is necessary: • Passing parameters. and l in the example above).access in the base class have been initialized. 133 . Calling the constructor for the superclass must be the first statement in the body of a constructor. } } The following is the equivalent of the constuctor above.

This problem can be solved as follows : Parent class can define a parameterless constructor. so the compiler will insert a call to the parameterless constructor of the parent. class Parent { int _x. there is no explicit call to a constructor in the first line of constructor. Parent(int x) { _x = x. but there is no parameterless parent constructor! Therefore this produces a compilation error. // If any constructor is defined. } Parent() { _x = 0. // constructor without parameters 134 . needs explicit call to super. the compiler doesn't // automatically create a default parameterless constructor. } } // constructor ////////////////// class that must call super in constructor class Child extends Parent { int _y. /////////////////// class without a parameterless constructor. Parent() { this(0). _y = y. the compiler doesn't // automatically create a default parameterless constructor. class Parent { int _x. Parent(int x) { _x = x. Example of class without parameterless constructor /////////////////// class without a parameterless constructor. // If any constructor is defined.• No parameterless constructor. } } In the example above. There is no parent constructor with no parameters. Child(int y) { // WRONG. } } // constructor with parameter // constructor without parameters A better way to define the parameterless constructor is to call the parameterized constructor so that any changes that are made only have to be made in one constructor.

it is necessary for the subclass to modify the methods defined in the superclass. } } 6.radius = radius. this new definition replaces the old definition of the method. //radius is inherited Cylinder(double height. this.height = height.40). if you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the base class. etc. until the Object class is finally reached. A subclass inherits methods from a superclass.3 Overriding Methods In a derived class. } public static void main(String args[]) { Cylinder obj = new Cylinder(30. } // other method definitions here public double getArea() { 135 . class Circle { //declaring the instance variable protected double radius. Sometimes. class Circle { double radius. Circle(double radius) { this. } } class Cylinder extends Circle { double height.radius=radius. Example of passing parameters to the base class constructor. Circle(double radius) { this.} } Note that each of these constructors implicitly calls the parameterless constructor for its parent class. double radius) { super (radius). This is referred to as method overriding. The following example demonstrates method overriding.

println(“Surface area of cylinder :” + myCylinder.return Math.getArea()).println(“Area of circle :”+ myCircle. The Cylinder class is defined below.20). The next step is to define a subclass to override the getArea() method in the Circle class. myCylinder = new Cylinder(1.50).out. class Cylinder extends Circle { //declaring the instance variable protected double length. } }// end of class Cylinder When the overriden method (getArea) is invoked for an object of the Cylinder class. this. the new definition of the method is called and not the old definition from the superclass(Circle). System. Cylinder myCylinder.out. The derived class will be the Cylinder class. 136 . For example.PI*radius*radius. System. which returns a String object containing the name of the object's class and its hash code. } //this method returns the cylinder surface area public static void main(String args[]) { Circle myCircle. Most. while the getArea method in the Cylinder class computes the surface area of a cylinder. myCircle = new Circle(1. The getArea() method in the Circle class computes the area of a circle.double length) { super(radius). The ability of a subclass to override a method in its superclass allows a class to inherit from a superclass whose behavior is "close enough" and then override methods as needed.PI*radius*length. the method returns the area of the circle. all classes are descendents of the Object class.getArea().length = length. }//this method returns the area of the circle }// end of class circle When the getArea method is invoked from an instance of the Circle class. if not all.2. } // other method definitions here public double getArea() { // method overriden here return 2*super.20. classes will want to override this method and print out something meaningful for that class.getArea()+2*Math. Object contains the toString method. Cylinder(double radius.

println(e1). Also. public class Subclass extends Superclass { public void aMethod() { //overrides aMethod in Superclass 137 . simply call the overridden method using the super keyword. For example. } } Now. and number and type of the parameters for the overriding method must match those in the overridden method. super. e1. } public static void main(String args[]) { Employee e1 = new Employee().out. but not less. System. method name. called Subclass.overriddenMethodName(). a protected method in the superclass can be made public but not private. here's a subclass. Rather. Superclass: public class Superclass { public boolean aVariable. For example. The return type. that overrides aMethod. } } The toString() method is called implicitly when you try to print the object. you want to add more functionality to it.public class Employee { private String name.name = “John Smith”. the access specifier for the overriding method can allow more access than the overridden method. you don't want to completely override a method. Consider this class. To do this. // overrides Object's toString method public String toString() { return name. Calling the Overridden Method Sometimes. public void aMethod() { aVariable = true. The overriding method can have a different throws clause as long as it doesn't declare any types not declared by the throws clause in the overridden method.

out.println("The override method in Cat. myAnimal.out. final methods cannot be overridden).println("The hide method in Animal. is called Cat: public class Cat extends Animal { public static void hide() { System.hide(). which contains one instance method and one class method: public class Animal { public static void hide() { System.").println("The hide method in Cat. a subclass cannot override a class method.out. super. a subclass cannot override methods that are declared static in the superclass. } public void override() { System.override(). In other words. System.println("The override method in Animal. a subclass of Animal. casts it 138 ."). keyword cannot be used in a static reference. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass. This example contains two classes. } public void override() { System. Let's look at an example to see why.").println(aVariable). These are discussed later. } } The second class. Methods a Subclass Cannot Override A subclass cannot override methods that are declared final in the superclass (by definition. The main method in this class creates an instance of Cat. myAnimal. The first is Animal. Animal myAnimal = (Animal)myCat. Also.aMethod().} } super aVariable = false."). } } The Cat class overrides the instance method in Animal called override and hides the class method in Animal called hide.out. } public static void main(String[] args) { Cat myCat = new Cat().out.

It is the type of the object being referred to (not the type of of the reference variable) that determines which version of an overridden method will be executed class A { void callme() { System. For instance methods. } } class Dispatch { public static void main (String args [] ) { 139 . The version of the hidden method that gets invoked is the one in the superclass.out. and then calls both the hide and the override methods on the instance. In the example. It is a mechanism by which a call to an overridden function is resolved at run time.println(“Inside B’s callme method”).out. and the version of the overridden method that gets invoked is the one in the subclass. Thus. and a static method cannot hide an instance method. rather than compile time (run-time polymorphism). the runtime system invokes the hide method defined in Animal. An instance method cannot override a static method. Thus.out. the runtime system invokes the method defined in the runtime type of the reference on which the method is called. In the example. } } class B extends A { //override callme void callme() { System. } } class C extends A { // override callme void callme() { System.println(“Inside A’s callme method”). The output from this program is as follows: The hide method in Animal.to a Animal reference. For class methods. the runtime system invokes the method defined in the compile-time type of the reference on which the method is called. 6. the runtime system invokes the override method defined in Cat. the compile-time type of myAnimal is Animal.4 Dynamic Method Dispatch Dynamic Inheritance is the ability of an object to inherit classes at runtime and provides several key abilities. The principle is a superclass reference variable can refer to a subclass object.println(“Inside C’s callme method”). The override method in Cat. the runtime type of myAnimal is Cat.

c = new C().A B C A a = new A().callme(). //object of type A //object of type B // object of type C // reference variable of type a // r refers to an A object //calls A’s version of callme // r refers to B object //calls B’s version of callme //refers to C object //calls B’s version of callme r = a. For example: @Override class Cat extends Pet { } or @Override void feedTheDog() { } The following example illustrates all three built-in annotation types. For example. r. r. annotations provide a way for programmers to instruct the compiler on how to handle certain situations. There are three useful annotations built-in to release 5.List. } } 6.0 that will be discussed. r. r. r = b. b = new B(). } @Deprecated static void deprecatedMethod() { } } 140 . r = c.5 Annotations Introduced in J2SE 5. class Food {} class Hay extends Food {} class Animal { Food getPreferredFood() { return null. an annotation can indicate that a particular method or class should be overridden in a subclass or that certain compiler error messages shouldn't be printed. Annotations use the form @annotation and can be applied to methods or classes.callme().callme().util. using methods: import java.0.

Deprecated The @Deprecated annotation indicates that the marked method should no longer be used.0. } @Override //compiler error if getPreferredFood //overloaded. } @SuppressWarnings({"deprecation". Hay getPreferredFood() { return new Hay(). In the preceding example.suppressed raw. the compiler will generate an error message. the override annotation is used to indicate that the getPreferredFood method in the Horse class is overriding the getPreferredFood method in the Animal class.lang. "unchecked"}) void useDeprecatedMethod(List raw) { //deprecation warning . unless that warning is suppressed in the subclass.add(new Horse()).lang. As of J2SE 5. java.class Horse extends Animal { Horse() { return. } } java. java. Note that this method is returning a different type (Hay) than the superclass (Food) — this practice is called covariant return types.suppressed Animal. the compiler-based @Deprecation annotation replaces the Javadoc @deprecation tag. If a method marked with @Override does not override the same method in one of its superclasses.deprecateMethod().Override The @Override annotation indicates that a method defined in the current class must override a method is one of its superclasses. TM In the preceding example. Invoking or overriding the deprecatedMethod method will generate a compile-time warning. //unchecked warning . Note: The @deprecated tag used by the Javadoc tool achieves the same result as @Deprecation.lang. the deprecatedMethod in the Animal class is marked with the deprecated annotation.SuppressWarnings 141 . not overridden //Notice the return type is different //(covariant return type).

class SuperA { int x = 10. One interesting feature of Java member variables is that a class can access a hidden member variable through its superclass. the useDeprecatedMethod method in the Horse class uses the suppress warnings annotation to suppress both the unchecked and deprecation warnings that would otherwise occur.0 and some Java compiler implementations may suppress compiler warnings. For example. Consider the following superclass and subclass pair: class Super { Number aNumber. using the SuppressWarnings annotation on the entire Horse class is not recommended because genuine errors in the code might be hidden. // hides x in superclass void methodA() { 142 .aNumber super keyword allows a method to refer to hidden variables. In the preceding example.6 Hiding Member Variables Member variables defined in the subclass hide member variables that have the same name in the superclass. It is strongly recommended that you suppressed warnings only where necessary. } class Subbie extends Super { Float aNumber. but this feature won't be fully implemented in javac until release 6. But you can access Super's aNumber from Subbie with super.0. Another example of variable hiding. Note: This annotation can be used as of release 5. 6. } class SubA extends SuperA { int x = 20. } The aNumber variable in Subbie hides aNumber in Super.The @SuppressWarnings annotation indicates that the named compiler warnings should be suppressed.

out. which represents an abstract concept and should not be instantiated. apple. } } You can access a hidden variable by casting the object to its superclass. It can't be instantiated. } If you attempt to instantiate an abstract class. as such. the Number class makes sense only as a superclass to classes like Integer and Float. What you see instead are instances of carrot. It makes sense to model numbers in a program.java:6: class AbstractTest is an abstract class. Similarly in object-oriented programming. both of which implement specific kinds of numbers. Food represents the abstract concept of things that we all can eat. a class that you define represents an abstract concept and. System. new AbstractTest().println(“ x in SuperA :” + super. For example. System. An abstract class is a class that can only be subclassed-it cannot be instantiated.out. should not be instantiated. 6.7 Abstract Classes Sometimes. for example. with the syntax ((Superclass)object). A class such as Number.println(“ x in SubA :” + x). you may want to model an abstract concept without being able to create an instance of it. but it doesn't make sense to create a generic number object. Instead.x). use the keyword abstract before the class keyword in your class declaration: abstract class Number { . Take.out. the Number class in the java.System. } public static void main(String args[]) { new SubA().lang package represents the abstract concept of numbers. ^ 1 error Abstract class can contain static methods. and chocolate.name. . is called an abstract class. It doesn't make sense for an instance of food to exist. 143 . To declare that your class is an abstract class.println(“ x in SuperA :” + ((SuperA)this). the compiler displays an error similar to the following and refuses to compile your program: AbstractTest. .x). food in the real world.methodA(). Have you ever seen an instance of food? No.

to provide member variables and methods that were wholly shared by all subclasses. You can take advantage of these similarities and declare them all to inherit from the same parent object--GraphicObject. . In this way. they just differ in how they are drawn. The graphics objects cannot share these types of states or behavior. the abstract class can leave some or all of the implementation details of those methods up to its subclasses. int newY) { 144 . void moveTo(int newX.println("Equal"). } } 6. methods with no implementation. Each of these graphic objects share certain states (position. rectangles. draw). and so on. that is. else System. lines. thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface. . However.public abstract class test { public static void main(String [] args) { int x = 3. bounding box) and behavior (move. GraphicObject. but are implemented in entirely different ways (no default implementation in the superclass makes sense). all GraphicObjects must know how to draw themselves.8 Abstract Methods An abstract class may contain abstract methods. On the other hand.out. This is a perfect situation for an abstract superclass. Bezier curves. int y = 1.out. In an object-oriented drawing application. such as draw. you can draw circles. However. the graphic objects are also substantially different in many ways: drawing a circle is quite different from drawing a rectangle. such as the current position and the moveTo method. an abstract class can define a complete programming interface. First you would declare an abstract class. Let's look at an example of when you might want to create an abstract class with an abstract method in it. . if (x == y) System. The GraphicObject class would look something like this: abstract class GraphicObject { int x. y. GraphicObject also declares abstract methods for methods. that need to be implemented by all subclasses.println("Not equal"). resize.

} //Constructor public double getRadius() { return r.} . .14. . } } class Rectangle extends GraphicObject { void draw() { . } } class Rectangle extends Shape { protected double w. A subclass must override methods that are declared abstract in the superclass. // Instance data 145 . } class Circle extends Shape { public static final double PI = 3. } public double circumference() { return 2*PI*r. . public double area() { return PI*r*r. } abstract void draw(). protected double r. synchronized or a final method. // semicolon instead of body. } } An abstract class is not required to have an abstract method in it. . public abstract class Shape { public abstract double area(). An abstract method cannot be static. h. such as Circle and Rectangle. . class Circle extends GraphicObject { void draw() { . Each non-abstract subclass of GraphicObject. } //Accessor // implementation abstract methods.r = r. But any class that has an abstract method in it or that does not provide an implementation for any abstract methods declared in its superclasses must be declared as an abstract class. . // Instance data public Circle(double r) { this. // Abstract methods: note public abstract double circumference(). would have to provide an implementation for the draw method. or the subclass itself must be abstract.

you can declare your class to be final and thereby prevent any subclasses from being created. } public double getWidth() { return w.0. double h) { this.h = h. This class is so vital to the operation of the compiler and the interpreter that the Java system must guarantee that whenever a method or object uses a String it gets exactly a java. There are (at least) two reasons why you might want to do this: to increase system security by preventing system subversion. the bytecode verifier ensures that the subversion is not 146 . Security: One mechanism that hackers use to subvert systems is to create a subclass of a class and then substitute their class for the original.area(). } } class ShapeExample { public static void main(String args[]) { Shape[] shapes = new Shape[3]. This ensures that all strings have no strange. or unpredictable properties. } public double getHeight() { return h. The String class in the java. In addition. and for reasons of good object-oriented design. the compiler prints an error message and refuses to compile your program. } public double area() { return w*h.lang. // Create an array to hold shapes shapes[0] = new Circle(2. shapes[2] = new Rectangle(4.0). 2.lang package is a final class for just this reason. for(int i = 0. possibly causing damage or getting into private information. 3.9 Final Classes You can declare that your class is final. If you try to compile a subclass of a final class. this.0.0). To prevent this kind of subversion.length.0). undesirable.public Rectangle(double w. i < shapes. // Compute the area of the shapes } } 6. inconsistent. double total_area = 0.String and not some other string.w = w. that is. } public double circumference() { return 2*(w + h). i++) total_area += shapes[i]. // Fill in the array shapes[1] = new Rectangle(1. that your class cannot be subclassed. The subclass looks and feels like the original class but does vastly different things.

i = 40. use the keyword final before the class keyword in your class declaration.taking place at the bytecode level. int j = 1. To specify that your class is final. Design: You may also wish to declare a class as final for object-oriented design reasons. n. . n.java:6: Can't subclass final classes: class ChessAlgorithm class BetterChessAlgorithm extends ChessAlgorithm { ^ 1 error Another example of final class class SmallBrain {} final class Dinosaur { int i = 7. It does this by checking to make sure that a class is not a subclass of a final class. conceptually.f(). its declaration should look like this: final class ChessAlgorithm { .j++. } Any subsequent attempts to subclass ChessAlgorithm will result in a compiler error such as the following: Chess. your class should have no subclasses. void f() {} } // class Further extends Dinosaur {} // error: Cannot extend final class 'Dinosaur' public class Jurassic { public static void main(String[] args) { Dinosaur n = new Dinosaur(). For example. SmallBrain x = new SmallBrain(). if you wanted to declare your (perfect) ChessAlgorithm class as final. } } 147 . n. You may think that your class is "perfect" or that. .

Final Arguments class Gizmo { public void spin() {} } public class FinalArguments { void with(final Gizmo g) { // g = new Gizmo().6. you might want instead to make the nextMove method final: class ChessAlgorithm { . All methods of final class are implicitly final. some of its methods are final and some are not. final void nextMove(ChessPiece pieceMoved. .. the Object class does this.. As just shown. bf. } public static void main(String[] args) { FinalArguments bf = new FinalArguments().spin(). bf. instead of making your ChessAlgorithm class final. } . . // Illegal -. BoardLocation newLocation) { . } // void f(final int i) { i++.g is final g.spin(). } void without(Gizmo g) { g = new Gizmo(). .with(null). For example. } // Can't change // You can only read from a final primitive: int g(final int i) { return i + 1.g not final g. You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. } Final methods cannot be abstract methods.10 Final Methods Does creating a final class seem heavy-handed for your needs? Do you really just want to protect some of your class's methods from being overridden? You can use the final keyword in a method declaration to indicate to the compiler that the method cannot be overridden by subclasses. // OK -. . } } 148 .without(null).

Hence if the classes are of package type then they cannot be used outside the package. 149 . Technically. and the instantiation at runtime. If you want to use them outside the package declare them as public. you will have to import the package using import statement discussed in the next chapter. creates several instances of the same anonymous class. If the anonymous class extends another class. Because they don’t have a name. If not. If the base class is in the different package import the package and you can use the protected members. For this reason. It also creates a new instance of that class and returns it as the result of the statement. like any other regular class. That requires yet another form of the new statement. If the anonymous class implements an interface. anonymous classes are considered nonstatic inner classes. so they have the same privileges and limitations of nonstatic inner classes declared inside a method. there is no way to refer to them. their declaration must be given at creation time. Hence they can be used only by the classes in that package or by the classes in the unnamed package. its body can access the class’s members. override its methods. If you are not using packages. The private members in the base class are not inherited in the subclass. Notice that the declaration of the anonymous class is made at compile time.11 Access control and Inheritance When you are creating a subclass make sure that the super class is present in the same package.If a method is not final it can be overridden in the subclass. as follows: new <class or interface> <class’ body> This form of the new statement declares a new anonymous class that extends a given class. and so on. The protected members are inherited by the subclasses. then take care to save the subclass in the same directory as the baseclass as the directory acts as an unnamed package. as part of the new statement. That means that a new statement inside a for loop.12 Anonymous Inner Class Anonymous classes are classes that don’t have a name (hence the term anonymous). for example. its body must implement the interface’s methods. As seen above the object of the super class can use dynamic method 6. and not one instance of several different anonymous classes. Hence private methods in the base class are not overridden even though there is a method with the same name and same signature in the subclass. The members with no access specifier are of the type “package private”. 6.

passing an instance of the anonymous nested class: someMethod(new SomeClass() { /*body of the anonymous class goes here*/ }). if you want to use a non-default constructor instead. To define.: return new SomeClass(12) { /*body of the anonymous class goes here*/ }. An anonymous nested class must either implement an interface or extend a class. You might like to think of an anonymous nested class as part of a really long new statement. will call the SomeClass constructor which takes an int. in method scope. The following example calls someMethod(). but that doesn’t justify creating a whole new class.g. and which is why it has a ". as they do not have a name that you can use to declare the constructor method. Examples: public MyClass makeObj(final String name) { return new SubClassOfMyClass() { public String toString() { return "My name is "+name. which happens to contain a class definition. Anonymous classes are particularly useful for quickly creating event handlers in Swing applications. } }." at the end. In both cases SomeClass() is not the name of the anonymous class (anonymous means it has no name) rather is it the name of the class that you are extending or the interface you are implementing. the default constructor of that class is called. For example the following line causes the method to return an object which is an instance of an anonymous nested class: return new SomeClass() { /*body of the anonymous class goes here*/ }.Anonymous classes are great when you need to perform some task that needs an object. maybe because the needed class is too simple or because it's used only inside a single method. These classes cannot define a constructor. } Only final members of the outer class can be accessed in the methods of the anonymous inner class. but the implements or extends keywords are not used. 150 . an anonymous nested class that implements a specified interface: An anonymous nested class is defined where is it instantiated (in a method). If SomeClass() is a class. you supply arguments e.

clone().13 The Object class Methods of Object class protected native Object clone() throws CloneNotSupportedException Creates a new object of the same class as this object. An example of cloning an object: class Car extends Cloneable { String color. Car(String color) { this. } public String toString() { return color + “Colored Car”.color = color. } } 151 . } 6. A class indicates that its instances can be cloned by declaring that it implements the Cloneable interface. System.out.println(c1). No constructor is called. It then initializes each of the new object's fields by assigning it the same value as the corresponding field in this object. return new Object() { public String toString() { return objName.println(c2). System. } }.out. The clone method of class Object will only clone an object whose class indicates that it is willing for its instances to be cloned.public Object makeObj(String name) { final String objName = "My name is " + name. Car c2 = (Car)c1. } } class CloneExample { public static void main(String args[]) throws CloneNotSupportedException { Car c1 = new Car(“Red”).

then x. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup. For any reference value x. and z. public final native void notify() 152 . It is symmetric: for any reference values x and y. public final native Class getClass() Returns the runtime class of an object.public boolean equals(Object obj) Compares two Objects for equality. y. protected void finalize() throws Throwable Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.util. public native int hashCode() Returns a hash code value for the object. this method returns true if and only if x and y refer to the same object (x==y has the value true). x. then calling the hashCode method on each of the two objects must produce the same integer result.equals(null) should return false.equals(z) should return true. if x.equals(x) returns true. The equals method for class Object implements the most discriminating possible equivalence relation on objects. for any reference values x and y. but is otherwise ignored. that is. It is consistent: for any reference values x and y. This method is supported for the benefit of hashtables such as those provided by java. The finalize method in Object does nothing.equals(y) should return true if and only if y.equals(z) returns true. This integer need not remain consistent from one execution of an application to another execution of the same application. The equals method implements an equivalence relation:      It is reflexive: for any reference value x. x. multiple invocations of x. x. The general contract of hashCode is:   Whenever it is invoked on the same object more than once during an execution of a Java application.Hashtable. It is transitive: for any reference values x. the hashCode method must consistently return the same integer.equals(y) returns true and y.equals(y) consistently return true or consistently return false. Any exception thrown by the finalize method causes the finalization of this object to be halted.equals(x) should return true. If two objects are equal according to the equals method.

See the notify method for a description of the ways in which a thread can become the owner of a monitor. The current thread must own this object's monitor. The toString method for class Object returns a string consisting of the name of the class of which the object is an instance. the toString method returns a string that "textually represents" this object. For objects of type Class. public String toString() Returns a string representation of the object. 153 . The result should be a concise but informative representation that is easy for a person to read.Wakes up a single thread that is waiting on this object's monitor. public final void wait() throws InterruptedException Waits to be notified by another thread of a change in this object. See the notify method for a description of the ways in which a thread can become the owner of a monitor. By executing the body of a synchronized statement that synchronizes on the object. A thread waits on an object's monitor by calling one of the wait methods. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. In general. A thread waits on an object's monitor by calling one of the wait methods. public final native void notifyAll() Wakes up all threads that are waiting on this object's monitor. and the unsigned hexadecimal representation of the hash code of the object. This method should only be called by a thread that is the owner of this object's monitor. Only one thread at a time can own an object's monitor. This method should only be called by a thread that is the owner of this object's monitor. The thread then waits until it can re-obtain ownership of the monitor and resumes execution. It is recommended that all subclasses override this method. A thread becomes the owner of the object's monitor in one of three ways:    By executing a synchronized instance method of that object. by executing a synchronized static method of that class. This method should only be called by a thread that is the owner of this object's monitor. the at-sign character `@'.

This method should only be called by a thread that is the owner of this object's monitor. Summary 154 . See the notify method for a description of the ways in which a thread can become the owner of a monitor. The current thread must own this object's monitor. has elapsed. specified by timeout milliseconds plus nanos nanoseconds arguments. but it allows finer control over the amount of time to wait for a notification before giving up. The timeout period.public final native void wait(long timeout) throws InterruptedException Waits to be notified by another thread of a change in this object. See the notify method for a description of the ways in which a thread can become the owner of a monitor. has elapsed. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:   Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:   Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The timeout period. The current thread must own this object's monitor. specified by the timeout argument in milliseconds. int nanos) throws InterruptedException Waits to be notified by another thread of a change in this object. This method is similar to the wait method of one argument. The thread then waits until it can re-obtain ownership of the monitor and resumes execution This method should only be called by a thread that is the owner of this object's monitor. public final void wait(long timeout.

Except for the Object class. private d.true e. This is primarily true when an existing class creates a type whose features are close to.false true. Useful methods inherited from Object include toString. f. notify. c. Red color2 = new Red(). protected 155 .true. Questions 1.false false.true.false true.out. You can prevent a class from being subclassed by using the final keyword in the class's declaration. An abstract class can contain abstract methods — methods that are declared but not implemented.true.false. A class inherits member variables and methods from all its superclasses. } } What is the result of attempting to compile and run the program? a. equals. false. Run-time error j. clone.true i."+b2+". a class has exactly one direct superclass. boolean b3 = color2 instanceof Blue."+b3).false. and notifyAll. Similarly. it cannot be instantiated. A subclass can override methods that it inherits. Inheritance provides a formal mechanism for code reuse. wait. System. Subclasses provide the implementations for abstract methods. whether direct or indirect. true.false. When an existing class is extended to define a new class. the existing class is often called the superclass and the new class is often called the subclass. or it can hide variables or methods that it inherits.true false.true true. d. None of the above 2. but not identical to the features needed in the new type. An abstract class can only be subclassed. getClass. Which of the following modifiers can be applied to the declaration of a field? a. Compile-time error k. abstract b. All classes are descendants from this class and inherit methods from it. b.true. The subclass inherits all of the variables and all of the methods defined in the superclass and its superclasses. class Color {} class Red extends Color {} class Blue extends Color {} class A { public static void main (String[] args) { Color color1 = new Red(). g. The Object class is the top of the class hierarchy. boolean b1 = color1 instanceof Color.false. final c.print(b1+". you can prevent a method from being overridden by subclasses by declaring it as a final method.Extending an existing class often provides an easy way to create a new type. h. boolean b2 = color1 instanceof Blue.false false.

The compiler attempts to create a default constructor for class A. public class Basics {} class Basics1 {} protected class Basics2 {} private class Basics3 {} Class Basics4 {} // // // // // 1 2 3 4 5 Suppose these are top-level class declarations and not nested class declarations. An abstract class can be instantiated. a1[0] = new A11(). a3[0] = a3[1] = a3[2] = a2.out. b. e. System. Compile-time error at 1. 4 e. a2[0] = a2[1] = a1.java. An abstract class can not extend a concrete class. 1 b. An abstract class must declare at least one abstract method. c. d.}} } class A12 { public static void main(String[] arg) { A11[] a1 = new A11[1]. Compile-time errors are generated at which lines? a.e.print(a3[2][1][0]). An anonymous class can be declared abstract. public 3. class A {A(int i) {}} class B extends A {} // 1 // 2 Which of the following statements are true? a. The compiler attempts to create a default constructor for class B. 5 6. f. A11[][][] a3 = new A11[3][][]. 5. Which of the follow statements is true. a. } // // // // // // // 1 2 3 4 5 6 7 156 . class A11 {public String toString() {return "A11". An abstract class is implicitly final. A local class can be declared abstract. 3 d. d. and suppose that all of the declarations are contained in one file named Basics. Compile-time error at 2 4. c. A11[][] a2 = new A11[2][]. 2 c. b.

Run-time error None of the above 157 . Compile-time error at 3. Compile-time error at 7. g. Compile-time error at 2. i. d.What is the result of attempting to compile and run the program? a. Compile-time error at 5. e. j. h. f. Compile-time error at 6. k. c. Compile-time error at 4. Prints: null Prints: A11 Compile-time error at 1. b.

lines. and to control access. classes for reading and writing (input and output) are in java. . . to avoid naming conflicts.1 Packages To make classes easier to find and to use. . programmers bundle groups of related classes and interfaces into packages. too. 158 . such as circles. } You should bundle these classes and the interface in a package for several reasons: • • • You and other programmers can easily determine that these classes and interfaces are related. .Chapter 7 : Packages and Interfaces 7. The classes and interfaces that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java. You and other programmers know where to find classes and interfaces that provide graphics-related functions.java file public class Circle extends Graphic implements Draggable { . The names of your classes wont conflict with class names in other packages. . and points. .java file public interface Draggable { .lang. and so on. Definition: A package is a collection of related classes and interfaces providing access protection and namespace management. because the package creates a new namespace. . You also write an interface. rectangles.java file public abstract class Graphic { . You can put your classes and interfaces in packages.io. Let's look at a set of classes and examine why you might want to put them in a package. Suppose that you write a group of classes that represent a collection of graphic objects. Draggable. that classes implement if they can be dragged with the mouse by the user: //in the Graphic. } //in the Draggable.java file public class Rectangle extends Graphic implements Draggable { . } //in the Circle. } //in the Rectangle. .

println("Hi"). it does recommend that package names be used as directory names.they can use mixed case and be of any length.out. here are two files in the packagetest directory.println("Hello World").java package packagetest.greet(). While the Java Language specification does not put a limit on the length of a package name.You can allow classes within the package to have unrestricted access to one another yet still restrict access for classes outside the package.such as one named after the application. //ClassA. This helps avoid potential name space collisions. } } //ClassB. The package name must be the same as the enclosing directory. then the class in the source file is placed in the unnamed package. package names start with a lowercase letter. class ClassB { static void greet() { System. Conventionally. The unnamed package is often used when creating classes for small applications. class ClassA { public static void main(String[] args) { ClassB. } } Note that these source files must be named ClassA. If the package declaration is not given. Package names are identifiers . public class HelloWorld { public static void main(String[] args) { System. be limited to 1024 characters total.java package packagetest. It is recommended to use package names of a dozen characters or less.java (case matters) and they must be in a directory named packagetest. UNIX operating systems typically require that the full path to a file. Another example of creating a package package world. For example.java and ClassB. for larger projects all code should be placed in a named package . Package declarations Each file must have a package declaration which precedes all non-comment code. from root through file name. However. 159 .out.

but not in the java command..defineClass(ClassLoader. To compile the classes: javac packagetest/ClassB. for the parent directory. If you used to play around with DOS or UNIX. we just go to the world directory and type the command: C:\world>javac HelloWorld.ClassLoader.lang. When compiling HelloWorld class.java If you try to run this HelloWorld using java HelloWorld. Setting up the CLASSPATH If the HelloWorld class is saved as described above the classpath can be set as follows. you must be outside the packagetest directory.NoClassDefFoundError: HelloWorld (wrong name: world/HelloWorld) at java.java javac packagetest/ClassA. you will get the following error: Exception in thread "main" java.defineClass0(Native Method) at java.C:\.. you may be familiar with .lang.java:442) C:\world>java HelloWorld 160 . On the command prompt type this set CLASSPATH=. as an alias for the current directory and . In our CLASSPATH we include this for convenient reason. We set the CLASSPATH to point to 2 places. We use . Also. we use . java packagetest. Generally use a forward slash ("/") because it is used more commonly than the backslash in other places as well.ClassLoader.. Java will find our class file not only from C: directory but from the current directory as well.} } Create a folder world in c: drive and save the class file as HelloWorld. (dot dot).java To run the main program in ClassA. (semicolon) to separate the directory location in case we keep class files in many places.lang. . (dot) and C:\ directory.java Compiling and running packages from a command line To compile the above example.ClassA or java packagetest/ClassA In windows the "/" can be replaced by the "\" in the javac command. (dot) and .

rendering.java:290) at sun. If we want to run it.ClassLoader. we have to tell JVM about its fully-qualified class name (world.java:191) at java. to create nested packages.lang.java:248) at java.net.HelloWorld) instead of its plain class name (HelloWorld). class MyClass { } 7.security.SecureClassLoader. package abc. separated by dots.loadClass(ClassLoader.misc.2 Using package members Only public package members are accessible outside the package in which they are defined.access$1(URLClassLoader. etc. Within the "vis" package may be several more nested packages to do data management.java:101) at java.loadClass(ClassLoader.vis.renderer.java:247) The reason is right now the HelloWorld class belongs to the package world.HelloWorld C:\world>Hello World Note: fully-qualified class name is the name of the java class that includes its package name Nesting packages Package declarations may be a string of names.net. For instance. 161 .URLClassLoader.URLClassLoader. Circle etc.AccessController.java:197) at java. To use a public package member from outside its package.security. such as Rectangle.doPrivileged(Native Method) at java.java:286) at java. C:\world>java world.lang.defineClass(SecureClassLoader.loadClass(Launcher. there may be a project "abc" package in which are found several nested packages for "vis" work. the examples in this book have referred to types by their simple names. and so forth.at java.URLClassLoader.URLClassLoader$1. This is useful for creating a hierarchy of packages. You can use a package member's simple name if the code you are writing is in the same package as that member or if that member has been imported. "database" work.net.Launcher$AppClassLoader.findClass(URLClassLoader.ClassLoader.defineClass(URLClassLoader.net.run(URLClassLoader.java:216) at java. you must do one or more of the following: • • • Refer to the member by its long (qualified) name Import the package member Import the member's entire package Referring to a Package Member by Name So far.

You'll find that using long names is okay for one-shot uses. But you'd likely get annoyed if you had to write packagetest. For example. ClassB objB = new ClassB(). The asterisk in the import statement can be used only to specify all the classes within a package. Now you can refer to the ClassA class by its simple name: ClassA obj = new ClassA(). the following does not match all the classes in the packagetest package that begin with C: 162 .*. Now you can refer to any class or interface in the graphics package by its short name: ClassA obj = new ClassA(). In such cases. if there is one. if you are trying to use a member from a different package and that package has not been imported. Importing an Entire Package To import all the types contained in a particular package. use the import statement with the asterisk (*) wildcard character: import packagetest.ClassA. It cannot be used to match a subset of the classes in a package.ClassA again and again. as shown here. which includes the package name. you can just import the member instead.ClassA You could use this long name to create an instance of packagetest. you must use the member's qualified name. Also. you can import the entire package. But if you use many types from a package.ClassA obj = new packagetest. This approach works well if you use just a few members from the packagetest package. This is the qualified name for the ClassA class declared in the packagetest package in the previous example: packagetest. Importing a Package Member To import a specific member into the current file. Here's how you would import the ClassA class from the packagetest package created in the previous section: import packagetest.However. packagetest. your code would get messy and difficult to read.ClassA(). put an import statement at the beginning of your file before any class or interface definitions but after the package statement.

Square.regex. you have to be more specific and use the member's qualified name to indicate exactly which Rectangle class you want: graphics.util.regex. 163 . In such a situation. the following is ambiguous: Rectangle rect. the Java compiler automatically imports three entire packages:   The default package (the package with no name) The java. lets consider that you have created this package package graphics.util.*) simply Pattern. Note: Another. With the import statement. For example. you generally import only a single package member or an entire package. For example. You must always refer to it as either java.awt have been imported. If a class contains package declaration. you could import ClassB and its inner classes this way: import packagetest. Don’t import unnecessary classes. you must refer to each member by its qualified name. For your convenience.import packagetest.util. class Rectangle { } The java. importing java.*.Rectangle rect. less common form of import allows you to import only a class and its public inner classes. it generates a compiler error. like ClassB.lang package Note: Packages aren't hierarchical. import statement and class definition they should be written only in the same given order.Pattern or (if you import java. // does not work Instead. If both graphics and java.Rectangle and ClassB. Avoid duplicating import statement.awt package also contains a Rectangle class.ClassB. if the packagetest. Disambiguating a Name If by some chance a member in one package shares the same name with a member in another package and both packages are imported.Pattern.* doesn't let you refer to the Pattern class as regex. Also there is no need to import the classes in the same package.ClassB class contained useful inner classes. For example.C*.

Also. } greaterEqual(Object m){ .7. . public class { . (Classes do not. _none_ of the methods are implemented. but are discouraged from doing so as the marking is considered obsolete practice. . . boolean greaterEqual(Object m). } 164 . or synchronized in a member declaration in an interface. . . . You can mark them as such. } Polynomial multiply(Polynomial P){ .) There are almost no disadvantages to multiple inheritance of interface (small name conflict problems are one exception). Interfaces are also considered to be the way Java gains some of the benefits of multiple inheritance without the drawbacks. you cannot use transient. This means that a programmer creates something that obliges other programmers to follow a set of conditions. boolean greater(Object m). The interfaces themselves need not be public and several interfaces in the standard libraries are not public and thus used only internally. . For example public interface Comparable { boolean less(Object m). . An interface creates a protocol that classes may implement. volatile. boolean boolean boolean boolean Polynomial implements Comparable less(Object m){ . boolean lessEqual(Object m). . } greater(Object m){ . . . you may not use the private and protected specifiers when declaring members of an interface. } lessEqual(Object m){ . .3 Interfaces Interfaces are part of what is known as “programming by contract”. . } All instance methods are implicitly public and abstract. There is no code at all associated with an interface. One can actually extend several interfaces. In Java an interface is similar to an abstract class in that its members are not implemented. } . Note that one can extend an interface (to get a new interface) just as you can extend a class. All constant values defined in an interface are implicitly public. static. and final. Member declarations in an interface disallow the use of some declaration modifiers. In interfaces. The Polynomial class that implements Comparable will need to implement all of the functions declared in the interface. Interfaces thus enjoy the benefits of multiple inheritance. .

as follows: class Driver { public Car getCar( Car c){ .the effects on the development cycle are considerable. The Driver object requires knowledge of the Car object and has access to all public methods and variables contained within that object. Class Car will implement the interface by providing a start() method.A class may choose to implement any number of interfaces. To code the Driver object using interfaces. The Driver object can be written without interfaces. Also. 165 . an abstract class can choose to implement part of an interface leaving the rest for non-abstract subclasses. we can create another object called Driver. } class Car implements Vehicle{ // Required to implement Vehicle public void start(){ . but it forever links the Driver object with that of the Car. Consider the simple example of a class Car that implements interface Vehicle.. the following implementation could be used: class Driver{ public Vehicle getVehicle( Vehicle c) { } . } } Having laid the foundations of the Car object.. Other functionality in the Car class has been left out for the sake of clarity. Interface Vehicle has a single method called start(). The usefulness of interfaces goes far beyond simply publishing protocols for other programmers. In this situation.changing the references from Car to Vehicle -.. It is best to avoid such tight coupling of code because it increases dependencies and reduces flexibility.. interface Vehicle { // All vehicle implementations must implement the start //method public void start(). Using the second implementation.. the Driver has knowledge only of the methods and variables defined in the Vehicle interface. Any other public methods and data contained in the specific implementation of the Vehicle interface are hidden from the user of the Vehicle object. the two objects are said to be tightly coupled. A class that implements an interface must provide bodies for all methods of that interface. It is the Driver's job to start the Car and bring it to the restaurant patron. This code example satisfies the functional requirements of the system.. } } The Driver object has a method called getCar that returns a Car object. } While the code changes are fairly minor -.

m2(" + s + ")". } public class Base { public String m1() { return "Base. } private String p() { return "Base. Consider the following interface and class definitions: interface Foo { String m3().m1". That guarantees that objects instantiated from concrete classes possess implementation code for all the operations of each type specified in the implements clause.p()". } public String m3() { return "Derived. and has therefore eliminated the possibility that developers will use undesirable methods.m1()". } } 166 . } public String m2( String s ) { return "Base. Defining object types with interfaces The Java interface keyword declares a type and the implements keyword guarantees that a class either implements or defers the implementation of all operations for each type specified in the implements clause. } } public class Derived extends Base implements Foo { public String m1() { return "Derived.m3()".This simple code change has ensured the proper concealment of information and implementation from other objects.

Incompatible variable types prevent this attempt to attach a variable to the very object to which it is already attached.Interface Foo declares a new type. the type-checker rejects the second statement in Section 2 since type Foo does not possess operation m1(). Foo foo = derived. System. Base base = derived. The third statement similarly passes type-checking.println( base. the type-checker overrules the underlying Derived object's ability to perform the specified method call by enforcing variable type conformance. not the attached object type. the type-checker rejects the section's third statement.println( derived. Let's examine the ramifications of these type definitions. The additional implements Foo clause means type Derived also subtypes Foo. The type-checker enforces conformance between the type Derived variable and the type Foo variable by verifying that Derived actually subtypes Foo.println( derived. Thus you achieve multiple type inheritance: type Derived subtypes type Base and type Foo. and that object has implementation for both the m1() and m3() methods.m1() ).out. // REJECT // REJECT Section 1 calls method m3() through three different reference variable types. Similarly.println( foo. with a single operation.m3() ).out. Remarkably. Base base = derived. Derived derived = new Derived(). Note that these conformance checks consider the variable type.m1() ). System. In the rejected statements. System. // call m1() System. The definition of class Derived differs from before only by the addition of the implements Foo clause. // REJECT The first statement attaches a type Derived variable to a type Derived object-creation expression. Implementing multiple inheritance in Java If you want to write something similar to: 167 . System. Foo foo = derived.println( base. even though foo and base point to the same object.out.out.out. Foo. Now let's take a look at method invocation via the different variable types. Since type Base does not possess operation m3().m1() ). Derived derived = new Derived(). foo = base. m3(). The second statement attaches a variable of type Foo to the created object. the three variables remain attached to the same object for every method call.m3() ). The typechecker rejects the fourth statement since Foo does not subtype Base.m3() ). // call m3() System.out.println( foo.

In other words. An Interface can only declare constants and instance methods.) In Java.util.//this code will give compile time error public class Employee extends Person. you would have everything necessary to define and implement an Employee class. implicitly inheriting all of the super-interface operations. java.Date getHireDate().multiple implementation inheritance is not a feature of Java. For example: interface File { 168 . a class can implement multiple interfaces. contains additional methods. but cannot implement default behavior. Employment { // detail omitted } Here. each subinterface must be explicitly listed as extending one or more other interfaces. Java allows a class to have a single superclass and no more.. } and the EmployeeLike interface is: public interface EmployeeLike { float getSalary(). Inheriting implementation from more than one superclass .EmploymentLike { //details omitted } Difference between an Interface and an Abstract class An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. int getAge(). If you could only put them together. Suppose the PersonLike interface is: public interface PersonLike { String getName().e. An abstract class can have instance methods that implement a default behavior. Java supports multiple interface inheritance. On the other hand. Person is a concrete class that represents a person. while Employment is another concrete class that represents the details of a person who is employed. } You can create an Employee class like this : public class Employee implements PersonLike. Subinterfaces One interface may be described as a subinterface of another if it extends its properties (i.

} 7. contain static constants that are used within the class and are also useful outside the class.PI.0. For occasional use. the only way to access those constants was by fully spelling out the names Math.public void open(String name).E. but if constants from another class are used extensively. the java. BorderLayout. in your code. For example. } interface ReadWriteFile extends ReadableFile. and NORTH without all the extra typing. Then in the code body you can use double area = PI * radius * radius. WritableFile { public void seek(int position). Prior to Java version 5.lang.Math class contains the constants PI and E for pi and e.*. } interface WritableFile extends File { public void writeByte(byte b).PI * radius * radius. To use static imports. For example. Wildcards also work in the import static statement: import static java. In addition to the constants.Math. Math.Math. then the static import feature will reduce the code and also make it easier to read. you can use just PI. E. } interface ReadableFile extends File { public byte readByte(). 169 . public void close().4 Static Import Many classes. respectively.lang. With static imports.PI. instead of double area = Math. double logarithm = log (number). simply typing the Math.NORTH.lang. including many in the Java core libraries. all the many static methods in the Math class are also available when you use the wildcard static import line above.PI is probably easier. add the static keyword to the import statement as follows: import static java. etc.

static final double OMEGA = 901.0 } Any class that needs these constants can implement MyConstantsImpl. An alternative is to put the constants into an interface. 170 .0 + MyConstants. final static double OMEGA = 901.1*ALPHA)/(1. say that you need the constants ALPHA and OMEGA for several different programs.instead of double logarithm = Math. The first option is to create a utility class that holds the constants. This will not interfere with the class design since there is no limit to the number of interfaces that a class can implement.0 } Then in your other classes. Interfaces with Constants Only Before the static import became available.OMEGA However. Then a method in the class that implements MyConstantsImpl could use the constants in an equation without the class reference: x = (3.1.: public class MyConstants { final static double ALPHA = 1. whcih is far more readable. The methods in the program will then refer to the constants simply with ALPHA and OMEGA.1.g.log (number).0 + OMEGA). e.OMEGA). public interface MyConstantsImpl { static final double ALPHA = 1. placing the MyConstants class name wherever these constants appear can be tedious and also makes the code less readable.ALPHA)/(1. For example. especially in a formula like x = (3. you would refer to these constants with MyConstants. a trick for avoiding the need to write the class name for static constants was to create an interface whose only purpose is to hold constants.ALPHA MyConstants.1 * MyConstants.

You would not think of a class that implements MyConstantsImpl as a MyConstants object in the sense of taking on an identifiable behavior of an interface. however. then the class. So too are all classes. violates the object-oriented design of the language. That is. instance initializers.5 strictfp The keyword "strictfp" is used to control certain aspects of floating-point arithmetic. and method declarations. You can use strictfp as a modifier of class. constructors. Methods within interfaces cannot be declared using strictfp because this is an implementation rather than an interface property. they are FP-strict only if their defining class is FP-strict. interface.This technique. any expression that occurs within the class or method is an FP-strict expression. Because constructors cannot be declared using strictfp. or if it is a compile-time constant expression. methods. and static initializers within the declaration. In practical terms. interface. So what does FP-strict actually mean? Consider the following example: public strictfp class FpDemo3 { public static void main(String[] args) { double d = 8e+307." If a class. or method is FP-strict. 171 . interfaces. you are not really implementing anything. An expression is FP-strict if it occurs anywhere within one of these FP-strict declarations. variable initializers. like this: // legal uses of strictfp strictfp interface A {} public strictfp class FpDemo1 { strictfp void f() {} } You cannot use strictfp on constructors or methods within interfaces: // illegal uses of strictfp interface A { strictfp void f(). this means that if a class or method is declared with strictfp. So constants-only interfaces are ill advised and considered bad programming style . } public class FpDemo2 { strictfp FpDemo2() {} } The strictfp keyword is used to designate an expression as "FP-strict. Use a class instead and then statically import the class. interface. 7. or method is declared using strictfp.

} } The maximum value of a double (Double.8e+308. Questions 1. which is larger than Double.5 != 4.MAX_VALUE) is approximately 1. an implementation is allowed to use an extended exponent range to represent intermediate results. They are also helpful while using multiple inheritance.0 * d). Interfaces are used as a programming discipline. It helps you to use the class members without using the class name.0. System.println(4. By contrast. use FP-strict rules everywhere. if the expression is not FP-strict. you can know that the floating-point arithmetic in your application behaves the same when you move your application to a different Java implementation or hardware platform. the result is 32e+307 or 3.0 * d * 0. in that: (4.5).0 * d) * 0.5 because the Java programming language guarantees a left-to-right order of evaluation. Note that multiplication in this example is not associative.0 * (d * 0. this could keep the expression from overflowing. and produce a final result that is within range. interface I1 {} interface I2 {} class Base implements I1 {} class Sub extends Base implements I2 {} class Red { public static void main(String args[]) { 172 .6e+308.2e+308. The static import is a new concept of J2SE 5. This is true even though the later multiplication by 0. Summary Packages are important as they act as a namespace.MAX_VALUE. the first expression is evaluated as: (4. the implementation is required to evaluate the whole expression as resulting in positive infinity (which the program prints as "Infinity"). which is less than Double.println(2. They help to avoid conflict in classes and you can group the related classes together as a single package. Because the expression is FP-strict.MAX_VALUE. When the first part of the expression is evaluated. In other words.0 * d) * 0. in effect.5 produces a final value for the expression of 1.out.5) strictfp is important because its use guarantees common behavior across different Java implementations. it can. An implementation is not required to do this.out. In the FpDemo3 example.System. In the FpDemo3 example.

Sub s2 = (Sub)base. d. Base base = s1. 1 2 3 4 None of the above 173 . b. e. I1 i1 = s1. // // // // 1 2 3 4 A compile-time error is generated at which line? a. I2 i2 = s1. c.} } Sub s1 = new Sub().

} private void m3() {System.m1.m2.out.out. // 2 a. "). a.m2().java. None of the above 174 . A.dan.m3(). "). b.} void m4() {System.print("A.print("A. Compile-time error at 1.out. Compile-time error at 3. Compile-time error at 4.m4.m4(). // 4 }} Assume that the code appears in a single file named A. // 1 a. A.} } class B { public static void main(String[] args) { A a = new A(). A. e. // 3 a. public class A { public void m1() {System.m2.m4.chisholm. "). d.2.out.m1().print("A. package com.print("A.} protected void m2() {System. f. Compile-time error at 2.m1. ").m3. c. Prints: A.m3. What is the result of attempting to compile and run the program? a.

If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler. The term exception is shorthand for the phrase "exceptional event.Chapter 8 : Assertions and Exception handling 8. the runtime system leaps into action to find someone to handle the exception. The runtime system searches backwards through the call stack. By using exceptions to manage errors. including its type and the state of the program when the error occurred. to simple programming errors. the method creates an exception object and hands it off to the runtime system. the runtime system (and consequently the Java program) terminates. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. The exception handler chosen is said to catch the exception. until it finds a method that contains an appropriate exception handler. beginning with the method in which the error occurred. Java programs have the following advantages over traditional error management techniques: • • • Advantage 1: Separating Error Handling Code from "Regular" Code Advantage 2: Propagating Errors Up the Call Stack Advantage 3: Grouping Error Types and Error Differentiation Advantage 1: Separating Error Handling Code from "Regular" Code In pseudo-code. The runtime system is then responsible for finding some code to handle the error. In Java terminology. your function might look something like this: readFile { 175 . The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. When such an error occurs within a Java method. Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception. such as a hard disk crash. The exception object contains information about the exception. An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. such as trying to access an out-of-bounds array element. creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception." Many kinds of errors can cause exceptions--problems ranging from serious hardware errors.1 What is an Exception? The Java language uses exceptions to provide error-handling capabilities for its programs.

} There's so much error detection. read the file into memory. And worse yet. reporting and handling. } return errorCode. if (readFailed) { errorCode = -1. } } else { errorCode = -3. but it ignores all of these potential errors: • • • • • What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed? To answer these questions within your read_file function. } close the file. open the file. determine its size. if (gotTheFileLength) { allocate that much memory. if (theFileDidntClose && errorCode == 0) { errorCode = -4. 176 .} open the file. } else { errorCode = errorCode and -4. } } else { errorCode = -2. if (theFileIsOpen) { determine the length of the file. and returning that the original 7 lines of code are lost in the clutter. if (gotEnoughMemory) { read the file into memory. allocate that much memory. reporting. the logical flow of the code has also been lost in the clutter. close the file. you'd have to add a lot of code to do error detection. } } else { errorCode = -5. Your function would end up looking something like this: errorCodeType readFile { initialize errorCode = 0. At first glance this function seems simple enough.

If your read_file function used exceptions instead of traditional error management techniques. Suppose that the readFile method is the fourth method in a series of nested method calls made by your main program: method1 calls method2. } catch (sizeDeterminationFailed) { doSomething. } method3 { call readFile. } catch (memoryAllocationFailed) { doSomething. which finally calls readFile. allocate that much memory. Java provides an elegant solution to the problem of error management: exceptions. method1 { call method2. } catch (fileOpenFailed) { doSomething. } catch (readFailed) { doSomething. Exceptions enable you to write the main flow of your code and deal with the. exceptional cases elsewhere. it would look something like this: readFile { try { open the file. close the file. } catch (fileCloseFailed) { doSomething. which calls method3. determine its size. read the file into memory. } 177 .making it difficult to tell if the code is doing the right thing: Is the file really being closed if the function fails to allocate enough memory? It's even more difficult to ensure that the code continues to do the right thing after you modify the function three months after writing it. } method2 { call method3. Many programmers "solve" this problem by simply ignoring it--errors are "reported" when their programs crash. well. } } Advantage 2: Propagating Errors Up the Call Stack A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods.

method1 { errorCodeType error. } method3 throws exception { call readFile. else proceed. Thus only the methods that care about errors have to worry about detecting errors. } errorCodeType method3 { errorCodeType error. if (error) return error. if (error) doErrorProcessing. Traditional error notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1-the only method that is interested in them. method1 { try { call method2. } } method2 throws exception { call method3. } catch (exception) { doErrorProcessing. thereby allowing a method further up the call stack to catch it. else proceed. } 178 . } The Java runtime system searches backwards through the call stack to find any methods that are interested in handling a particular exception. error = call method2. error = call method3. error = call readFile. if (error) return error. A Java method can "duck" any exceptions thrown within it. } errorCodeType method2 { errorCodeType error.Suppose also that method1 is the only method interested in the errors that occur within readFile. else proceed.

Advantage 3: Grouping Error Types and Error Differentiation Often exceptions fall into categories or groups. including those errors specifically represented by one of its subclasses. Thus a method informs its callers about the exceptions that it can throw. The code that uses exceptions is more compact and easier to understand.However. Java exceptions must be instances of Throwable or any Throwable descendant. Note again the difference in the bloat factor and code obfuscation factor of these two error management techniques. Any checked exceptions that can be thrown within a method are part of that method's public programming interface and must be specified in the throws clause of the method. . . as you can see from the pseudo-code. One way a method can catch exceptions is to catch only those that are instances of a leaf class. . Each "leaf" class (a class with no subclasses) represents a specific type of exception and each "node" class (a class with one or more subclasses) represents a group of related exceptions. . you can create subclasses of the Throwable class and subclasses of your subclasses. ArrayException is a subclass of Exception (a subclass of Throwable) and has three subclasses. 179 . ElementTypeException. and NoSuchElementException are all leaf classes. For example. As for other Java classes. an exception handler would specify an ArrayException argument: ArrayException catch (ArrayException e) { . For example. an exception handler that handles only invalid index exceptions has a catch statement like this: catch (InvalidIndexException e) { . } is a node class and represents any error that can occur when manipulating an array object. to catch all array exceptions regardless of their specific type. A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement. InvalidIndexException. ducking an exception does require some effort on the part of the "middleman" methods. so that the callers can intelligently and consciously decide what to do about those exceptions. Each one represents a specific type of error that can occur when manipulating an array.

such as the one shown here.lang. pointer exceptions (such as trying to access an object through a null reference). including I/O Exceptions. Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. runtime exceptions. the compiler checks that these exceptions are caught or specified. .Throwable class. can make your code more error prone by catching and handling exceptions that you didn't anticipate and therefore are not correctly handled within the handler. 8.2 Types of Exceptions All exception classes are the subclass of java.} This handler would catch all array exceptions including InvalidIndexException. and exceptions of your own creation. although you can. The Throwable Class and Its Subclasses 180 . and NoSuchElementException. ElementTypeException. Thus the compiler does not require that you catch or specify runtime exceptions. Checked exceptions are exceptions that are not runtime exceptions and are checked by the compiler. and indexing exceptions (such as attempting to access an array element through an index that is too large or too small). You can find out precisely which type of exception occurred by querying the exception handler parameter e. Runtime exceptions are those exceptions that occur within the Java runtime system. This includes arithmetic exceptions (such as when dividing by zero). The cost of checking for runtime exceptions often exceeds the benefit of catching or specifying them. . } Exception handlers that are too general. Java has different types of exceptions. to name a few. You could even set up an exception handler that handles any Exception with this handler: catch (Exception e) { .

it's unlikely that typical Java programs will ever throw Errors either. you get the ability to throw an exception without specifying that you do so. A NullPointerException can occur anywhere a program tries to dereference a reference to an object. Errors When a dynamic linking failure or some other "hard" failure in the virtual machine occurs. What does it cost you if you throw a RuntimeException or create a subclass of RuntimeException just because you don't want to deal with specifying it? Simply. although you can. You can create your own RuntimeException subclasses. the cost of checking for runtime exceptions exceeds the benefit of catching or specifying them. IllegalAccessException signals that a particular method could not be found. For example. These descendants indicate various types of exceptions that can occur. Runtime Exceptions The RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime)." 181 .Throwable has two direct descendants: Error and Exception. In other words. Thus the compiler does not require that you catch or specify runtime exceptions. when is it ever good to avoid documenting a method's behavior? The answer is "hardly ever. Typically. An example of a runtime exception is NullPointerException. The Exception class has many descendants defined in the Java packages. However. a method is not required to specify that it throws RuntimeExceptions. it is a way to avoid documenting the exceptions that a method can throw. When is this good? Well. and NegativeArraySizeException indicates that a program attempted to create an array with a negative size. The cost of checking for the exception often outweighs the benefit of catching it. The Java packages define several RuntimeException classes. which occurs when a method tries to access a member of an object through a null reference. In addition. the virtual machine throws an Error. Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. You can catch these exceptions just like other exceptions. Typical Java programs should not catch Errors. One Exception subclass is RuntimeException. Exceptions Most programs throw and catch objects that derive from the Exception class.

Or you could put all of the statements within a single try statement and associate multiple handlers with it. You could put each statement that might potentially throw an exception within its own try statement.8.println("Value at: " + i + " = " + victor.elementAt(i)).3 Catching and Handling Exceptions The first step in writing an exception handler is to enclose the statements that might throw an exception within a try block.true). a try block looks like this: try { Java statements } The segment of code labelled Java statements is composed of one or more legal Java statements that could throw an exception. The try Block The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. try { System. and provide separate exception handlers for each try. out = new PrintWriter(new FileWriter("OutFile.out. In other words. if an exception occurs within the try statement. A try statement must be accompanied by at least one catch block or one finally block. i++) out. Next. Java's finally block provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block.txt"). you associate exception handlers with a try block by providing one or more catch blocks directly after the try block.println("Entering try statement"). The try block is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequent catch blocks) associated with it. 182 . that exception is handled by the appropriate exception handler associated with this try statement. } The try statement governs the statements enclosed within it and defines the scope of any exception handlers associated with it. Use the finally block to close files or release other system resources. In general. for (int i = 0. i < size. The following listing uses one try statement for the entire method because the code tends to be easier to read. PrintWriter out = null.

. .getMessage()). . and only objects that derive from Throwable can be thrown. . .err. .The catch Block(s) The try statement defines the scope of its associated exception handlers. These statements are executed if and when the exception handler is invoked. The argument to the catch statement looks like an argument declaration for a method. . SomeThrowableObject. The runtime system invokes the exception handler when the handler is the first one in the call stack whose type matches that of the exception thrown. The argument type. try { . } catch (ArrayIndexOutOfBoundsException e) { System. . An example of using multiple catch blocks 183 . The general form of Java's catch statement is: catch (SomeThrowableObject variableName) { Java statements } As you can see. When Java programs throw an exception they are really just throwing an object. . ) { ) { There can be no intervening code between the end of the try statement and the beginning of the first catch statement. If the superclass catch block is written first then the catch block of subclass becomes unreachable and gives compile-time error.getMessage()). . . . } When you have to write multiple catch blocks and the exception classes in the blocks are related to each other then take care to write the catch block for the subclass first and then the catch block for the superclass. . . You associate exception handlers with a try statement by providing one or more catch blocks directly after the try block: try { . the catch statement requires a single formal argument. } catch (IOException e) { System. The catch block contains a series of legal Java statements.println("Caught IOException: "+e. } catch ( . } catch ( .lang package. declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class defined in the java. } .println("Caught ArrayIndexOutOfBoundsException:" + e. . .err.

} } Catching Multiple Exception Types with One Handler Each handles only one type of exception. The closest common ancester of IOException and ArrayIndexOutOfBoundsException is the Exception class. .class MultiCatch { public static void main (String args[]) { try { int a = args.out.length. c[42] = 99.println("a = " + a). An exception handler that handles both types of exceptions looks like this: try { . .println ("Array Index oob:" + e). The finally Block The final step in setting up an exception handler is providing a mechanism for cleaning up the state of the method before (possibly) allowing control to be passed to a different part of the program. } catch (Exception e) { System. 184 .println ("After try/catch blocks. System. int c[] ={ 1 }.println("Exception caught:"+e. The Java language allows you to write general exception handlers that handle multiple types of exceptions.out. } catch (ArithmeticException e) { System.out.out. You do this by enclosing the cleanup code within a finally block. int b = 42 / a .err."). Also. exception handlers that are too general can make code more error prone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not intended. Your exception handler can be written to handle any class that inherits from Throwable.println ("Divide by 0:" + e). } catch (ArrayIndexOutOfBoundsException e) { System. } Handlers that can catch most or all exceptions are typically useless for error recovery because the handler has to determine what type of exception occurred anyway to determine the best recovery strategy. } System.getMessage()).

Regardless of whether control exits the writeList method's try block due to one of the three scenarios listed previously.out. getMessage is a method provided by the Throwable class that prints additional information about the error that occurred. the code within the finally block will be executed.out.getStackTrace(). This is the finally block for the writeList method. The Throwable class also implements two methods for filling in and printing the contents of the execution stack when the exception occurred. out. for (int i = 0. You access the instance variables and methods of exceptions in the same manner that you access the instance variables and methods of other objects. The following code shows how to call the getStackTrace method on the exception object: catch (Exception cause) { StackTraceElement elements[] = cause.close().println(elements[i]. A stack trace is a useful debugging tool that you'll normally take advantage of when an exception has been thrown.getLineNumber() + ">> " + elements[i]. } } Displaying a description of an exception Throwable overrides the toString() so that it returns a string containing a description of the exception.The runtime system always executes the statements within the finally block regardless of what happens within the try block.getFileName() + ":" + elements[i]. You can display this description in a println() statement by simply passing the exception as an argument.println("Closing PrintWriter"). i++) { System. } } Nested try statements 185 . n = elements. It cleans up and closes the PrintWriter. Accessing Stack Trace Information Definition: A stack trace provides information on the execution history of the current thread and lists the names of the classes and methods that were called at the point when the exception occurred. i < n.getMethodName() + "()"). finally { if (out != null) { System. } else { System.err.println("PrintWriter not open").length.

which calls the method.out. If no catch statement matches.*/ if( a = 2 ) { int c [] = { 1 }. // division by zero /* if two command line arg is used . then the Java runtime system will handle the exception. class NestTry { public static void main (String args[]) { try { int a = args. You can enclose a call to a method within a try block.Each time a try statement is entered. Inside that method is another try statement.println(“a = “ + a).println(e). or until the entire nested try statements are exhausted. c[ 42 ] = 99. /* if no command-line args are present the following statement will generate a divide-by-zero exception*/ int b = 42 / a. In this case. the try statement within the method is still nested inside the outer try block. the stack is unwound and the next try statement’s catch handlers are inspected for a match. Nesting of try statements can occur in less obvious ways when method calls are involved. then generate an out of bounds exception . This continues until one of the catch statements succeeds. System. the context of that exception is pushed on the stack.out. If an inner try statement does not have a catch handler for a particular exception. //generate an out of bound exception } } catch (ArrayIndexOutOfBoundsException e) { System. } } catch (ArithmeticException e) { 186 . try //nested try block { /* if one command line arg is used . then a divide-by-zero exception will be generated by the following code*/ if (a == 1) a = a / (a – a). //An Example of nested try statements.length.

if (size == 0) throw new EmptyStackException(). return obj. 2) C:\> java NestTry One a = 1 divide by zero 3) C:\> java NestTry One Two a = 2 Array index out of bounds. } The EmptyStackException class is defined in the java. the compiler refuses to compile your program and displays an error message similar to the following: testing. 187 . 8.util package.4 The throw Statement All Java methods use the throw statement to throw an exception.} } } System. Here's an example of a throw statement: throw someThrowableObject.Throwable.java:10: Cannot throw class java. throw new Integer(4). In the Java system. obj = objectAt(size .1. setObjectAt(size .lang. throwable objects are instances of any subclass of the Throwable class. The throw statement requires a single argument: a throwable object.1). it must be a subclass of class java.Integer. Sample outputs: 1) C:\> java NestTry Divide by zero. size--. If you attempt to throw an object that is not throwable. public Object pop() throws EmptyStackException { Object obj.lang.println(“Divide by zero”). null).out.

println("procA's finally").println("Recaught " ).out.println("procB's finally"). } } 188 . } catch(NullPointerException e) { System.println("inside procB"). } catch(NullPointerException e) { System.out. } finally { System. Recaught One more example using finally. static void procB() { try { System. class FinallyDemo { // Through an exception out of the method. } } // Return from within a try block.out.out. static void procA() { try { System. return. // re-throw the exception } } public static void main(String args[]) { try { demoproc()."). } } } The resulting output is Caught inside demoproc.out.println("inside procA"). throw new RuntimeException("demo").// Demonstrate throw. class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo").out.println("Caught inside demoproc. } finally { System. throw e.

. static void procC() { try { System.println("inside procC"). procC(). Java requires that a method either catch or specify all checked exceptions that can be thrown within the scope of the method. A method can catch an exception by providing an exception handler i.out. } finally { System.out. using a try. } } The resulting Output is: inside procA procA's finally Exception caught inside procB procB's finally inside procC procC's finally 8. } procB().5 The throws Clause The declaration of the pop method contains this clause: throws EmptyStackException The throws clause specifies that the method can throw an EmptyStackException.// Execute a try block normally. } catch (Exception e) { System.println("procC's finally"). } } public static void main(String args[]) { try { procA().catch block for that type of exception.e.println("Exception caught"). 189 .out.

} catch (IllegalAccessException e) { System. Here's an example: public void writeList() throws IOException.println("Inside throwOne. for (int i = 0. ArrayIndexOutOfBoundsException { Remember that ArrayIndexOutofBoundsException is a runtime exception. This is only true for overriding methods not overloading methods.txt").println("Value at: " + i + " = " + victor. so you don't have to specify it in the throws clause. Specifying the Exceptions Thrown by a Method public void writeList() { PrintWriter out = new PrintWriter(new FileWriter("OutFile. the method must specify that it can throw that exception. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.If a method chooses not to catch an exception. Thus if a method has exactly the same name and arguments it can only throw exceptions declared in the parent class. although you can.out.elementAt(i)). i++) out.6 Overriding methods that throw exceptions An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class. } public static void main(String args[]) { try { throwOne(). The throws clause specifies that if an exception occurs it is not explicitly handled. true).out. throw new IllegalAccessException("demo"). i < size."). } The throws clause is composed of the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The throws clause goes after the method name and argument list and before the curly bracket that defines the scope of the method.println("Caught “). or exceptions that are children of exceptions in the 190 . Caught 8. } } } The resulting Output is Inside throwOne.

java.*. RuntimeException subclasses (unchecked):              ArithmeticException ArrayIndexOutOfBoundsException ArrayStoreException ClassCastException IllegalArgumentException IllegalMonitorStateException IllegalStateException IllegalThreadStateException IndexOutOfBoundsException NegativeArraySizeException NullPointerException NumberFormatException SecurityException 191 . there are no similar rules to overloaded methods. They need not be included in any method’s throws list.parent declaration.7 Java’s built in exceptions Inside the standard package java. Also an overridden method in a sub class may throw Exceptions.io. Since. 8. remember that this only applies to overridden methods. It can however throw fewer or no exceptions. Checked exceptions are those defined by java. Again.lang is implicitly imported to all Java programs. Thus the following example will not compile import java. exception not in base version of method public static void amethod()throws IOException{} } If it were the method in the parent class that was throwing IOException and the method in the child class that was throwing FileNotFoundException this code would compile.lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. The most general of these are subclasses of RuntimeException. or throws these exceptions.lang. They are called unchecked exceptions because the compiler does not check to see if a method handles. most exceptions derived from RuntimeException are automatically available. Java defines several exception classes. class Base{ public static void amethod()throws FileNotFoundException{} } public class ExcepDemo extends Base{ //Will not compile.

IncompatibleClassChangeException 192 . the accesses o.length and a[0] in the following class declaration throws a NullPointerException at runtime.length(). For example. class Null { public static void main(String args[]) { String o = null. o. a[0] = 0. j = j / j. int a[] = null.  StringIndexOutOfBoundsException UnsupportedOperationException Checked Exceptions defined in java. the following code causes an ArithmeticException to be thrown: class Arith { public static void main(String args[]) { int j = 0. } } It is interesting to note that if you throw a null object you actually throw a NullPointerException. For example. } } NullPointerException An attempt to access a variable or method in a null object or a element in a null array throws a NullPointerException.lang        ClassNotFoundException CloneNotSupportedException IllegalAccessException InstantiationException InterruptedException NoSuchfieldException NoSuchMethodException ArithmeticException Attempting to divide an integer by zero or take a modulus by zero throw the ArithmeticException--no other arithmetic operation in Java throws an exception.

Four specific changes that throw a IncompatibleClassChangeException at runtime are: • • • • A variable's declaration is changed from static to non-static in one class but other classes that access the changed variable aren't recompiled. The following class declaration results in a ClassCastException at runtime: class ClassCast { public static void main(String args[]) { Object o = new Object().length(). The OutOfMemoryException can only occur during the creation of an object. A method that is declared in one class is deleted but other classes that access the method aren't recompiled. A field that is declared in one class is deleted but other classes that access the field aren't recompiled. i.e. String s = (String)o. For example. For example. a[0] = 0. when new is called. } } NegativeArraySizeException A NegativeArraySizeException is thrown if an array is created with a negative size.. A variable's declaration is changed from non-static to static in one class but other classes that access the changed variable aren't recompiled. ClassCastException A ClassCastException is thrown if an attempt is made to cast an object O into a class C and O is neither C nor a subclass of C.In general the IncompatibleClassChangeException is thrown whenever one class's definition changes but other classes that reference the first class aren't recompiled. } } OutOfMemoryException An OutOfMemoryException is thrown when the system can no longer suppy the application with memory. 193 . the following code results in an OutOfMemoryException at runtime: class Link { int a[] = new int[1000000]. // the cast attempt s. the following class definition throws a NegativeArraySizeException at runtime: class NegArray { public static void main(String args[]) { int a[] = new int[-1].

Link l. class NoClass is declared: class NoClass { public static void main(String args[]) { C c = new C(). } } } NoClassDefFoundException A NoClassDefFoundException is thrown if a class is referenced but the runtime system cannot find the referenced class. } class OutOfMem { public static void main(String args[]) { Link root = new Link(). if the runtime system can't find C.l = new Link().class it throws the NoClassDefFoundException. Link cur = root.l. cur = cur. interface I { } class IncompType { public static void main(String args[]) { I r = (I)new("I"). } } ArrayIndexOutOfBoundsException 194 . IncompatibleTypeException An IncompatibleTypeException is thrown if an attempt is made to instantiate an interface. while(true) { cur. For example. } } When NoClass is run. C class must have existed at the time NoClass is compiled. For example. the following code causes an IncompatibleTypeException to be thrown.

} catch (IOException e) { throw new SampleException("Other IOException". 195 . Two methods and two constructors were added to Throwable. class NoLink { static native void foo(). For example: in an array throws an class ArrayOut { public static void main(String args[]) { int a[] = new int[0]. Since every Throwable can have a cause. the class from which all exceptions inherit. } } 8. and initCause returns the current exception. The chained exception API was introduced in 1.. public static void main(String args[]) { foo().8 Chained Exceptions Chained exceptions allow you to rethrow an exception. getCause returns the exception that caused the current exception. each exception can have a cause. } } UnsatisfiedLinkException An UnsatisfiedLinkException is thrown if a method is declared native and the method cannot be linked to a routine in the runtime. providing additional information without losing the original cause of the exception.. which itself can have a cause. Throwable) Throwable(Throwable) The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception.4 by adding a cause property of type Throwable to exceptions. The following example shows how to use a chained exception: try { . and so on. a[0] = 0. The methods and constructors in Throwable that support chained exceptions are: Throwable getCause() Throwable initCause(Throwable) Throwable(String.An attempt to access an invalid element ArrayIndexOutOfBoundsException. e).

The intent is that this object will be interpreted as the thing that caused this throwable to get thrown in the first place.out. The other way to associate a cause with a Throwable is to invoke the initCause method on an existing Throwable object's reference.println("Print StackTrace"). passing a reference to another Throwable object as a parameter.println("Cause is:\n" + e. System.//blank line System. All that you are required to do is pass a Throwable object's reference to the constructor for a new Throwable object. System. whether or not it had anything to do with the true cause. you can associate a cause with a Throwable in two different ways. when an IOException is caught. System. a new SampleException exception is created with the original cause attached and the chain of exceptions is thrown up to the next higher level exception handler. It then becomes a cause.out.out. or invoke the initCause method on an existing Throwable object. of course.println("Msg is:\n" + e. } catch(NewEx01 e){ System.*.} In this example. e. This works even when you are instantiating a new object from a class that doesn't have a constructor that accepts a parameter of type Throwable.out. import java.getMessage()). However. class Excep20{ public static void main(String[] args){ try{ new Class01(). Two ways to encapsulate a cause As suggested above. This assumes. that the class from which you are instantiating the new object has such a constructor.println("In main catch block"). One way is to invoke one of the constructors that accepts a Throwable as a parameter. you could encapsulate any Throwable object in a new Throwable object.io.println().out.meth01().printStackTrace(). passing a reference to another Throwable object as a parameter. }//end catch }//end main }//end Excep20 //This is a new exception class class NewEx01 extends Exception{ public NewEx01() { 196 .getCause()). What is a cause? A cause is a reference to another Throwable object.

} public NewEx02(String message. 197 . }//end catch }//end meth01 void meth02() throws NewEx02{ try{ meth03(). } }//end NewEx02 class Class01{ void meth01() throws NewEx01{ try{ meth02(). System.} public NewEx01(String message){ super(message).getMessage()). throwable).println(). } }//end NewEx01 //This is a new exception class class NewEx02 extends Exception{ public NewEx02() { } public NewEx02(String message){ super(message). } public NewEx02(Throwable throwable){ super(throwable).println("In meth01 catch block").println("Msg is:\n" + e.//blank line throw new NewEx01("Msg from meth01". } public NewEx01(Throwable throwable){ super(throwable). } public NewEx01(String message. } catch(NewEx02 e){ System. System.out.Throwable throwable){ super(message.getCause()). System. throwable).out.e).out.Throwable throwable){ super(message.println("Cause is:\n" + e.out.

println("Cause is:\n" + e. will your users have access to those exceptions? A similar question is: Should your package be independent and self-contained? Example public class DivideByZeroException extends Exception { 198 . Use one written by someone else.println("In meth02 catch block"). System. 2. The Java development environment provides a lot of exception classes that you could use.9 Creating Your Own Exception Classes Choosing the Exception Type to Throw When faced with choosing the type of exception to throw. throw new NewEx02("Msg from meth02".out. throw ex.getMessage()). you can probably get away with using someone else's: • • • Do you need an exception type that isn't represented by those in the Java development environment? Would it help your users if they could differentiate your exceptions from those thrown by classes written by other vendors? Does your code throw more than one related exception? If you use someone else's exceptions.getCause()). Write one of your own. System.} catch(RuntimeException e){ System. You should go to the trouble of writing your own exception classes if you answer "yes" to any of the following questions.println("Msg is:\n" + e. }//end catch }//end meth03 }//end Class01 8.initCause(e).out.out.println().e). System. } catch(ArithmeticException e){ IndexOutOfBoundsException ex = new IndexOutOfBoundsException("Msg from metho03").out. }//end catch }//end meth02 void meth03(){ try{ int x = 3/0. ex. Otherwise. you have two choices: 1.

} } catch(ArrayIndexOutOfBoundsException e) { System. Most of the applets and applications that you write will throw objects that are Exceptions.out.lang package provides two Throwable subclasses that further divide the type of problems that can occur within a Java program: Errors and Exceptions.println(e). the java. (Errors are reserved for serious hard errors that occur deep in the system. Similarly.) Runtime exceptions don't have to be specified in the throws clause of a method. The bottom line is that you shouldn't subclass RuntimeException unless your class really is a runtime exception! Naming Conventions It's good practice to append the word "Exception" to the end of all classes that inherit (directly or indirectly) from the Exception class. } } public class DivisionExample { public static void main(String args[]) { try { int x = Integer. classes that inherit from the Error class should end with the string "Error". } public DivideByZeroException(String message) { super(message). } else { System.println(e).out. 199 . } catch(DivideByZeroException e) { System.public DivideByZeroException() { super("Dividing by Zero!").parseInt(args[0]).println(x/y).out. if(y == 0) { throw new DivideByZeroException().parseInt(args[1]). } } } Choosing a Superclass However. int y = Integer.

4 that simulates the functionality of assertions but it would be hard to do so in such a way that they would be turned off at runtime. By default.4 version of assertions. Assertions can be considered an extension of comments in that comments are often used to tell a person reading the code that a particular statement or piece of code should always be true. However because programmers in the past have used the word assert in creating their own versions of assertions the compilation process requires a command line parameter to tell it that it will be using the genuine JDK 1.4 Myprog.4 and require no additional import statements in the source code. Assertions are a key part of JDK 1.10 Assertions Assertions were added to Java with the release of JDK1. When a programmer is investigating an issue assertions can be enabled and if any of the assert statements are not true an assert exception will be thrown. When a program is running normally assertions are disabled and cause no performance overhead. instead of indicating by a comment that a statement should always be true you can assert that it should always be true. How assertions are used? Where and how you use assertions is a matter of judgment in a similar way to where and how you use comments.java If you then run the program normally in the form java Myprog 200 .8. and if they are not an assert error will be thrown. This takes the form javac -source1. With assertions. Why Assertions exist? Assertions are a fairly simple concept where you write a statement that should always be true. Assertions are a feature of other Object Orientated languages and there has been pressure for a while for them to be added to Java. assert statements are disabled during normal program run. If you then run the code with assertions enables you do not have to rely on a close reading of the code as you would with comments but the running of the code itself will check your assertions are true. but in a form that can be removed from the finally compiled version of the code so they cause no runtime overhead. As the name implies assertions are used to assert something that should always be true. It would be perfectly possible to write code using the constructs available in Java prior to JDK1.4.

java -enableassertions Myprog or java –ea Myprog What should you assert to be true? Assertions should be used for anything you believe should always be true. Because your public methods may be used in programs written by other people you cannot be certain that they will have assertions enabled and thus the normal running of the program may be faulty. Imagine if you had an application dealing with media types.assertions are disabled and no assert exceptions will be thrown. It is not appropriate to use assertions to check the parameters passed to public methods. The same assumption may be made for code in protected or in package protected methods. mpg. Where should you use assertions? Assertions should not be used to enforce the public interface of a program. avi or gif files. One of the most public interfaces of a program is its command line parameters. Because you believe that the type will always be one of those file types there is definitely a problem if you get to the end of the case statement without branching and you can place an assert statement at the location of the default option. really are true you can run the program with assertions enabled as follows. However it is appropriate to use assertions for checking the parameters to private methods as these will generally only be called by code written by people who have access to the source of those methods. For example if you are falling through a case statement or a set of if/else statements you might believe that the code should always exit before it reaches the final test. It is not appropriate to use assert to check the command line parameters of a program because assertions will not always be enabled. Your application might be expecting to deal with jpg. Thus traditionally a programmer will inspect the command line passed to a Java program by looking at the value in the String args array passed from the command line. If you subsequently have an issue you want to investigate and confirm that all of the assertions of items that should always be true. Typically if this array does not contain the expected type of values the program will exit and print a message indicating what the correct format of the command line should be. You set up a case statement that branch according to the type of file. Assert syntax 201 . therefore you could assert that the date of death is in the future. For another example if you were recording the date of a persons death you program (or your morality) might have a problem if you had the date of death in the future. If a person has an age less than zero your program or its input has a significant problem. For example it should always be true that a person has an age greater than zero. The introduction of the assert mechanism does not change this.

e.The assert statement has two formats The simple assert somebooleatest and assert somebooleantest : someinformatinvemethod In the first simpler version the assert tests that something is true and if it is not an AssertionError is thrown.out. This example is simple in that the right hand side of the expression is a simple string.m1( -1 ): " ).out. } public static void main( String[] args ) { Foo foo = new Foo().print( "foo.m1( 1 ): " ). foo. a method with any return type except void.out. System. public class Foo { public void m1( int value ) { assert 0 <= value. } } If the assertions are disabled the output is foo.m1( -1) : OK If the assertions are enabled the output is 202 .println( "OK" ). The more complex version might be of the form assert (iAge > 0) :"age must be greater than zero". System. System.m1( -1 ). For example if you were testing that a persons age was greater than zero you might create an assert in the form assert (iAge > 0).m1(1) : OK foo. foo. but this could be any method call that returns a value. i.print( "foo.m1( 1 ).

lang.f.c.g.m1(1) : OK foo. None of the above 3.out. x = 1. There are two types of exception types: checked and runtime exceptions. class A {A() throws Exception {}} // 1 class B extends A {B() throws Exception {}} // 2 class C extends A {} // 3 Which of the following statements is true? a. d.out.x. Prints: true. Questions 1. a = b = c = d = f = g = 0. None of the above public static void main (String[] args) { Error error = new Error().b. class A { c.m1( -1) (Runtime Exception – AssertionError) Summary An exception is an abnormal condition arised during the program execution that disrupts the normal flow of program and terminates the application. You can also define your own exception class.false b. There are built-in api exception classes in java. Compile-time error at 2. System.true c."). Compile-time error f. } } What is the result of attempting to compile and run the program? a. Prints: false.true e. Prints: false. All exception classes are subclasses of Throwable class. Exception exception = new Exception().print(error instanceof Throwable). System. Run-time error g.print((exception instanceof Throwable) + ". Prints: true. class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Purple { public static void main(String args[]) { int a.false d. Compile-time error at 3.foo. try { 203 . 2. b.d. Compile-time error at 1.

out.0. Prints: 0.0.} switch (x) { case 1: throw new Level1Exception().print("1"). } a++. switch (j) { case 0: System.} } Which statements are true? a.} finally {c++.1.1.0.1.1.out.print("0"). System.} finally {g++. c. With assertions enabled it prints 210210 followed by an AssertionError message. d. b. 204 . Run-time error h.1.0. Prints: 0. default: assert j == 2.} catch (Exception e) {f++. With assertions enabled it prints only 210210.m1(i)."+c+". class A { d.1.1.1.1 c.0. } } public static void main (String[] args) { A a = new A(). e.1. for (int i=5. Prints: 1. case 2: throw new Level2Exception()."+g).0. case 3: throw new Level3Exception().out.0 b. None of the above } void m1(int i) { int j = i % 3. Prints: 0."+f+".1. Compile-time error g."+b+". g.print(j)."+d+".try { } catch (Level2Exception e) {b++.out. case 1: System.0. With assertions enabled it prints nothing. With assertions enabled it prints 210210-1 followed by an AssertionError message. Prints: 1. } } } catch (Level1Exception e) { d++. What is the result of attempting to compile and run the program? a.1. i >= -1. break.} System. With assertions disabled it prints 210210-1 With assertions disabled it prints only 210210 Assertions should not be used within the default case of a switch statement. break.0.1 e. f.0.1 4.print(a+".1 f. i--) {a.

205 .

The objective of multitasking is to utilize the idle time of the CPU. Process-based multitasking is running two programs concurrently. This is thread-based multitasking. where each process (program) is a context. you could say that process-based multitasking is program-based multitasking. Your engine keeps running regardless of whether the car is moving. You want your CPU cycles to be processing instructions and data rather than waiting for something to process. Programmers refer to a program as a process. For example. Thread-based multitasking is having a program perform two tasks at the same time. In processbased multitasking. Programmers call this context switching.1 Multitasking Multitasking is performing two or more tasks at the same time. Additional resources are needed for each process to communicate with each other. An idling engine wastes gas. Likewise. a word processing program can check the spelling of words in a document while you write the document. Therefore. Nearly all operating systems are capable of multitasking by using one of two multitasking techniques: process-based multitasking and thread-based multitasking. 9. The same concept applies to the CPU in your computer. the threads in thread-based multitasking share the same address space in memory because they share the same program. A good way to remember the difference between process-based multitasking and thread-based multitasking is to think of process-based as working with multiple programs and thread-based as working with parts of one program. Think of the CPU as the engine of your car.2 What Is a Thread? 206 . communication among parts of the program happens within the same memory location. each process requires its own address space in memory. This also has an impact on context switching. A CPU cycle is somewhat similar to your engine running. Your objective is to keep your car moving as much as possible so you can get the most miles from a gallon of gas.Chapter 9 : Multithreaded programming 9. Process-based multitasking has a larger overhead than thread-based multitasking. In comparison. The operating system requires a significant amount of CPU time to switch from one process to another process. because switching from one part of the program to another happens within the same address space in memory.

This is illustrated by the following figure: The Java run-time environment manages threads. and an end. a thread itself is not a program. However. or watch three sorting algorithms race to the finish. unlike in process-based multitasking where the operating system manages switching between programs. each has a beginning. play animation and sound concurrently. a thread is considered lightweight because it runs within the context of a full-blown program and takes advantage of the resources allocated for that program and the program's environment. multiple parts of a program running concurrently). This means that one thread can pause while other threads continue to process. That is. Rather. Each thread is a different path of execution. an execution sequence. a sequence.. You've probably written a program that displays "Hello World!". You are used to life operating in a concurrent fashion. 207 . A thread is part of a program that is running. At any given time during the runtime of the program. Definition: A thread is a single sequential flow of control within a program. Threads are processed asynchronously. it cannot run on its own. and an end and at any given time during the runtime of the thread. The HotJava Web browser is an example of a multithreaded application.All programmers are familiar with writing sequential programs. A thread is similar to a real process in that a thread and a running program are both a single sequential flow of control. This is a sequential program. there is a single point of execution. A single thread also has a beginning..so why not your browser? Some texts use the name lightweight process instead of thread. print a page in the background while you download a new page. However. it runs within a program. there is a single point of execution. Thread-based multitasking has multiple threads running at the same time (that is. Within the HotJava browser you can scroll a page while it's downloading an applet or image. The following figure shows this relationship.

Controlling groups of threads Sometimes it is necessary to control multiple threads at the same time. By passing an argument to the constructor that creates the Thread object. If a thread dies and there are no other threads except daemon threads alive. Basic support for threads in the Java platform is in the class java.As a sequential flow of control. • • Subclass the Thread class and override the run method. To implement a thread using the Thread class. the Thread inherits the daemon attribute of its parent Thread object. the Java virtual machine stops. A Thread object has a boolean attribute that specifies whether or not a thread is a daemon thread.lang. Provide a class that implements the Runnable interface and therefore implements the run method. it is set using the setDaemon() method. Every Thread object belongs to a ThreadGroup object. It provides a thread API and provides all the generic behavior for threads. Java provides the ThreadGroup class for this purpose. running. the ThreadGroup of a thread can be set when the Thread object is created. by passing an argument to the constructor that creates the Thread object. the thread that runs the garbage collector in Java is a daemon thread. you need to provide it with a run method that performs the thread's task. and threads that run system code are daemon threads. There are two ways to provide the run method. a Runnable object provides the run method to the thread. If an explicit ThreadGroup is not specified. some other texts use execution context as a synonym for thread. For most programming needs. and having a priority. (It must have its own execution stack and program counter for example. yielding. Daemon threads A daemon thread is a thread that runs continuously to perform a service. For example. In general. sleeping. a thread must carve out some of its own resources within a running program. The daemon attribute of a thread is set when the Thread object is created. the Thread belongs to the same ThreadGroup as its parent Thread object. (The actual implementation of concurrent operations is system-specific. The daemon attribute is queried using the isDaemon() method.Thread. 208 . If the daemon attribute is not explicitly specified. Thus.) The code running within the thread works only within that context. the underlying implementation doesn’t matter. The thread that processes mouse events for a Java program is also a daemon thread.) These behaviors include starting. threads that run application code are not daemon threads. without having any connection with the overall state of the program. In this case.

A new Thread class always starts running the public void run() method of a class.int n) The thread sleeps for m milliseconds. String There are many methods in the Thread class.3 The Thread class The class java. The thread will start executing in the run() method of the Runnable parameter when Thread. stop() This method stops and kills a running thread. ThreadGroup The new thread will belong to the group specified by the parameter ThreadGroup. 209 . sleep(int m)/sleep(int m. the new thread starts running in the run() method of an object. the thread begins executing in the run() method of the target class. This is a deprecated method. However. To create a thread.start() is called. resume() This method resumes the execution of a suspended thread. The constructors are the following: Thread() Thread(Runnable) Thread(ThreadGroup) Thread(String) Thread(ThreadGroup. A thread can get its name by calling Thread. All of them create a new thread.start() is called. • • • suspend() This method suspends the execution of the thread. When Thread. plus n nanoseconds. The Thread class has seven constructors. the thread does not start running right away.getName().lang. a new instance of this class must be created. Thread.start() must be called to actually make the thread run.String) Thread(Runnable.Runnable.9. Currently.Thread is used to create and control threads. If it is suspended.String) The constructors can use three possible parameters: • • • The name of the new thread is the parameter String. This method can be called only once. Some of the methods that control the thread execution are the following: • start() This method starts the thread. A ThreadGroup can be used to organize a thread.String) Thread(ThreadGroup. It remains suspended until resume() is called. The thread does not start running until Thread. It has no effect on • a thread that is not suspended. Runnable The Runnable parameter is an object that has implemented the Runnable interface. it does not die until it starts running again. When Thread. It starts executing in the run() method of its Runnable target that was set when the constructor was called.start() has been called.start() is called. the thread does not stop unless it is running.

out.println(n). This is usually called the main thread of your program. // change the name of the thread t. System.println(“Current thread :“+ t).setName(“My thread”).main] After name change : Thread[My Thread. try { for(int n = 5. Often it must be the last thread to finish execution because it performs various shutdown actions.out.main] 5 4 3 210 .4 Using the main thread When a Java program starts up. Although the main thread is created automatically when your program is started.9. } } } The output of the program is as follows : Current thread : Thread[main. Example. you can control it just like any other thread. System.println(“After name change :” +t). n > 0.currentThread(). because it is the one that is executed when your program begins. //controlling the main thread class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread. Thread. } } catch(InterruptedException e) { System.) { System. Once. you have a reference to the main thread.out.sleep(1000). 5. To do so you must obtain the reference to it by calling the method currentThread(). Its general form is shown below: static Thread currentThread() This method returns a reference to the thread in which it is called. it can be controlled through a Thread object. one thread begins running immediately. The main thread is important because :   It is the thread from which other “child” threads will be spawned. n -. which is a public static member of Thread.out.5.println(“Main thread interrupted”).

its priority and the name of its group. } } The first method in the SimpleThread class is a constructor that takes a String as its only argument. A thread group is a data structure that controls the state of a collection of threads as a whole. 211 . it displays the name of the thread.out. } catch (InterruptedException e) {} } System. int nanoseconds) throws InterruptedException You can set the name of the thread by using setName(). } public void run() { for (int i = 0.5 Creating a thread Subclassing Thread and Overriding run The first way to customize a thread is to subclass Thread (itself a Runnable object) and override its empty run method so that it does something. You can obtain the name of the thread by calling getName(). This process is managed by particular runtime environment. Its priority is 5. By default. i < 10. the name of the main thread is main. Its general form is static void sleep(long milliseconds) throws InterruptedException static void sleep(long milliseconds.out. i++) { System.println("DONE! " + getName()). The sleep method causes the thread from which it is called to suspend execution for the specific period of milliseconds. which is the default value. which is used later in the program. try { sleep((long)(Math. Let's look at the SimpleThread class. which does just that: public class SimpleThread extends Thread { public SimpleThread(String str) { super(str). the first of two classes in this example.2 1 When you try to print t.random() * 1000)).println(i + " " + getName()). The syntax is given below: final void setName(String threadName) final String getName() 9. This constructor is implemented by calling a superclass constructor and is interesting to us only because it sets the Thread's name. and main is also the name of the group of threads to which this thread belongs.

the run method prints DONE! along with the name of the thread. The run method of the SimpleThread class contains a for loop that iterates ten times. new SimpleThread("Fiji").start(). In each iteration the method displays the iteration number and the name of the Thread. Compile and run the program. and both threads are displaying their output at the same time. which in turn calls the run method. Implementing Runnable interface 212 . The reason is that both SimpleThread threads are running concurrently. } } The main method starts each thread immediately following its construction by calling the start method. That's it for the SimpleThread class. The TwoThreadsTest class provides a main method that creates two SimpleThread threads: Jamaica and Fiji.start(). You should see output similar to this: Note how the output from each thread is intermingled with the output from the other. Let’s put it to use in TwoThreadsTest. So both run methods are running. When the loop completes. After the loop has finished. the thread stops running and dies. then sleeps for a random interval of up to 1 second.The next method in the SimpleThread class is the run method. The run method is the heart of any Thread and where the action of the Thread takes place. public class TwoThreadsTest { public static void main (String[] args) { new SimpleThread("Jamaica").

start(). public ThreadedClass(){ data = 0. Single-threaded systems use an approach called an event loop.The Runnable interface is a built-in interface in java. t2. This one instance is used to spawn a multitude of threads (each executing the run() method of the same object). This helps reduce inefficiency by preventing the waste of CPU cycles.start(). Thread t2 = threadedClass. a signal that a network file is ready to be read. only one instance of ThreadedClass is created.getNewThread(). polling a single event queue to decide what to do next. a single thread of control runs in an infinite loop.lang package and has only one method in it – that is public void run() When you are implementing the Runnable interface you have to override the run method //Implementing Runnable public class ThreadedClass implements Runnable { int data. In this model. This wastes CPU time. nothing else can happen in the system. It can also result 213 . } } In the main() method of the code above. } public Thread getNewThread(){ Thread t = new Thread( this ). then the event loop dispatches the control to the appropriate event handler.getNewThread(). with polling.println( ++data ).out.6 The Java Thread Model Java uses threads to enable the entire environment to be asynchronous. } public void run(){ //this method runs when start() is invoked on the thread System. } public static void main( String[] args ){ ThreadedClass threadedClass = new ThreadedClass(). t1. return t. say. Thread t1 = threadedClass. 9. Once this polling mechanism returns with. Until this event handler returns.

• Ready State A thread in this state is ready for execution. This thread has access to CPU. • Blocked A resource cannot be accessed because it is being used by another thread. • Suspended Execution is paused and can be resumed where it left off. This thread cannot be executed now. A suspended thread is started. In single-threaded environment. it gets converted to running state. A simple diagram is shown below: A more detailed diagram follows: 214 . One thread can pause without stopping other parts of your program. but is not being currently executed. the entire program stops running. Once a thread in the ready state gets access to the CPU.in one program dominating the system and preventing any other events from being processed. The Life cycle of a thread The following figure shows the states that a thread can be in during its life and illustrates which method calls cause a transition to another state. when a thread blocks because it is waiting for some resource. • Terminated or Dead State A thread reaches "dead" state when the run method has finished execution. The thread on which yield() is invoked would move from running state to ready state. or by invoking an object’s wait() method. by blocking on I/O. • Resumed. A thread can enter the waiting state by invoking its sleep() method. by unsuccessfully attempting to acquire an object’s lock. The states of a Thread A thread can be in one of these states: • Running A thread is said to be in running state when it is being executed. It can also enter the waiting state by invoking its (deprecated) suspend() method. A CPU intensive operation being executed may not allow other threads to be executed for a "large" period of time. The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated. To prevent this it can allow other threads to execute by invoking the yield() method.

which is the Thread. Thread aThread = Thread. Nor could you differentiate between a Runnable thread and a Not Runnable thread. If the isAlive method returns false.State values is returned: • • • • • • NEW RUNNABLE BLOCKED WAITING TIMED_WAITING TERMINATED The API for the Thread class also includes a method called isAlive.0. you couldn't differentiate between a New Thread or a Dead thread. currentPriority = aThread. The isAlive method returns true if the thread has been started and not stopped. 215 .NORM_PRIORITY.getState method. one of the following Thread. Prior to release 5. int currentPriority. Constants Thread. If the isAlive method returns true.MAX_PRIORITY can also be used. 9. By default. you know that the thread either is a New Thread or is Dead. When called on a thread.MIN_PRIORITY and Thread.0 introduced the Thread. the setPriority() method sets the thread priority to 5.7 Thread priority A thread's priority is specified with an integer from 1 (the lowest) to 10 (the highest).currentThread().getPriority(). you know that the thread is either Runnable or Not Runnable.Testing Thread State Release 5.

hi. } } class HiLoPri { public static void main (String args [ ]) { Thread.start(). } } public void stop() { running = false.MAX_PRIORITY). Clicker hi = new Clicker (Thread. if you cannot resist messing with priorities. However.NORM_PRIORITY .println("Main Thread Interrupted"). } catch (InterruptedException e) { System. private volatile boolean running = true.join().join(). Use medium to low-priority for CPU-intensive threads to avoid hogging the processor down.stop().aThread. Setting priorities may not always have the desired effect because prioritization schemes may be implemented differently on different platforms.setPriority( currentPriority + 1 ).currentThread(). use higher priorities for threads that frequently block (sleeping or waiting for I/O).start().setPriority(Thread.sleep(10000). } public void start () { t. hi. } lo. lo. Thread t. } 216 .t.start(). try { Thread. public Clicker(int p) { t = new Thread(this). } public void run () { while (running) { click++.stop().out. try { hi. Clicker lo = new Clicker (Thread.NORM_PRIORITY + 2). class Clicker implements Runnable { int click = 0.2). t.t.setPriority(p). lo.

which causes the currently running thread to yield its hold on CPU cycles. } System. 90% of the CPU time.yield().println("Low-Priority Thread:" + lo. System. indicates that the threads did context switch even though neither voluntarily yielded the CPU nor blocked for I/O.out.catch (InterruptedException e) { System. On some operating systems the threading algorithm may automatically give different threads a share of the CPU time. Low-Priority Thread:4408112 High-Priority Thread:589626904 The output depends on the speed of your CPU and the number of other tasks running in the system.println(Thread.out. on others one thread might simply hog processor resources.getName() + " Leaving run"). Thread. } } The output of this program.println("High-Priority Thread:" + hi. If no other threads are in a "ready to run state" the thread that was executing may restart running again. System. The higher priority thread got approx. Example of using yield() method public class TestRunner implements Runnable { public void run() { System.out.println(Thread.println("InterruptedException Caught"). Because of the platform dependent nature of Java threading you cannot be certain if a thread will ever give up its use of CPU resources to other threads.getName() + " In run").out. For this reason the Java Thread class has a static method called yield.out.currentThread().8 Using the Thread yield method. } 9.currentThread(). shown as follows when run under Windows 2000.click). } } 217 . Volatile ensures that the value of running is examined each time the following loop iterates: while(running) { click++.click). This thread returns to the "ready to run" state and the thread scheduling system has a chance to give other threads the attention of the CPU.

start().start().public class TestYield { public static void main (String[] args) { TestRunner r1 = new TestRunner().9 Stopping a Thread and stop() methods of Thread provide asynchronous methods of stopping a thread. these methods have been deprecated because they are very unsafe. t1. If you don’t want to use the deprecated method you can set a variable that the thread checks occasionally. it should return from the run() method. Thread t1 = new Thread(r1). while (i < 100) { i++. 218 . if(!allDone) System. i<= 10. } } A thread with this run method dies naturally when the loop completes and the run method exits.println(i).out. class MyThread extends Thread { boolean allDone = false. Using them often results in deadlocks and incorrect resource cleanup. When the thread detects that the variable is set. t2. However. suspend() Instead of using stop. t1. Thread t2 = new Thread(r1). For example. // This method is called when the thread runs public void run() { try { for(int i=1.setName("TestThreadHaah"). else return.setName("BlahBlah"). System. the while loop in this run method is a finite loop: It will iterate 100 times and then exit: public void run() { int i = 0.out. t2.println("i = " + i). a thread should arrange for its own death by having a run method that terminates naturally. } } 9.i++) { sleep(500).

These techniques involve calling the isAlive() method and the join() method. a boolean false is returned. } catch(InterruptedException e) { System. You can use the isAlive() method to examine whether a child thread continues to run. Programmers use two other techniques to ensure that the main thread is the last thread to terminate. When threads operate on damaged objects. thus. } // Stop the thread thread. The isAlive() method determines whether a thread is still running. } } Why is stop deprecated? Because it is inherently unsafe.allDone = true. } class ThreadStopDemo { public static void main(String args[]) { // Create and start the thread MyThread thread = new MyThread(). Both of these methods are defined in the Thread class.out. the main thread is the last thread to finish in a program.out. However. there isn’t any guarantee that the main thread won’t finish before a child thread finishes. 9. arbitrary behavior can result. Such objects are said to be damaged. the user has no warning that his program may be corrupted.sleep(2000). The join() method waits until the child thread terminates and “joins” 219 .10 Determining When a Thread Has Finished Typically. the isAlive() method returns a boolean true value. If it is.start(). ThreadDeath kills threads silently. The join() method works differently than the isAlive() method. thread. The corruption can manifest itself at any time after the actual damage occurs.println(e). Unlike other unchecked exceptions. Stopping a thread causes it to unlock all the monitors that it has locked.} } } } catch(InterruptedException e) { System. other threads may now view these objects in an inconsistent state. or it may be pronounced. even hours or days in the future. (The monitors are unlocked as the ThreadDeath exception propagates up the stack. try { Thread.println(e).) If any of the objects previously protected by these monitors were in an inconsistent state. otherwise. This behavior may be subtle and difficult to detect.

thread. If two threads of the same priority are 220 .join(). threads run one at a time in such a way as to provide an illusion of concurrency. } else { System.isAlive()) { System. } else { System.start(). // Check if the thread has finished in a non-blocking way if (thread.the main thread.println(“Finished”).out. Thread scheduling is implementation dependent and cannot be relied on to act the same way on every JVM When a thread is created. it inherits its priority from the thread that created it. } catch (InterruptedException e) { System. yields.isAlive()) { System. class ThreadDemo { public static void main(String args[]) { // Create and start a thread MyThread thread = new MyThread(). Hence. At any given time. In addition.println(“Finished”). Only when that thread stops. Execution of multiple threads on a single CPU in some order is called scheduling. This algorithm schedules threads on the basis of their priority relative to other Runnable threads.11 Thread Scheduling Many computer configurations have a single CPU. deterministic scheduling algorithm called fixed-priority scheduling.println(“Thread was interrupted”). you can use the join() method to specify the amount of time you want to wait for a child thread to terminate. when multiple threads are ready to be executed. } // Wait for the thread to finish try { thread. } if (thread.out.out. or becomes Not Runnable will a lower-priority thread start executing.out.out.println(“Thread has not finished”). } } } 9.println(“Thread has not finished”). the runtime system chooses for execution the Runnable thread that has the highest priority. The Java runtime environment supports a very simple.

the highest priority thread is running. Rule of thumb: At any given time. You cannot be certain which thread gets woken. Although Java defines priorities for threads from the lowest at 1 to the highest at 10. For this reason. the scheduler arbitrarily chooses one of them to run. In a time sliced system each thread gets a "slice" of the CPU time and then gets moved to the ready state. Non time slicing/Cooperative A priority system is used to decide which thread will run. the runtime system chooses the new higher-priority thread for execution. The Java runtime system's thread scheduling algorithm is also preemptive. it is removed from accessing the CPU and any other waiting Threads get a chance at CPU time. In a pre-emptive system one program can "pre-empt" another to get its share of CPU time. Time slicing/preemptive Each thread gets a set amount of CPU time for executing. Do not rely on it for algorithm correctness. A thread with the highest priority gets time with the CPU. The chosen thread runs until one of the following conditions is true: • • • A higher priority thread becomes runnable. If you have multiple waiting threads then it will be probably the thread that has been waiting the longest that will wake up. When each thread has had its chance with the CPU the cycle starts again. The thread scheduler may choose to run a lower priority thread to avoid starvation. On systems that support time-slicing. The downside is that you cannot be certain how long a Thread might execute or even when it will be running. This ensures against a single thread getting all of the CPU time. However. The notify method will wake up one thread waiting to reacquire the monitor for the object. use thread priority only to affect scheduling policy for efficiency purposes. However you cannot be certain. A program under this system needs to be created in such a way that it "voluntarily" yield access to the CPU. It yields. until the interpreter exits. Then the second thread is given a chance to run. and so on. Of course this is not always possible and you may have to try to test your code on as many platforms as possible. If at any time a thread with a higher priority than all other Runnable threads becomes Runnable. If you have only one waiting thread then you do not have a problem. some platforms will accurately recognise these priorities whereas others will not.waiting for the CPU. As a result you are generally advised to use notifyAll instead of notify. The beauty of this approach is that you can be confident that each thread will get at least some time executing. 221 . this is not guaranteed. or its run method exits. Once it has used up its time with the CPU. and the priorities of the threads will influence the result. and not to make assumptions about scheduling or priorities. The new thread is said to preempt the other threads. its time allotment has expired.

One specific type of semaphore is called a mutual exclusion semaphore or a mutex. In the early 1970s. Any other thread that tries to acquire ownership will be blocked and must wait until the owning thread releases the mutex. concurrently running threads share data and must consider the state and activities of other threads. ownership of this semaphore object is mutually exclusive. (The guarded code need not be contiguous -for example. The yield method gives other threads of the same priority a chance to run. In one such set of programming situations. imagine an application in which one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. the threads in those examples ran at their own pace without concern for the state or activities of any other concurrently running threads. the producer thread places mouse events in an event queue and the consumer thread reads the events from the same queue. there must be a mechanism by which multiple threads running the same method can synchronize their operations. Because only one thread can own a mutex at a given time. in that only one thread can own the mutex at any given time. as you type characters on the keyboard.A. Hoare and others developed a concept known as a monitor. A thread can voluntarily yield the CPU by calling the yield method. the others will continue to block. only one of them will get it when it is released by the current owner. Also. Any thread wishing to execute this code must acquire the associated mutex at the top of the code block and release it at the bottom.) In many interesting situations. try to write well-behaved threads that voluntarily relinquish the CPU periodically and give other threads an opportunity to run. separate. As the name indicates. this effectively ensures that only the owing thread can execute a monitor block of code. If no equal-priority threads are Runnable. the producer generates a stream of data that a consumer uses. For example.12 Thread Synchronization So far the examples in this chapter have contained independent. writing CPU-intensive code can have negative repercussions on other threads running in the same process. C. A monitor is a body of code whose access is guarded by a mutex. Both of these examples use concurrent threads that 222 . every object in the Java language has a single monitor associated with it. Each thread contained all the data and methods required for its execution and didn’t require any outside resources or methods. such that only one of them is allowed to proceed when accessing the same object or lines of code.Relinquishing the CPU As you can imagine. If multiple threads are waiting in line for the same mutex. the yield is ignored.R. called producer-consumer scenarios. Or. A method in a Java object is said to be thread safe if it can be safely run in a multithreaded environment. asynchronous threads. In general. To achieve this safety. This synchronization requires the threads to communicate with each other using objects called semaphores. 9.

} System.print(“[“ + msg).out. try { Thread. or mutex (mutually exclusive lock) used. Entry to the code is protected by a monitor lock around it. Callme target.share a common resource: The first shares a file. Note that the lock is based on the object and not on the method. } catch(InterruptedException e) { System. they must be synchronized. its object is locked and it cannot be called by any other code until the lock is freed.out. Any other thread will not be able to execute the code until the first thread has finished and released the lock.sleep(1000). The synchronized keyword The synchronized keyword can be used to mark a statement or block of code so that only one thread may execute an instance of the code at a time. For a method the synchronized keyword is placed before the method thus synchronized void amethod() { /* method body */} For a block of code the synchronized keyword comes before opening and closing brackets thus.out. A lock is assigned to the object and ensures only one thread at a time can access the code.println(“]”). It is generally more common to synchronize the whole method rather than a block of code. } } class Caller implements Runnable { String msg. Thus when a thread starts to execute a synchronized block it grabs the lock on it. You may also see the words monitor. When a synchronized block is executed.println(“Interrupted”). Because the threads share a common resource. This process is implemented by a system of locks. Thread t. 223 . Example //This program is not synchronized class Callme { void call(String msg) { System. and the second shares an event queue. synchronized (Object Reference) { /* Block body */ } The value in parentheses indicates the object or class whose monitor the code needs to obtain.

“Hello”). The output of the program is [Hello] [Synchronized] If the Callme class is a third party class then you cannot change its code.t. } } class Synch { public static void main(String args[]) { Callme target = new Callme().start().public Caller(Callme targ. “Synchronized”). Caller obj1 = new Caller(target. } } } Output is : [Hello[Synchronized ] ] Same example using synchronization: In the code above just add the keyword synchronized in front of the call method in the Callme class. obj2.println(“Interrupted”). try { obj1. t =new Thread(this). } catch(InterruptedException e) { System. } public void run() { target.out. msg = s.call(msg). t.t. String s) { target = targ.join(). Caller obj2 = new Caller(target.join(). In that case you can use the synchronized block in the run method as follows: public void run() { 224 . synchronized void call(String msg) This prevents other thread from entering call() while another thread is using it.

} public void run() { for (int i = 0.put(number.} synchronized(target) { target. stores it in a CubbyHole object. public class Consumer extends Thread { 225 .number = number. the Producer sleeps for a random amount of time between 0 and 100 milliseconds before repeating the numbergenerating cycle: public class CubbyHole { private int contents. public Producer(CubbyHole c.call(msg). } } public class Producer extends Thread { private CubbyHole cubbyhole. } catch (InterruptedException e) { } } } } The Consumer consumes all integers from the CubbyHole (the exact same object into which the Producer put the integers in the first place) as quickly as they become available. To make the synchronization problem more interesting. this. The Producer/Consumer Example In this example. the Producer generates an integer between 0 and 9 (inclusive). } Only the run method is changed. The rest of the code is same. try { sleep((int)(Math. i < 10. private int number. i++) { cubbyhole.random() * 100)). } public void put(int value) { contents = value. public int get() { return contents. i). int number) { cubbyhole = c.

However. and the final result depends on the timing of how the threads are scheduled. assume for a moment that these two threads make no arrangements for synchronization. In this situation. } } } Producer and Consumer example share data through a common CubbyHole object. One problem arises when the Producer is quicker than the Consumer and generates two numbers before the Consumer has a chance to consume the first one. and let’s discuss the potential problems that might arise from this. i < 10. } public void run() { int value = 0. within the get and put methods of the CubbyHole object.number = number. Race conditions can lead to unpredictable results and subtle program bugs. In this situation. this. the Consumer misses a number. A problem such as this is called a race condition. public Consumer(CubbyHole c.get(number). i++) { value = cubbyhole. neither Producer nor Consumer makes any effort whatsoever to ensure that happens. Part of the output might look like this: Another problem might arise when the Consumer is quicker than the Producer and consumes the same value twice. The synchronization between these two threads occurs at a lower level.private CubbyHole cubbyhole. the result is wrong because the Consumer should get each integer produced by the Producer exactly once. Race conditions in the producer-consumer example are prevented by having the storage of a new integer into the CubbyHole by the 226 . the Consumer might produce output that looks like this: Either way. int number) { cubbyhole = c. A race condition is a situation in which two or more threads or processes are reading or writing some shared data. for (int i = 0. private int number. Although Consumer ideally will get each value produced once and only once.

the two threads must do some simple coordination. A thread can prevent this from happening by locking an object. The Producer locks the CubbyHole. the code segments that access the same object from separate. In the producer-consumer example. and the Producer should not modify it when the Consumer is getting the value. } public synchronized void put(int who. the thread that called the method locks the object whose method has been called.. and notifyAll — to help threads wait for a condition and notify other threads when that condition changes. public synchronized int get(int who) { . The Object class provides a collection of methods — wait. A critical section can be a block or a method and is identified with the synchronized keyword. and the Consumer must have a way to indicate that the value has been retrieved. The Consumer should not access the CubbyHole when the Producer is changing it. First. Here’s a code skeleton for the CubbyHole class: public class CubbyHole { private int contents. the Producer must have a way to indicate to the Consumer that the value is ready.. When an object is locked by one thread and another thread tries to call a synchronized method on the same object. So put and get in the CubbyHole class should be marked with the synchronized keyword. Locking an Object Within a program. private boolean available = false. Second. thereby preventing the Consumer from calling the CubbyHole's get method: 227 . concurrent threads are called critical sections. notify. the put and get methods of CubbyHole. That is. Thus. } } The method declarations for both put and get contain the synchronized keyword.. the two threads must not simultaneously access the CubbyHole. Other threads cannot call a synchronized method on the same object until the object is unlocked. The Java platform associates a lock with every object and the lock is acquired upon entering a critical section. The activities of the Producer and the Consumer must be synchronized in two ways.Producer be synchronized with the retrieval of an integer from the CubbyHole by the Consumer. int value) { .java are the critical sections. when it calls CubbyHole's put method. Whenever control enters a synchronized method. the second thread will block until the object is unlocked..

public synchronized void put(int value) { //CubbyHole locked by the Producer . When control enters method a. the thread attempts to acquire the same lock again. This ensures that race conditions cannot occur in the underlying implementation of the threads. it locks the CubbyHole.println("here I am. The current thread can acquire Reentrant 228 .out. the Producer unlocks the CubbyHole.println("here I am. The two threads must also be able to notify one another when they've done their job.. The Java runtime environment allows a thread to reacquire a lock because the locks are reentrant. thereby reacquiring the lock. Synchronization isn't the whole story. Reaquiring a Lock The same thread can call a synchronized method on an object for which it already holds the lock. b. } public synchronized void b() { System. thereby preventing the Producer from calling put: public synchronized int get() { // CubbyHole locked by the Consumer . the current thread acquires the lock for the Reentrant object. calls the other. because b is also synchronized. when the Consumer calls CubbyHole's get method. in a()").. // CubbyHole unlocked by the Consumer } The acquisition and release of a lock is done automatically and atomically by the Java run-time system. System. Reentrant locks are important because they eliminate the possibility of a single thread’s waiting for a lock that it already holds.. in b()"). Now.. //CubbyHole unlocked by the Producer } When the put method returns. In platforms that don’t support reentrant locks. Because the Java platform supports reentrant locks. thus ensuring data integrity. Similarly. Consider this class: public class Reentrant { public synchronized void a() { b(). this sequence of method calls causes deadlock. The first. this works. } } contains two synchronized methods: a and b.out. a calls b. a.

available. these two methods won't work. contents = value. in b() here I am. CubbyHole has another private member variable. } } As implemented. and both a and b execute to conclusion. as is evidenced by the output: here I am. wait and notify should be placed within synchronized code to ensure that the current code owns the monitor Using the notifyAll and wait Methods in the Producer/ Consumer Example Let's investigate how the code in CubbyHole's put and get methods helps the Producer and the Consumer coordinate their activities. The available variable is true when the value has been put but not yet gotten and is false when the value has been gotten but not yet put. Here's one possible implementation for the put and get methods: public synchronized int get() { if (available == true) { available = false. in a() 9. The CubbyHole stores its value in a private member variable called contents. put doesn't do anything. Look at the get method. It therefore waits for the condition to be met.13 Interthread Communication The construct of wait/notify plays an important role in the Java language's interthread communication mechanism. the causing thread notifies the waiting thread to wake up and proceed from where it left off. What happens if the Producer hasn't put anything in the CubbyHole and available isn't true? The get method does nothing. } } //won't work! public synchronized void put(int value) { //won't work! if (available == false) { available = true. that is a boolean.the Reentrant object's lock again. if the Producer calls put before the Consumer got the value. 229 . Similarly. return contents. Once the condition is true. The essential idea is that one thread needs a certain condition that can be brought about by another thread to become true.

public synchronized int get() { while (available == false) { try { //wait for Producer to put value wait().You really want the Consumer to wait until the Producer puts something in the CubbyHole and the Producer to notify the Consumer when it's done so. Here are the new get and put implementations that wait on and notify each other of their activities: class CubbyHole { boolean available. it notifies Consumer by calling notifyAll. int contents. Similarly. When Producer puts something in the CubbyHole. } public synchronized void put(int value) { while (available == true) { try { //wait for Consumer to get value wait(). The two threads must coordinate more fully and can use Object's wait and notifyAll methods to do so. } } The code in the get method loops until the Producer has produced a new value. available = true. //notify Producer that value has been retrieved notifyAll(). get calls the wait method. Each time through the loop. The wait method relinquishes the lock held by the Consumer on the CubbyHole (thereby allowing the Producer to get the lock and update the CubbyHole) and then waits for notification from the Producer. //notify Consumer that value has been set notifyAll(). return contents. The Consumer then comes out of the wait state and the get method returns the value in the CubbyHole. the Producer should wait until the Consumer takes a value (and notifies the Producer of its activities) before replacing it with a new value. } catch (InterruptedException e) { } } contents = value. 230 . } catch (InterruptedException e) { } } available = false.

which arbitrarily wakes up one of the threads waiting on this object. The awakened threads compete for the lock. and a Consumer and then starts both the Producer and the Consumer: public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole().The put method works in a similar fashion. There are the three versions of the wait method contained in the Object class: wait() Waits indefinitely for notification wait(long timeout) Waits for notification or until the timeout period has elapsed. the CubbyHole). and the others go back to waiting. One thread gets it. you also can use them in place of sleep. but it could be important for threads that sleep for minutes at a time. c1. Both wait and sleep delay for the requested amount of time.start(). wait(long timeout. Running the Producer-Consumer Example Here’s a small standalone application. It waits for the Consumer thread to consume the current value before allowing the Producer to produce a new one. called ProducerConsumerTest. p1. 1). This doesn't matter too much for threads that don't sleep for long. that creates a CubbyHole object. a Producer. Producer p1 = new Producer(c. The Object class also defines the notify method. 1).start(). Consumer c1 = new Consumer(c. You can easily wake up wait with a notify but a sleeping thread cannot be awakened prematurely. The notifyAll method wakes up all threads waiting on the object in question (in this case. Note: Besides using these timed wait methods to synchronize threads. } } Here’s the output of ProducerConsumerTest: Producer Consumer Producer Consumer #1 #1 #1 #1 put: got: put: got: 0 0 1 1 231 . timeout is measured in milliseconds. int nanos) Waits for notification or until timeout milliseconds plus nanos nanoseconds have elapsed.

then its thread can be suspended. with both of them swaying from side to side and no progress being made. Once suspended. a separate thread can be used to display the time of the day. suspending a thread is a simple matter. A simple example is where each thread already holds one object and needs another that is held by the other thread. occurs when two or more threads are waiting on a condition that cannot be satisfied. This continues for some time. but both keep moving to the same side at the same time. but no work gets done. If the user doesn’t want a clock. the ultimate form of starvation. A system is fair when each thread gets enough access to limited resources to make reasonable progress.Producer Consumer Producer Consumer Producer Consumer Producer Consumer Producer Consumer Producer Consumer Producer Consumer Producer Consumer #1 #1 #1 #1 #1 #1 #1 #1 #1 #1 #1 #1 #1 #1 #1 #1 put: got: put: got: put: got: put: got: put: got: put: got: put: got: put: got: 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 9. Resuming & Stopping Threads Sometimes suspending execution of a thread is useful. (A common real world example is when two people approach each other in a narrow corridor. these two threads can run forever in lock-step. cannot make progress. effectively managing to achieve nothing at all. as a result. Each person tries to be polite by moving to one side to let the other one pass. Clearly.14 Starvation and Deadlock If you write a program in which several concurrent threads are competing for resources. A fair system prevents starvation and deadlock. Livelocks A livelock. unlike a deadlock. happens when threads are actually running. This usually happens when the two threads are working at cross-purposes. restarting the thread is also a simpler matter. Now imagine a situation wherein each thread puts down the object it possesses and picks up the object put down by the other thread. Deadlock most often occurs when two (or more) threads are each waiting for the other(s) to do something. thereby ensuring that neither can pass.) 9. Starvation occurs when one or more threads in your program are blocked from gaining access to a resource and. For example.15 Suspending. Deadlock. Whatever the case. so what is done by the first thread is undone by another. you must take precautions to ensure fairness. 232 .

Thread. } System.out. t1.println(“New Thread :” + t).out. t = new Thread(this.i--) { System.println(e).t.An example using the deprecated methods: //using suspend() and resume() class NewThread implements Runnable { String name.println(“Resuming thread one”). name).println(“Suspending thread one”).sleep(1000).println(“Main thread interrupted”).resume(). } } class SuspendResume { public static void main(String args[]){ NewThread t1 = new NewThread(“One”). System.join().out.t. Thread.out. NewThread(String threadName) { name = threadName.t.suspend(). t2. t. try { Thread. } } catch(InterruptedException e) { System. } System. // start the thread } // this is the entry point for Thread public void run() { try { for(int i=15.start(). NewThread t2 = new NewThread(“Two”).out.t. t1.sleep(200). System. } catch(InterruptedException e) { System.println(“Main thread exiting”).println(name + “exiting”). } } 233 . System. i > 0.out.println(name + “:” + i). t1.sleep(1000).join(). //name of thread Thread t.out.out.

class NewThread implements Runnable { String name. // start the thread } // this is the entry point for Thread public void run() { try { for(int i=15. boolean suspendFlag. While one thread is suspended the other runs. NewThread(String threadName) { name = threadName. synchronized(this) { while(suspendFlag) { wait().println(e). name). t.println(name + “:” + i).This program creates two threads and suspends one of them. i > 0. t = new Thread(this. notify(). System.out.out.start(). The same example code is written below without using deprecated methods.i--) { System. } System. } } In the main method of the previous code instead of calling suspend() call mysuspend() method and instead of resume() call myresume() 234 .sleep(200). } void mysuspend() { suspendFlag = true.println(name + “exiting”). suspendFlag = false. } synchronized void myresume() { suspendFlag = false. Thread. //name of thread Thread t.println(“New Thread :” + t).out.out. } } } } catch(InterruptedException e) { System.

} gA.gB). Example of ThreadGroup: class NewThread extends Thread { NewThread(String threadName.println(getName() + “: exiting”). System. i > 0. start().out.println(e).gA).out. i--) { System.16 ThreadGroup ThreadGroup creates a group of threads.out.threadName). Thread.suspend(). NewThread t4 = new NewThread(“Four”.println(e). This is valuable in situations in which you want to suspend and resume a number of related threads. try { Thread.println(getName() + “:”+ i). It defines two constructors: ThreadGroup(String groupName).9.sleep(1000). } } catch(Exception e) { System. NewThread t2 = new NewThread(“Two”. NewThread t3 = new NewThread(“Three”.out. 235 . String groupName) ThreadGroup offers a convenient way to manage groups of threads as a unit. ThreadGroup tg) { super(tg. ThreadGroup gB = new ThreadGroup(“Group B”).sleep(5000).println(“New Thread :”+ this).gB). } System. //start the thread } //This is the entry point for the thread public void run() { try { for(int i=15. NewThread t1 = new NewThread(“One”. } catch(Exception e) { System.out.gA). } } class ThreadGroupDemo { public static void main(String args[]) { ThreadGroup gA = new ThreadGroup(“Group A”). ThreadGroup(ThreadGroup parent.

join().println(e). try { t1. t4.sleep(5000). } gA.println(e).out.join().join().try { Thread. t2.resume(). Thread-based multitasking also called as multithreading is cheaper compared to process based multitasking. 236 . Multitasking can be achieved by process based multitasking and thread based multitasking. } } } Summary A thread is a logical execution unit that has a single sequential flow. In multithreaded application you can execute multiple threads within a single program. t3.out. } catch(Exception e) { System.join(). } catch(Exception e){ System.

you use Strings when you don't want the value of the string to change. if you pass a string data into a method. Once they are initialized and populated the value and memory allocation is set (they are immutable. System.out.println("And might I add that you look lovely today.").) If the String is changed in any way a new String object is created in memory for the new value. meaning they can not be changed.Chapter 10 : String Handling The Java development environment provides two classes that store and manipulate character data: String.lang package and they implement the CharSequence interface. so you could use a literal string in place of a String there. For example. and second when it encounters new String(). you can use a literal string to initialize a String. you specify literal strings between double quotes "Hello World!" You can use literal strings anywhere you would use a String object. Because they are constants. Both String and StringBuffer are the classes in java. but more efficient than. The above construct is equivalent to. 10. Strings are typically cheaper than StringBuffers and they can be shared. Creating a string 237 . because the compiler ends up creating two Strings instead of one: first when the compiler encounters "Hola Mundo!". you use StringBuffers when you know that the value of the character data will change. The StringBuffer class provides for non-constant strings. In the Java language. Because the compiler automatically creates a new String object for every literal string it encounters. you would use a String. System.out. and StringBuffer. The String class provides for constant strings. and you don't want the method to modify the string in any way (which is typical). for mutable strings.1 The String class Strings in Java are constants. String s = "Hola Mundo". this one String s = new String("Hola Mundo"). For example. So it's important to use Strings when they're appropriate.println() accepts a String argument. for immutable strings.

Strings are created like any other object in Java using the new operator. } } This program prints ABCDEF CDE There are two more constructors of String class String(StringBuffer) String(StringBuilder) The first one creates a string whose value is set from a string buffer. String s2 = new String(ascii. Comparing Strings The equals method Comparing two Strings references to see if they hold identical strings is easily achieved with the equals method.out. 70}.println (str).out.'A'}. System. System.'A'. This method is called on one string object and takes another as an input 238 . For example one of the String constructors allows an array of characters to be taken as input: char letters[] = {'J'. 66. 68.println(s2). String s1 = new String(ascii). While creating a String object you can also specify the byte values.'V'. String str = new String (letters). 67. // will print JAVA One more constructor of String is String (String obj) String s = new String(“Java”). The second creates a string whose value is set from a string builder. 2. int numChars) Class StringExample { public static void main(String args[]) { byte ascii [] = {65.println(s1). int startIndex. 3). 69. String (byte asciiChars[]) String (byte asciiChars[]. // One constructor accepts an array of chars System.out.

// false 239 .out. both containing the same string. // false If you try to compare two strings like this: if (str == str2) System. So if you want to compare the contents of the string use equal. if it is equal to 0 they are equal and if the result is greater than 0 then the first is greater than the second. String str3 = "goodbye". Two references which point to the same object will always return true with the equals method.parameter. This short example shows how comparisons are made amongst string: class strCmp { public static void main (String args[]) { String str = "Hello". It is possible that two strings are equal without them being the same object.out. else System. // true System.println (str. you are actually checking to see whether the two references str and str2 refer to the same object.out. String str2 = "Java".equals(str2)). System.println ("false"). The equalsIgnoreCase method This method is similar to the equals method instead it performs the case insensitive comparison of Strings. For example: String str = "hello". if they are equal it returns the boolean value true.equals(str2)). boolean equalsIgnoreCase (String str) The compareTo method int compareTo(String str) This method is called in the same way as the equals method but returns an integer result. but two references which refer to different objects. If the result is less than 0 then the first string is less than the second. with be false with the == operator. otherwise it returns false.println ("true").out. String str2 = "hello". System.out.println ("str and str2" + str. if you want to check if the two references refer to the same object use ==.println ("str and str3" + str.equals(str2)).

out. The following program.out.e. String. len)) { i++.println (str. int) This method tests whether the specified region of this string matches the specified region of the String argument.substring(i. For each character. the program calls the regionMatches method to determine whether the substring beginning with the current character matches the string for which the program is looking. String. The charAt method 240 . int len = findMe. } } } The output from this program is Eggs. while (!searchMe. RegionMatchesDemo. int. boolean foundIt = false. 0.compareTo(str2)). findMe. if true. foundIt = true. int) boolean regionMatches(boolean. // a negative number. The boolean argument indicates whether case should be ignored.System. uses the regionMatches method to search for a string within another string: public class RegionMatchesDemo { public static void main(String[] args) { String searchMe = "Green Eggs and Ham". String findMe = "Eggs". the case is ignored when comparing characters. int.regionMatches(i. i+len)). int i = 0.length(). The program steps through the string referred to by searchMe one character at a time. i. str is less than str2 } } The compareToIgnoreCase method This method is similar to the compare method the only difference is it performs the case insensitive comparison.println(searchMe. int. int compareToIgnoreCase(String str) The regionMatches method boolean regionMatches(int. } if (foundIt) { System.

once they have been declared the objects can not be altered.println (str.charAt(0)). However. System. char ch = “abc”. 241 . Hence.e.charAt(1). they are called immutable objects.println (str.char charAt (int where) This method is called on a string object with an integer value as a parameter.length()). i. String str2 = "Java". it returns a char which is at the location of the parameter passed in the string. // 5 + 4 = 9 } } Altering Strings Strings in Java are actually rather like constants. What they actually do is return a new String. assigns ‘b’ to ch The length method public int length().out.out. //demonstrate toUpperCase and toLowerCase class ChangeCase { public static void main(String args[]) { String s = “ This is a test”. there are several methods which appear to need to alter the contents of the string. The toUpperCase and ToLowerCase method String toLowerCase() String toUpperCase() These two methods are called on a string object and simply convert all letters in the string to the appropriate case. This method is called on a string object with no parameters and returns an integer number which is the number of characters in the string class strExample { public static void main (String args[]) { String str = "Hello". // H. char is position 0 System.length() + str2.

The second version allows the start of the substring being created to be specified as well as the end. 242 . String upper = s.println(“Uppercase:”+ upper). LowerCase : this is a test. The substring method String substring (int startIndex) String substring (int startIndex. The concat method String concat(String str) This method is called on one string object with another as its parameter. String lower = s. } } The output produced by the program is shown here: Original : This is a test. trim().out.concat(“Two”). The first type leaves the new string with all letters from the old ranging from the first to the number specified. Puts “Hello World” into s. the first accepts an int and the second two. The trim method String trim() A very simple method called on a string object this simply removes all whitespace from the string String s = “ Hello World ”.println(“Lowercase:”+ lower).out.toUpperCase(). String s2 = s1. int endIndex) This versatile method is overloaded to have two versions.println(“Original :” + s). UpperCase : THIS IS A TEST. puts “OneTwo” into s2. The two are concatenated together with the object on which the method was called holding the new string.toLowerCase(). System. System.out. String s1 = “One”.System.

System.PI)). For example. The string is searched for the first char parameter.The replace method String replace (char original.println (str). int startIndex. str2 = str2. // str now equals "HELLO java" System. An example of methods which alter Strings class altStr { public static void main (String args[]) { String str = "Hello". to print the value of pi System.’w’). when it is found it is replaced with the second.toLowerCase(). // HELLO System. puts the string”Hewwo” into s The valueOf method static static static static static String String String String String valueOf valueOf valueOf valueOf valueOf (double num) (long num) (Object obj) (char char[]) (char char[].out.println (str2).out.concat(str2). // str now equals "HELLOjava" 243 . Instead it is a static method which is overloaded to accept all simple Java types and returns a string. String str2 = "Java".println(String.out. str = str.replace(‘l’. char replacement) This method is called on a string object with two char parameters. int numChars) This method is slightly different to the one mentioned above because it is not called on a string object.valueOf(Math.toUpperCase(). As a convenience. str = str.trim(). String s = “Hello”.println (str). the String class provides the static method valueOf() which you can use to convert variables of different types to Strings.out.// java str = str.

System. find.println (str).141).str.println (str).valueOf (3.out.length()).lastIndexOf(find)). 4)).indexOf ('s')).println // find the string (str.println (str. String find = "will". no offset (str. int startIndex) lastIndexOf(String s.out. find in str. int startIndex) lastIndexOf(int ch) lastIndexOf(String s) lastIndexOf(String s. System. int startIndex) indexOf(String s. no offset 244 . int startIndex) These two overloaded methods allow a character or substring to be searched for. System. // str = "java" System. // str = "jivi" System. str = str. 'i'). // find char.out. The example below shows possible versions of the two methods. // str = "3.println (str. class indexTest { public static void main (String args[]) { String str = "This string will be searched". // find s.141" } } Searching String The indexOf and lastIndexOf methods int int int int int int int int indexOf (int ch) indexOf (String s) indexOf(int ch.out. str = String.out. offset by 9 System.out.println (str).replace ('a'. These methods allow for the string to be searched either from the beginning (IndexOf) or from the end (lastIndexOf).lastIndexOf ('s'. str = str.println (str). The input parameters for these methods is a char or string which is to be found and an optional offset from the beginning (or end) of the string. no offset System.indexOf (find)).out.println // find the string System. given as an int.out.substring (5.

Then substring() uses the return value of lastIndexOf() to extract the filename extension--that is.lastIndexOf(pathseparator). sep).'). The following class illustrates the use of lastIndexOf() and substring() to isolate different parts of a filename. the String class supports four different versions of both the indexOf() and lastIndexOf() methods which  returns the index of the first (last) occurrence of the specified character 245 . This code assumes that the filename actually has a period ('. int sep = fullpath. } } The extension() method uses lastIndexOf() to locate the last occurrence of the period ('.substring(dot + 1). then dot + 1 is equal to the length of the string which is one larger than the largest index into the string (because indices start at 0).lastIndexOf(pathseparator). char pathseparator. then lastIndexOf() returns -1. pathseparator = sep. } String extension() { int dot = fullpath. class Filename { String fullpath.lastIndexOf('. notice that extension() uses dot + 1 as the argument to substring(). dot). char sep) { fullpath = str.') in the filename. } String filename() { int dot = fullpath.substring(0.} } The indexOf() and lastIndexOf() methods are frequently used in conjunction with substring() which returns a substring of the string.').substring(sep + 1.'). Filename(String str. and the substring() method throws a "string index out of range exception". the substring from the period ('.') character is the last character of the string. if the filename does not have a period ('.lastIndexOf('. substring() accepts an index equal to (but not greater than) the length of the string and interpret it to mean "the end of the string". } String path() { int sep = fullpath.') to the end of the string. return fullpath.') in it. While the methods in the example above uses only one version of the lastIndexOf() method. If the period ('. return fullpath. However. Also. return fullpath.

3) returns true The split method J2SE 1.endsWith(“bar”). returns the index of the first (last) occurrence of the specified String. both return true “Foobar”. This method uses the concept of a regular expression to specify the delimiters. The toCharArray() method If you want to convert the characters in a string to char type and store it in the character array use this method char [] toCharArray() The startsWith and endsWith methods The startsWith method determines whether a given String begins with a specified string. “Foobar”.startsWith(“Foo”).4 added the split() method to the String class to simplify the task of breaking a string into substrings. The endsWith determines whether the String ends up with a specified String. or tokens. searching forward (backward) from the specified index returns the index of the first (last) occurrence of the specified String. “Foobar”. int startIndex) boolean endsWith(String str) For example. boolean startsWith(String str) boolean startsWith(String str.   returns the index of the first (last) occurrence of the specified character. A regular expression is a remnant from the Unix grep tool ("grep" meaning "general regular expression parser"). 246 .startsWith(“bar”. searching forward (backward) from the specified index The getBytes method byte [] getBytes() This method converts the String to the byte array where each character in the string is converted to its ascii equivalent and stored in the array.

The + operator There is another special piece of string syntax using the + operator. However. i < words.out.println(CustName + " ordered a " + CustOrder + ". i++) System. String CustOrder = "Java Programming Course". String s = "Hello". //To use "*" as a delimiter.In its simplest form. StringTokenizer is still useful for some tasks. Example of String concatenation with other data types int age = 9. The split() method takes a parameter giving the regular expression to use as a delimiter and returns a String array containing the tokens so delimited.").println(s).println(s). String s = “He is ” + age + “ years old”. // t = "Hello there. String t = s + "there" + ".out.split() method is much easier and more natural to use than the StringTokenizer class. System. For example.println (words[i]). an overloaded StringTokenizer constructor allows you to specify that the tokens to be returned include the delimiter characters themselves. searching for a regular expression consisting of a single character finds a match of that character. Here int is converted to String String s = “four :” + 2 + 2.split (" "). how are you" + "today". how are you today" The following code will append several values together and output a line of text to the system console.out.out. the character 'x' is a match for the regular expression "x". System. String[] starwords = str. the String. the first example above becomes String str = "This is a string object". at the moment it is convenient to know how to use this.split ("*"). This allows strings to be added together. String[] words = str. System. This code displays 247 . String CustName = "John Smith". Using split(). For most string splitting tasks.length. for (int i=0. For example. simply specify "*" as the regular //expression: String str = "A*bunch*of*stars".

The plus operator which looks like it allows normal Strings to be extended actually uses the StringBuffer class and converts back to a string. which is not possible with a normal String. This is useful for a number of operation. A new object is created every time more text is appended. Constructors of StringBuffer class Constructor StringBuffer() Description Constructs a string buffer with no characters in it and an 248 .com”). 10. This is the niche filled by the StringBuffer class. For example : The following code creates String objects and uses the concatenation (+) character to add more characters to them: String sample1 = new String(“Builder.”. sample1 += “to be. The effects may be minimal in this instance (given the small amount of code). In the end.four : 22 rather than four : 4 This is because the String concatenation operator has the higher precedence than the arithmetic + operator. but a larger application with more operations will likely degrade performance.2 The StringBuffer Class The StringBuffer class is the second of Java's classes which deal with string handling. The reason Java has too separate classes to deal with strings is simply for performance reasons.com. the system creates four String objects to handle the alterations. such as adding characters into to the end of a string. Hence to get the desired result use String s = “four :” + (2 + 2). The first is created with the text Builder. sample1 += “the place “. While the original String class dealt with strings which were of a fixed length (the length of the number of characters the string contained) and whose contents could not be altered the StringBuffer class deals with strings which are not full of characters and whose contents can be changed. sample1 += “ is “. The problem with this approach is that too many resources are being used for such a simple procedure.

If the default constructor is called with no parameters this capacity is set to 16. Constructs a string buffer with no characters in it and an initial capacity specified by the length argument. The memory allocated to the object is automatically expanded to accommodate additional text. The StringBuffer class is designed to create and manipulate dynamic string information. in this case the capacity of the StringBuffer will be the number of characters in the initial string plus a further 16. the initial contents of the string buffer is a copy of the argument string. When a StringBuffer object is created it has a capacity.lang package. StringBuffer sb = new StringBuffer(“Builder. // capacity = 16 StringBuffer strbuf2 = new StringBuffer (25). otherwise an int may be passed as a parameter to specify the capacity. Methods concerned with capacity 249 . Creating StringBuffer objects To create a StringBuffer object use the following: StringBuffer rb = new StringBuffer(). StringBuffer strbuf = new StringBuffer (). The following example shows the possible ways of building StringBuffer objects. The second instance of the class has no value and a capacity of 30 characters. Constructs a string buffer so that it represents the same sequence of characters as the string argument.StringBuffer(int capacity) StringBuffer(String str) initial capacity of 16 characters. Another constructor allows an initial set of characters to be passed as a parameter.com”). // capacity = 25 StringBuffer strbuf3 = new StringBuffer ("Java"). and the final line creates an object with the initial value. in other words. // capacity = 4 + 16 = 20 The length method int length() Returns the length (character count) of this string buffer. StringBuffer sb = new StringBuffer(30). The first line creates an object with no text and the default capacity of 16 characters. so no special imports statement is needed to take advantage of it. The StringBuffer class is included in the base java. which is the number of characters that the StringBuffer will contain if full. StringBuffer sb = new StringBuffer().

out. The setLength method void setLength(int length) This method allows the length of a StringBuffer object to be set. To reset a StringBuffer (to use it somewhere else) set the length to zero using the setLength() method.setLength(0). This will "clear" out the value in the StringBuffer. System.out.println (strbuf. // prints 21 The capacity() method differs from length() in that it returns the amount of space currently allocated for the StringBuffer. called on the StringBuffer object with the new size (int) as the only parameter. unless the buffer is full. the actual capacity may be more than you have specified.println (strbuf). rather than the amount of space used.println (strbuf). if the value passed (int) is greater than the existing length then the remainder will be filled with zeros.append ("_world"). rb. // prints 5 System. Note that this method ensures a minimum capacity. The following example shows this: StringBuffer strbuf = new StringBuffer ("Hello").out. // Hello strbuf. An example of StringBuffer capacity class altBuf { public static void main (String args[]) { StringBuffer strbuf = new StringBuffer ("Hello").out. // Hello_World 250 .println (strbuf. System. The ensureCapacity method void ensureCapacity(int capacity) Once a StringBuffer object has been created the size of the buffer can be resized using the ensureCapacity method. System.capacity()). Note that the capacity will be different to the length.length()).The capacity method int capacity() This method is called on a StringBuffer object and returns the capacity as an int.

out. 251 . char charValue) The charAt method works the same as for a String object.println(“charAt(1) before = ” + sb. System. //demonstrate charAt and setCharAt class CharAtDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer(“Hello”).charAt(1)).println (strbuf).println(“Buffer after : ” +sb).strbuf. sb.println (strbuf). System. } } Here is the output generated by this program: Buffer before = Hello charAt(1) before = e buffer after = Hi charAt(1) after = i The insert method StringBuffer insert(int index.setCharAt(1. char charValue) Inserts the string representation of the char argument into this string buffer. char[] charArray) Inserts the string representation of the char array argument into this string buffer.insert (6.println(“charAt(1) after = ” + sb.setCharAt (5. ' ').println(“Buffer before = ” + sb).out.out. System.out. StringBuffer insert(int index. StringBuffer insert(int index. System.out. System. an int to specify the position in the StringBuffer and a char which the character at the given position will be changed to.’i').setLength(2). boolean booleanValue) Inserts the string representation of the boolean argument into this string buffer. The setCharAt method takes two parameters as input.charAt(1)). sb. System. // Hello World strbuf. // Hello Java World } } The charAt and setCharAt methods char charAt(int index) void setCharAt(int index. "Java ").out.

StringBuffer sb = new StringBuffer("Drink Java!"). float floatValue) Inserts the string representation of the float argument into this string buffer. or a String). An example of altering the contents of StringBuffer objects class AltBuf { 252 . the first (int) is the position where the data is to be added. you specify the index before which you want the data inserted. "Hot "). To add data at the end of a StringBuffer use an index equal to the current length of the StringBuffer or use append(). so the index for 'J' is 6.out. char[] charArray. long longValue) Inserts the string representation of the long argument into this string buffer. In the example. This example illustrates how you would insert a string into a StringBuffer. StringBuffer insert(int index.println(sb.StringBuffer insert(int index. To insert data at the beginning of a StringBuffer use an index of 0. The insert method is identical to the append method except that the data is added to the string at a specified position. StringBuffer insert(int index. int startIndex. Again this method is called on a StringBuffer object but it takes two parameters. sb. Indices begin at 0.toString()). This code snippet prints Drink Hot Java! With StringBuffer's many insert(). Object obj) Inserts the string representation of the Object argument into this string buffer. int intValue) Inserts the string representation of the second int argument into this string buffer. "Hot " needed to be inserted before the 'J' in "Java". and the second is the data to be added (of any simple type. StringBuffer insert(int index. String str) Inserts the string into this string buffer. StringBuffer insert(int index.insert(6. double doubleValue) Inserts the string representation of the double argument into this string buffer. System. StringBuffer insert(int index. int numChars) Inserts the string representation of a subarray of the str array argument into this string buffer. StringBuffer insert(int index.

int startIndex. System. " ").out. StringBuffer append(float floatValue) Appends the string representation of the float argument to this string buffer.out. StringBuffer append(char charValue) Appends the string representation of the char argument to this string buffer. System. System. System. StringBuffer append(char[] charArray) Appends the string representation of the char array argument to this string buffer.insert (7. // Hello World strbuf. StringBuffer append(char[] charArray.public static void main { StringBuffer strbuf = new ("Hello").println (strbuf). // Hello strbuf. 253 .println (strbuf). StringBuffer append(int intValue) Appends the string representation of the int argument to this string buffer.println (strbuf). // Hello_World strbuf. int numChars) Appends the string representation of a subarray of the char array argument to this string buffer. // Hello Java World } } The toString method String toString() Converts to a string representing the data in this string buffer. To output the StringBuffer value use the toString() method The append method StringBuffer append(boolean booleanValue) Appends the string representation of the boolean argument to the string buffer.out.append ("_world").out. "Java ").println (strbuf). StringBuffer append(double doubleValue) Appends the string representation of the double argument to this string buffer.setCharAt (6.

append("World"). StringBuffer b = new StringBuffer(). sb. The append method can be used to append values together.out.println(b.append(". sb.com and sends it to the standard output. sb. StringBuffer append(String str) Appends the string to this string buffer. sb.append("B").toString()). rb. System. This is achieved by the method being overloaded for all of the simple data types and using the valueOf method.append("r").append("Hello"). The StringBuffer variable. but only one object is created. sb. rb. This code creates the string Builder.println(sb. StringBuffer rb = new StringBuffer(). System. This method allows data of any of the simple data types to be added to the end of a StringBuffer. The append method is called on a StringBuffer object with the data to be added as an input parameter. The append method can accept any data type as input and converts the data to a String to be appended to the end of the value in the StringBuffer. sb. One more example 254 .append("u"). StringBuffer append(Object obj) Appends the string representation of the Object argument to this string buffer. Notice that the code takes advantage of the toString method of the StringBuffer class. now holds the value of "Hello World!". The same code using String objects would require more than eight objects.append(" ").append("d").append("Hello”).append("l"). This method converts the contents to a String object that can be used for output.com").append("e").append("i"). This allows text to be manipulated accordingly and used for output or data storage.out. sb.toString()).append("World!").StringBuffer append(long longValue) Appends the string representation of the long argument to this string buffer. StringBuffer sb = new StringBuffer(). sb.

System.out. String str) Replaces the characters in a substring of this StringBuffer with characters in the specified String. The deleteCharAt method StringBuffer deleteCharAt(int index) Removes the character at the specified position in this StringBuffer (shortening the StringBuffer by one character). System.delete(4.println(“After deleteCharAt : ” + sb). The length property is reset so that the text is truncated.append("Builder. System.sb.7).println(sb. sb.toString()).com The delete method StringBuffer delete(int start. int end. sb.out.println(“After delete :” + sb).out. The output follows: Builder.setLength(11). } } The following output is produced : After replace : This was a test The replace method public StringBuffer replace(int start. 255 . The reverse method StringBuffer reverse() The character sequence contained in this string buffer is replaced by the reverse of the sequence.com is awesome! Builder.deleteCharAt(0). //demonstrate delete and deleteCharAt class deleteDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer(“This is a test”).println(sb. System. int end) Removes the characters in a substring of this StringBuffer.com is awesome!"). sb.toString()). This code sets the capacity and populates the object with a string.out.

reverse(). 256 . } } The reverseIt() method accepts an argument of type String called source which contains the string data to be reversed. dest.redliuB The reverse method is present only in the StringBuffer class. the same size as source. int dstBegin) Characters are copied from this string buffer into the destination character array dst. return dest.com!"). sb.ensureCapacity(100). The getChars method public void getChars(int srcBegin. Example class ReverseString { public static String reverseIt(String source) { StringBuffer dest = new StringBuffer(source).reverse(). Hence if you want to reverse a String you can use the StringBuffer for doing so.The following code and output show it in action: StringBuffer sb = new StringBuffer(). Output: Builder.append("Builder. char dst[]. sb.com! !moc. dest. to a String. sb. Finally.println(sb. a StringBuffer. System. int srcEnd.toString()). the method converts dest.toString()). then loops backwards over all the characters in source and appends them to dest thereby reversing the string. System.println(sb.The substring begins at the specified index and extends to the end of the StringBuffer.out.toString(). The method creates a StringBuffer.out. The substring method String substring(int startIndex) Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.

int len = palindrome.0 added the StringBuilder class. int endIndex) Returns a new String that contains a subsequence of characters currently contained in this StringBuffer. i--) { dest.1). } System.String substring(int startIndex. // 1 b = "\r".length(). In fact. // 3 \u000a = new line d = "\u000d". so it really is a drop-in replacement. } } The output from this program is: doT saw I was toD Questions 1.println ("The result is " + result). class MCZ17 { public static String String String String } } void main (String[] args) { a = "\n". Because StringBuilder is not synchronized. you should use StringBuilder in preference over StringBuffer.println(dest. // 2 c = "\u000a". 10.0 javac compiler normally uses StringBuilder instead of StringBuffer whenever you perform string concatenation as in System. which reverses the characters of a string. public class StringsDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod".out. i >= 0. Following is a sample program called StringsDemo. it offers faster performance than StringBuffer.append(palindrome.charAt(i)). All the methods available on StringBuffer are also available on StringBuilder. StringBuilder dest = new StringBuilder(len). which is a drop-in replacement for StringBuffer in cases where thread safety is not an issue. for (int i = (len .toString()).3 The StringBuilder class J2SE5. // 4 \u000d = return 257 .out. In general. This program uses both a string and a string builder. the J2SE 5.

String d = '\uabcd'. 1 2. 3 d. String a = 'a'. class MCZ20 { b. c. } Which of the following lines can be inserted at the specified location without generating a compile-time error? a.Compile-time errors are generated at which lines? a. None of the above 258 . 2 c. d. b. 4 } public static void main (String[] args) { // Insert code here. String b = 'abc'. e. String c = '\u0041'.

memory. a program needs to import the java. a program opens a stream on an information source (a file.1 I/O Streams To bring in information. To use these classes. The stream classes are divided into two class hierarchies.io package contains a collection of stream classes that support these algorithms for reading and writing. a socket) and reads the information sequentially. as shown here Similarly. based on the data type (either characters or bytes) on which they operate. a program can send information to an external destination by opening a stream to a destination and writing the information out sequentially. like this: Reading open a stream while more information read information close the stream Writing open a stream while more information write information close the stream The java. I/O Stream Classes 259 .io package.Chapter 11 : I/O 11.

io package. parallelograms are abstract classes.This diagram shows most of the members of the java. Rectangles are classes. and ovals are interfaces Byte Streams 260 .

marking locations in the stream. 261 . For example. An input stream is automatically opened when you create it. int offset. The OutputStream class is an abstract base class that provides a minimal programming interface and a partial implementation of output streams in Java. programs should use the byte streams. The InputStream class is an abstract base class that provides a minimal programming interface and a partial implementation of input streams in Java. both Reader and InputStream provide methods for marking a location in the stream. Two of the byte stream classes. are used for object serialization. and resetting the current position within the stream. descendants of InputStream and OutputStream. Subclasses of Reader and Writer implement specialized streams and are divided into two categories: those that read from or write to data sinks Understanding the I/O Superclasses and InputStream define similar APIs but for different data types. int length) Also. skipping input. or let it be closed implicitly when the object is garbage collected. Reader provides the API and partial implementation for readers--streams that read 16-bit characters--and Writer provides the API and partial implementation for writers--streams that write 16-bit characters. or let it be closed implicitly when the object is garbage collected. finding out the number of bytes that are available for reading. int offset. skipping bytes of input. ObjectInputStream and ObjectOutputStream. An output stream is automatically opened when you create it. and resetting the current position. The InputStream class defines a methods for reading bytes or arrays of bytes. You can explicitly close a stream with the close() method. These streams are typically used to read and write binary data such as images and sounds.To read and write 8-bit bytes. Reader contains these methods for reading characters and arrays of characters: Reader int read() int read(char cbuf[]) int read(char cbuf[]. OutputStream defines methods for writing bytes or arrays of bytes to the stream and flushing the stream.io. Character Streams Reader and Writer are the abstract superclasses for character streams in java. You can explicitly close an output stream with the close() method. InputStream and OutputStream provide the API and partial implementation for input streams (streams that read 8-bit bytes) and output streams (streams that write 8-bit bytes). int length) InputStream defines the same methods but for reading bytes and arrays of bytes: int read() int read(byte cbuf[]) int read(byte cbuf[].

Type of I/O Byte Streams Character Streams ByteArrayInputStream CharArrayReader Memory ByteArrayOutputStream CharArrayWriter StringReader StringWriter PipedReader PipedWriter FileReader FileWriter StringBufferInputStream PipedInputStream PipedOutputStream FileInputStream FileOutputStream SequenceInputStream ObjectInputStream ObjectOutputStream DataInputStream DataOutputStream LineNumberInputStream PushbackInputStream PrintStream BufferedInputStream BufferedOutputStream FilterInputStream FilterOutputStream Pipe File Concatenation Object Serialization Data Conversion Counting Peeking Ahead Printing Buffering Filtering Converting between Bytes and Characters Use of streams N/A N/A N/A LineNumberReader PushbackReader PrintWriter BufferedReader BufferedWriter FilterReader FilterWriter InputStreamReader OutputStreamWriter 262 . Note that many times.io's streams and describes what they do. which occurs when the object is no longer referenced. input streams. and output streams--are automatically opened when created. java. You can close any stream explicitly by calling its close method. writers. Writer defines these methods for writing characters and arrays of characters: int write(int c) int write(char cbuf[]) int write(char cbuf[]. int offset. Or the garbage collector can implicitly close it.Writer and OutputStream are similarly parallel. int offset. int length) And OutputStream defines the same methods but for bytes: int write(int c) int write(byte cbuf[]) int write(byte cbuf[].io contains character streams and byte streams that perform the same type of I/O but for different data types. Stream classes The following table lists java. int length) All of the streams--readers.

LineNumberInputStream. FileOutputStream Collectively called file streams. DataOutputStream Read or write primitive data types in a machine-independent format. Pipes are used to channel the output from one thread into the input of another. FileWriter. ByteArrayInputStream. CharArrayWriter. StringReader. DataInputStream.CharArrayReader. FileInputStream. LineNumberReader Keeps track of line numbers while reading. PipedOutputStream Implement the input and output components of a pipe. ObjectOutputStream Used to serialize objects. ObjectInputStream. Use StringWriter to write to a String. StringWriter. StringWriter collects the characters written to it in a StringBuffer. PipedWriter. except that it reads bytes from a PipedReader. You create these streams on an existing array and then use the read and write methods to read from or write to the array. StringBufferInputStream Use StringReader to read characters from a String in memory. ByteArrayOutputStream Use these streams to read from and write to memory. PushbackInputStream 263 . PipedInputStream. FileReader. is similar to StringReader. these streams are used to read from or write to a file on the native file system. StringBufferInputStream StringBuffer. which can then be converted to a String. PushbackReader. SequenceInputStream Concatenates multiple input streams into one input stream.

Buffered streams are typically more efficient than similar nonbuffered streams and are often used with other streams. in. System. FilterWriter.lang defines a class called System. using the default character encoding or a character encoding specified by name. PrintWriter Contain convenient printing methods. System. The predefined Streams The java. System. When reading data from a stream. thereby reducing the number of accesses required on the original data source. using the default character encoding or a character encoding specified by name and then writes those bytes to an OutputStream.getProperty("file. By default this is the console. BufferedWriter. System also contains three predefined streams variables. which encapsulates several aspects of the run-time environment. InputStreamReader. it is sometimes useful to peek at the next few bytes or characters in the stream to decide what to do next. An OutputStreamWriter converts characters to bytes.in refers to the standard input. which is the keyboard by default. BufferedReader. these streams may be redirected to any compatible I/O device. PrintStream.These input streams each have a pushback buffer. You can get the name of the default character encoding by calling System. FilterInputStream. However. FilterOutputStream These abstract classes define the interface for filter streams.encoding"). so you will often see other writable streams wrapped in one of these. An InputStreamReader reads bytes from an InputStream and converts them to characters. These are the easiest streams to write to.err refers to the standard error stream.out refers to standard output stream. FilterReader. which also is the console by default. BufferedInputStream. 264 . These fields are declared as public static within System. OutputStreamWriter A reader and writer pair that forms the bridge between byte streams and character streams. which filter data as it's being read or written. out and err. BufferedOutputStream Buffer data while reading or writing.

public class ConsoleInputDemo { public static void main(String[] args) { try { BufferedReader stdin =new BufferedReader( new InputStreamReader(System. that converts bytes to characters. Its general form is shown here: String readLine() throws IOException An example of reading an entire line of input from console import java.out.in in a BufferedReader object.in.println(e). The readLine() method is a member of BufferedReader class. System. it can be used for inputStream.out. to create a character stream. Reader is an abstract class. To obtain InputStreamReader object.in)). To obtain a character-based stream that is attached to the console.*.io.err are objects of type PrintStream. System.readLine()). BufferedReader stdin =new BufferedReader( new InputStreamReader(System. } catch(IOException e) { System. InputStreamReader is its concrete sub-class.2 Reading console input In Java.in refers to an object of type InputStream.println(stdin.out and System. System.in is an object of the type InputStream. console input is accomplished by reading from System. 265 . even though they typically are used to read and write characters from and to the console.System.in)). The constructor of BufferedReader used is shown below: BufferedReader (Reader inputReader) Here inputReader is the stream that is linked to the instance of BufferedReader that is being created. } } } One example that reads from the console and prints the same string and terminates when an empty string is entered. 11. BufferedReader supports buffered input stream.out. These are byte streams. you wrap System.print("Enter a line:"). use the following constructor: InputStreamReader (InputStream inputStream) Because System.

import java.io.3 Writing console output This example prints a single character on the console. class BRRead { public static void main(String args[]) throws IOException{ char c.in)).import java.*. ‘q’ to quit:”).length() != 0) { System. String s = null.in)).print(c). We can obtain many print() and println() overloaded methods with the PrintWriter class.out stream.*. The OutputStreamWriter class only has a few basic write() methods. } } } An example of reading characters import java. System.read(). 266 . //read characters do { c = (char) br.out. } while( c != ‘q’). } } 11.io.println(s).printStackTrace().out. System. try { while((s = in. BufferedReader br = new BufferedReader ( new InputStreamReader(System.io. In this example we simply wrap the 16-bit encoded OutputStreamWriter class around the usual System.*.readLine()). } // An empty line terminates the program } catch(IOException e) { e.out.println(“Enter characters . public class Echo { public static void main(String[] args) { DataInputStream in = new DataInputStream( new BufferedInputStream(System.

} catch (IOException ioe) { System. public class StringOutput { public static void main(String f[]) { PrintWriter pw = new PrintWriter(System.write(c). import java.println( "IO error:" + ioe ).out). try { for( int i = 0. } } } Another example that prints a String on the console using PrintWriter class.text. i++) { c = s. } } } 11.*. i< s.println(s).4 System.println( "IO error:" + ioe ).true). String s = “Hello”. which provides a wide range of formatting options combined with output operation. OutputStreamWriter osw = new OutputStreamWriter(System.out.out 8-bit stream with the 16-bit // output stream.io. // Wrap the System.out. We take advantage of the autoflushing switch in one of the PrintWriter constructors so that we do not have to flush the buffers explicitly ourselves after every print.public class SingleCharConsole16bit { public static void main(String f[]) { char c. osw. String s = “Hello”. try { pw.out. } osw. } catch (IOException ioe) { System.charAt(i).printf() The java.Format subclasses offer limited formatting capabilities and are rather clumsy compared to the C language printf() function.flush().out. 267 .length().

Object.0 added a printf() method to the PrintStream class.util. The format argument is a string in which you embed specifier substrings that indicate how the arguments appear in the output.3f%n".. e.octal integer 'e' . J2SE 5. The '%' sign signals a specifier.precision]conversion 268 .out. of which there are several besides 'f'. double pi = Math. The simplest of the overloaded versions of the method goes as printf (String format.. args) The ". It uses a java.util. The general form of the specifier includes several optional terms: %[argument_index$][flags][width][.142 The format string includes the specifier "%5. A specifier needs at least the conversion character.Formatter. and the conversion symbol 'f' indicates a decimal representation of a floating-point number. So now you can use System.floating-point in scientific notation There are also special conversions for dates and times." indicates the varargs functionality.out.decimal integer 'o' . the precision value 3 requires three places in the fraction. System. For example.printf() to send formatted numerical output to the console.0 comes with the class java. It allows a method to accept a variable number of arguments.To satisfy the demands of programmers for such a facility and to facilitate the porting of C programs to Java.. Some of the other conversions include 'd' . Furthermore. J2SE 5. the wrappers for the primitives.PI.printf ("pi = %5.Formatter object internally.g. pi). which can both format numerical output into a string and send the string to a file or other destination Numerical values are formatted according to format specifiers like those for the printf() function in C. The width value 5 requires at least five characters for the number. The arguments can be primitives as well as object references.3f" that is applied to the argument.. results in the console output pi = 3.

out.out.3f %n".out.0 = %5. It is " %n" which outputs a line break. public class PrintfDemo { /** Illustrate several output formats with printf() **/ public static void main (String args[]) { double q = 1. A "\n" can also be used in some cases. System. System.E). r).0. // Increase the number of decimal places System.0 = %7.printf ("3.5f %n".5f * %2$4.out.3f %n". q).out. q).2e %n". System.printf ("1. but since "%n" always outputs the correct platformspecific line separator. q = 1.3f. // Scientific notation q = 1000. '+' requires that a sign be included and '0' requires padding with zeros.0 = %7. q). // User the argument index to put the argument values into // different locations within th string.printf ("0.0/0. "+ "A = %2$4.0. System.1f * %1$5.1f * %2$4.0/2.printf ("1000/3.0/3.printf ("C = 2 * %1$5. Math.1. // Print the number with 3 decimal places. 269 .PI. A flag indicates an option for the format.printf ("1. %2$ indicates the second argument in the list.0/0. Math.0/4567. Math. double r = 1.out.0/0.out.0/0. it is portable across platforms whereas"\n" is not.0. // NaN System. For example.0.2e %n".PI.0.0 = %09. // Negative infinity q = -1. q).1f. The width indicates the minimum number of characters and the precision is the number of places for the fraction.0 = %7. // Pad with zeros. q).0.printf ("-1.printf ("pi = %5. System. // Multiple arguments System. q).printf ("1.0 = %5.5f %n". The following program provides several examples of printf().2e %n".out. For example. System. q).4f %n".0/3.The argument_index indicates to which argument the specifier applies. q = 0.0/4567.0/3.2e %n". e = %5. There is also one specifier that doesn't correspond to an argument. // More scientific notation q = 3.0/2.0 = %7.0/3.out.

date and directory path. and to navigate subdirectory hierarchies.1 * 1. time.0 = -Infinity 0. Or File f = new File ("c:/server/classes/Hansen/playground/MyFile. You may also use a relative file name like this: File f = new File("hansen\\playground\\MyFile. such as permissions.0 = 3.0/0. e = 2.0 = NaN pi = 3.1 * 3.0/3. which most often is where the Java Virtual Machine is invoked.0 = 6. The simplest is this (using Windows file-syntax): File f = new File ("c:\\server\\classes\\hansen\\playground\\MyFile.0/3.7183 C = 2 * 3.1. We create an instance of the class by giving the name of the file (or directory).0/4567. A = 1.class"). There are several constructors: The File class has the following constructors File(String pathname). File(File directory.io can be used to obtain or manipulate the information associated with a disk file.14159 11.0/2.33e+02 3.class"). String filename).class"). A File object can represent either the name of a particular file or the names of a set of files in a directory.0 = 00000.142. String filename).57e-04 -1.0/0.14159 * 1.5 File class A File class present in java.33333 1. If you are in doubt you can get the name of the current user directory like this: 270 . // pathname could be file or a directory name File(String dirPathname. To use this format you'll have to know the "current user directory".333 1.500 1000/3.0 = 0.} } // class PrintfDemo Output of this program: 1.0 = 0.

String userdir = System.getProperty("user.dir");

Several methods are available for inspecting an instance of the File class. Some of the important ones are: Method
boolean exists() boolean isFile() boolean isDirectory() String[] list() String getName() String getPath()

Purpose does the file exist? is it a file? … or a directory? return the names of all files and directories in a directory get the file or directory's name get the file or directory's path

These methods are actually all we need in order to find all files and directories in a given directory--all the way down to the last leaves in the directory tree The File class is more than just a representation for an existing directory path, file, or group of files. You can also use a File object to create a new directory or an entire directory path. You can also look at the characteristics of files (size, last modification date, read/write), see whether a File object represents a file or a directory, and delete a file. If the file mentioned is not found the program simply exits.
import java.io.*; public class FileExample { public static void main(String[] args) { File f = new File(args[0]); if(f.exists()) { System.out.println(f + " exists"); } else { return; } System.out.println( "Absolute path: " + f.getAbsolutePath() + "\n Can read: " + f.canRead() + "\n Can write: " + f.canWrite() + "\n getName: " + f.getName() + "\n getParent: " + f.getParent() + "\n getPath: " + f.getPath() + "\n file size: " + f.length() + "\n lastModified: " + f.lastModified()); if(f.isFile()) System.out.println("it's a file"); else if(f.isDirectory()) System.out.println("it's a directory"); File rname = new File(args[1]);

271

f.renameTo(rname); File another = new File(args[2]); System.out.println("deleting..." + another); another.delete(); File makedir = new File(args[3]); makedir.mkdir(); } }

This program takes a filename as the first argument checks whether it exists. If yes then prints the characteristics of the file else exits the program. Next it also checks whether the file object is a file or directory. Then it renames the file as the second argument. The third argument specifies the file to be deleted. The fourth argument is the name of the new directory that gets created. The following program prints the list of all filenames and names of sub directories into the current directory.
// Displays directory listing import java.io.*; public class DirList { public static void main(String[] args) { try { File path = new File("."); // current directory String[] list = path.list(); for(int i = 0; i < list.length; i++) System.out.println(list[i]); } catch(Exception e) { e.printStackTrace(); } } }

The following program prints the list of only .java files in the current directory
import java.io.*; public class DirList { public static void main(String[] args) { try { File path = new File("."); // current directory String[] list = path.list(new DirFilter(“.java”)); for(int i = 0; i < list.length; i++) System.out.println(list[i]); } catch(Exception e) { e.printStackTrace(); } } }

272

class DirFilter implements FilenameFilter { String afn; DirFilter(String afn) { this.afn = afn; } public boolean accept(File dir, String name) { // Strip path information: String f = new File(name).getName(); return f.indexOf(afn) != -1; } }

The interface FilenameFilter has only one method
boolean accept(File dir, String name);

It says that all this type of object does is provide a method called accept( ). The whole reason behind the creation of this class is to provide the accept( ) method to the list( ) method so that list( ) can call back accept( ) to determine which file names should be included in the list. Thus, this technique is often referred to as a callback or sometimes a functor (that is, DirFilter is a functor because its only job is to hold a method). Because list( ) takes a FilenameFilter object as its argument, it means that you can pass an object of any class that implements FilenameFilter to choose (even at runtime) how the list( ) method will behave. The purpose of a callback is to provide flexibility in the behavior of code. DirFilter shows that just because an interface contains only a set of methods, you’re not restricted to writing only those methods. In this case, the DirFilter constructor is also created. The accept( ) method must accept a File object representing the directory that a particular file is found in, and a String containing the name of that file. You might choose to use or ignore either of these arguments, but you will probably at least use the file name. Remember that the list( ) method is calling accept( ) for each of the file names in the directory object to see which one should be included – this is indicated by the boolean result returned by accept( ). To make sure that what you’re working with is only the name and contains no path information, all you have to do is take the String object and create a File object out of it, then call getName( ) which strips away all the path information (in a platform-independent way). Then accept( ) uses the String class indexOf( ) method to see if the search string afn appears anywhere in the name of the file. If afn is found within the string, the return value is the starting index of afn, but if it’s not found the return value is -1. Keep in mind that this is a simple string search and does not have regular expression “wildcard” matching.

273

11.6 Using File Streams
File streams are perhaps the easiest streams to understand. The file streams-- FileReader, FileWriter, FileInputStream, and FileOutputStream--each read or write from a file on the native file system. You can create a file stream from a file name in the form of a string, a File object, or a FileDescriptor object. An Example of reading from a file using FileReader and printing the file contents on the console. The filename is passed as a command line argument. The FileReader class below accepts the filename as the argument and opens it for reading. If the file is not found an exception of type FileNotFoundException is thrown. FileNotFoundException is a checked exception and is a subclass of IOException. The readLine method of the BufferedReader reads a String till the end of the line. It throws the checked IOException. Hence both the exeptions are handled explicitly by using catch blocks.
import java.io.*; public class FileReadDemo { public static void main(String[] args) { try { BufferedReader in =new BufferedReader(new FileReader(args[0])); String s = new String(); String s2=””; while((s = in.readLine())!= null) s2 += s + "\n"; in.close(); } catch(FileNotFoundException e) { System.out.println(e); } catch(IOException e){ System.out.println(e); } } }

The following program uses FileReader and FileWriter to copy the contents of a file named farrago.txt into a file called outagain.txt:
import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile);

274

FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } }

This program is very simple. It opens a FileReader on farrago.txt and opens a FileWriter on outagain.txt. The program reads characters from the reader as long as there's more input in the input file and writes those characters to the writer. When the input runs out, the program closes both the reader and the writer. Here is the code that the Copy program uses to create a file reader:
File inputFile = new File("farrago.txt"); FileReader in = new FileReader(inputFile);

This code creates a File object that represents the named file on the native file system. File is a utility class provided by java.io. The Copy program uses this object only to construct a file reader on a file. However, the program could use inputFile to get information, such as its full path name, about the file. After you've run the program, you should find an exact copy of farrago.txt in a file named outagain.txt in the same directory. Remember that FileReader and FileWriter read and write 16-bit characters. However, most native file systems are based on 8-bit bytes. These streams encode the characters as they operate according to the default character-encoding scheme. You can find out the default characterencoding by using System.getProperty("file.encoding"). To specify an encoding other than the default, you should construct an OutputStreamWriter on a FileOutputStream and specify the encoding. A program that prints the line in a file myfile.txt
import java.io.*; class FileOutputDemo { public static void main(String args[]) { FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object try {

275

} catch (Exception e) { System.err.println ("Error writing to file"); } } }

// Create a new file output stream // connected to "myfile.txt" out = new FileOutputStream("myfile.txt"); // Connect print stream to the output stream p = new PrintStream( out , true); p.println ("This is written to a file"); p.close();

Here is another version of the program, CopyBytes, which uses FileInputStream and FileOutputStream instead of FileReader and FileWriter.
import java.io.*; public class CopyBytes { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } }

An example to read from a file and print it on screen and also print the line numbers in front of each line
import java.io.*; class ReadFileDemo { public static void main(String args[]) { try { FileReader fin = new FileReader(“file1.txt”); LineNumberReader li =new LineNumberReader(fin); BufferedReader in4 = new BufferedReader(li); PrintWriter out1 = new PrintWriter(System.out, true); String s=null; while((s = in4.readLine()) != null ) {

276

} }

} catch(EOFException e) { System.out.println("End of stream"); }

out1.println("Line " + li.getLineNumber() + s); } out1.close();

An example of storing some content in a file and recovering it.
import java.io.*; public class FileStore { public static void main(String[] args) { try { DataOutputStream out2 = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("Data.txt"))); out2.writeDouble(3.14159); out2.writeBytes("That was pi"); out2.close(); DataInputStream in5 = new DataInputStream( new BufferedInputStream( new FileInputStream("Data.txt"))); BufferedReader in5br = new BufferedReader( new InputStreamReader(in5)); System.out.println(in5.readDouble()); System.out.println(in5br.readLine()); } catch(EOFException e) { System.out.println("End of stream"); } } }

Another program that reads from a file using FileInputStream one byte at a time but checks whether the information is available before reading.
import java.io.*; public class TestEOF { public static void main(String[] args) { try { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream("TestEof.java"))); while(in.available() != 0) { System.out.print((char)in.readByte());

277

} }

} } catch (IOException e) { System.err.println("IOException"); }

Concatenating Files The SequenceInputStream creates a single input stream from multiple input sources. This example program, Concatenate, uses SequenceInputStream to implement a concatenation utility that sequentially concatenates files file1.txt and file2.txt together. This is the controlling class of the Concatenate utility:
import java.io.*; public class Concatenate { public static void main(String[] args) throws IOException { FileInputStream fin1 = new FileInputStream(“file1.txt”); FileInputStream fin2 = new FileInputStream(“file2.txt”); SequenceInputStream s = new SequenceInputStream(fin1,fin2); int c; while ((c = s.read()) != -1) System.out.write(c); s.close(); } }

11.7 Scanning text with java.util.Scanner
J2SE 5.0 adds classes and methods that can make every day tasks easier to perform. You will see how the newly added java.util.Scanner class makes it easier to read and parse strings and primitive types using regular expressions. Before the J2SE 5.0 release, you probably would have written code such as the following TextReader class to read text from a file:
import java.io.*; public class TextReader { public static void main(String[] args) { try { File file = new File(“TextSample.txt”); FileReader reader = new FileReader(file); BufferedReader in = new BufferedReader(reader);

278

util.io. To create the document.txt”).util. import java.printStackTrace().println(string). You should see the original file echoed back to you in standard output.readLine()) != null) { System. save the following two lines of text in a file named TextSample. you need to create a document for the class to read and parse. public class TextScanner { public static void main (String args[]) { try { File file = new File(“TextSample. You can simplify the code in TextReader by using java.close().close().hasNext()) { System. The basic approach in classes like this is to create a File object that corresponds to the actual file on the hard drive.scanner. It then uses the BufferedFile reader to read the file one line at a time. } scanner. The class then creates a FileReader associated with the file and then a BufferedReader from the FileReader. while ((string = in. while (scanner.out.printStackTrace(). } String string = null.next()). To view the TextReader class in action.util. a class that parses primitive types and strings: import java.Scanner. Scanner scanner = new Scanner(file).Scanner.out. } in.txt in the same directory as TextReader: Here is a small text file that you will use to test java.} } } catch (IOException e) { e. } catch (FileNotFoundException e) { e. } } } You should get the following output: 279 .println(scanner.*.

double x = input. line: ").print("Enter int.scanner. This method returns true if another token exists in the Scanner's input. By default the delimiter pattern is whitespace.util.separator")). String word = input. } catch (FileNotFoundException e) { e.next(). which is the case until it reaches the end of the file. Here is the revised code for TextScanner that uses a newline character as the delimiter: try { Scanner scanner = new Scanner(new File(fileName)). For example. So until it reaches the end of the file.nextDouble(). word. } scanner.println(scanner.close().out.util.out. } One more example of using Scanner public class ScannerTest { public static void main(String[] args) { Scanner input = new Scanner(System.getProperty("line.hasNext()) { System. // returns a String up to next whitespace String line = input. You can pass in a String or a java.nextLine(). you can read the input one line at a time by using the newline character (\n) as a delimiter.nextInt(). You can change the delimiter that is used to tokenize the input. TextScanner then calls the hasNext() method in Scanner.printStackTrace(). through the useDelimiter method of Scanner. The next() method returns a String that represents the next token. // returns rest of line & eats the '\n' 280 . The Scanner breaks the contents of the File into tokens using a delimiter pattern.next()). while (scanner.Pattern to the method. TextScanner creates a Scanner object from the File.useDelimiter (System. System.Here is a small text file that you will use to test java.in). scanner.regex. int a = input. TextScanner prints the String returned by next() on a separate line. double.

output. PrintStream out = new PrintStream(new BufferedOutputStream( new FileOutputStream("test. // write it to another file } out. class Redirecting { public static void main(String[] args) { try { BufferedInputStream in = new BufferedInputStream( new FileInputStream("Redirecting.println(s). Redirecting input is valuable for a command-line program in which you want to test a particular user-input sequence repeatedly.in)).printStackTrace(). Sample output: Enter int.out.true)). System. System.out").} } System. } } } 281 . // close file output stream } catch(IOException e) { e. line: -12 34.setErr(out).close().56 Great time had by all! -12:34. Here’s a simple example that shows the use of these methods: import java.8 Redirecting Standard I/O The methods in System class allow you to redirect the standard input. //reads from the file String s.out.readLine()) != null) { System.56:Great: time had by all! 11. and error IO streams using simple static method calls: setIn(InputStream) setOut(PrintStream) setErr(PrintStream) Redirecting output is especially useful if you suddenly start creating a large amount of output on your screen and it’s scrolling past faster than you can read it. word. BufferedReader br = new BufferedReader( new InputStreamReader(System.*.java")).println(a + ":" + x + ":" + word + ":" + line).io. System. double.setOut(out). while((s = br.setIn(in).

The RandomAccessFile class implements both the DataInput and DataOutput interfaces and therefore can be used for both reading and writing. You can do this with a file name or a File object. you can use the common read or write methods defined in the DataInput and DataOutput interfaces to perform I/O on the file. And this one opens the same file for both reading and writing: new RandomAccessFile("farrago. RandomAccessFile contains three methods for explicitly manipulating the file pointer. After the file has been opened. indicating the beginning of the file.io package implements a random access file. (You have to be able to read a file in order to write it.txt". 11. or random. The file pointer indicates the current location in the file. A random access file.  int skipBytes(int)--Moves the file pointer forward the specified number of bytes 282 .txt: new RandomAccessFile("farrago. The RandomAccessFile class in the java. access to a file's contents. When you create a RandomAccessFile.txt". When the file is first created. such as paper and magnetic tape.) The following code creates a RandomAccessFile to read the file named farrago.This program attaches standard input to a file. permits nonsequential. they are a consequence of a sequential medium. RandomAccessFile supports the notion of a file pointer. In addition to the normal file I/O methods that implicitly move the file pointer when the operation occurs. "rw"). and redirects standard output and standard error to another file. on the other hand. RandomAccessFile is similar to FileInputStream and FileOutputStream in that you specify a file on the native file system to open when you create it. Calls to the read and write methods adjust the file pointer by the number of bytes read or written. "r"). the file pointer is set to 0.9 Working with Random Access Files The input and output streams in this lesson so far have been sequential access streams--streams whose contents must be read or written sequentially. Although such streams are incredibly useful. you must indicate whether you will be just reading the file or also writing to it.

} catch(IOException e){} 283 . System. int temp. for(int cnt = 0.print( (char)inData. } System.getFilePointer(). cnt < 4.println("Display the entire file as characters. System. //Get current location of the file pointer.write('W'+cnt). try{ RandomAccessFile inData = new RandomAccessFile(junkFile. //Now read and display four bytes.close().print((char)temp)."). while( (temp = inData.io.txt"). filePointer = inData. cnt < 4.println(“\nNow write four bytes interior to the file. inData. inData.seek(filePointer-8).getFilePointer(). while( (temp = inData.read() ). cnt++) inData. System. for(int cnt = 0.out. long filePointer = inData.").out.println("Now open and read the file for random access“).out.out. System. //Note that it is necessary to reposition the file // pointer to the beginning of the file. class files03{ public static void main(String[] args) { File junkFile = new File("junk.read()) != -1) { System.print((char)temp).seek(filePointer-4)."rw").println("Now display four bytes interior to the file.out. inData.").println("Note that four bytes have been overwritten.out. inData.out. //Set the file pointer to a location interior to // the file.out.println("Now display the entire file again.read()) != -1) System. System.out."). cnt++) System.seek(0).").  void seek(long)--Positions long getFilePointer()--Returns the file pointer just before the specified byte the current byte location of the file pointer An example of using RandomAccessFile import java.*.

Some streams buffer the data. The filtering done by the streams depends on the stream.io package contains only one subclass of FilterReader: PushbackReader. FilterInputStream. filters it.io package provides a set of abstract classes that define and partially implement filter streams. //do something interesting here } Note that the readLine method has been deprecated in the DataInputStream. It features an example. A filter stream filters data as it's being read from or written to the stream.. Most filter streams provided by the java.) The java.println("\nEnd of program"). as in the following code: BufferedReader d = new BufferedReader(new DataInputStream(System. The write method in a writable filter stream filters the data and then writes it to the underlying stream. String input. and FilterOutputStream. DataIODemo. some count data as it goes by. For example.10 Filter Streams The java.System.io DataInputStream and DataOutputStream classes. while ((input = d. The read method in a readable filter stream reads input from the underlying stream. How to Use DataInputStream and DataOutputStream This page shows you how to use the java.readLine()) != null) { .in)). Using Filter Streams To use a filter input or output stream..out. The filter streams are FilterInputStream or FilterOutputStream.io package are subclasses of FilterInputStream and FilterOutputStream and are listed here:      and DataOutputStream BufferedInputStream and BufferedOutputStream DataInputStream LineNumberInputStream PushbackInputStream PrintStream (This is an output stream. }// end main }//end class files03 definition 11. and others convert data to another form. therefore we've wrapped it in a BufferedReader. attach the filter stream to another input or output stream when you create it. you can attach a filter stream to the standard input stream. A filter stream is constructed on another stream (the underlying stream). and passes on the filtered data to the caller. that reads and writes tabular data (invoices for 284 .

a set up to read the file just written. Next. i < prices.readChar(). in. The columns contain the sales price.txt: output streams. } 285 . Next.writeDouble(prices[i]). out. must be attached to another a FileOutputStream that is set up to write to a file DataOutputStream out = new DataOutputStream( new FileOutputStream("invoice1. the number of units ordered. DataInputStream FileInputStream try { while (true) { price = in. also must be attached to another InputStream. in.length. In this case. //throws out the tab unit = in. Then DataIODemo just reads the data back in using DataInputStream's specialized read methods.writeChars(descs[i]). although it is read and written in binary form and is non-ASCII: 19. while ((chr = in. and a description of the item. like other filtered OutputStream. //throws out the tab char chr.writeChar('\t'). } out.readDouble(). The tabular data is formatted in columns separated by tabs. Conceptually. desc = new StringBuffer(20). invoice1. in this case.writeChar('\t'). DataIODemo opens a DataInputStream on the file just written: DataInputStream in = new DataInputStream( new FileInputStream("invoice1. the data looks like this.readChar() != lineSep) { desc.readChar().txt")).append(chr).separator").99 9. out.99 12 8 Java T-shirt Java Mug DataOutputStream.writeInt(units[i]). DataIODemo uses DataOutputStream's specialized write methods to write the invoice data contained within arrays in the program according to the type of data being written: for (int i = 0. char lineSep = System. out.readInt().txt.merchandise).writeChar('\n'). i ++) { out. out.txt")).charAt(0). out.close().getProperty("line. it's attached to named invoice1.

the while (true) terminates.99.out.System. } The read method returns a value. } } catch (EOFException e) { } System. When all of the data has been read. "Java Pin". Many of the DataInputStream read methods can't do this. "Duke Juggling Dolls". 286 .writeDouble(prices[i]). null.99. Note the loop that DataIODemo uses to read the data from the DataInputStream. i ++) { out. "Java Mug". when data is read. double[] prices = { 19. So DataInputStreams read methods throw an EOFException instead.writeChar('\t').writeChars(descs[i]). suppose that you want to use -1 to indicate end of file. int[] units = { 12.txt")). total = total + unit * price.writeInt(units[i]). 15. you can't. 29. 50 }. or one of the other methods that reads numbers. out. Well. 8.99. "Java Key Chain" }.writeChar('\n'). 9.io. using readDouble.read()) != null) { . public class DataIODemo { public static void main(String[] args) throws IOException { // write the data out DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1. readInt. out.length. 13. For example. 4. out.99. 3. you see loops like this: while ((input = in.*. . for (int i = 0. because -1 is a legitimate value that can be read from the input stream. .99 }. DataIODemo displays a statement summarizing the order and the total amount owed and then closes the stream. in. out. import java.writeChar('\t'). Normally.println("For a TOTAL of: $" + total). which indicates that the end of the file has been reached.out. String[] descs = { "Java T-shirt". i < prices. When the EOFException occurs. because any value that could be returned to indicate the end of file may also be a legitimate value read from the stream.close(). out.println("You've ordered " + unit +" units of " + desc + " at $" + price).

in.} out.io-.readChar().txt")).println("You've ordered " + unit + " units of " +desc + " at $" + price). 287 .close(). in. However.getProperty("line. } } catch (EOFException e) { } System.99 You've ordered 29 units of Java Pin at $3. StringBuffer desc. System. // read it in again DataInputStream in = new DataInputStream(new FileInputStream("invoice1.append(chr).out. in.println ("For a TOTAL of: $" + total).99 For a TOTAL of: $892. double price.readInt().99 You've ordered 13 units of Duke Juggling Dolls at $15.ObjectInputStream and ObjectOutputStream-.out.11 Object Serialization Two streams in java.8800000000001 11. try { while (true) { price = in. double total = 0. char lineSep = System. int unit.separator").99 You've ordered 8 units of Java Mug at $9. total = total + unit * price. while ((chr = in. desc = new StringBuffer(20). // throws out the tab char chr.readChar()) != lineSep) desc.are byte streams and work like the other input and output streams. // throws out the tab unit = in.readChar(). } } When you run the DataIODemo program you should see the following output: You've ordered 12 units of Java T-shirt at $19.charAt(0).readDouble().99 You've ordered 50 units of Java Key Chain at $4.0. they are special in that they can read and write objects.close().

or writeUTF. You can use object serialization in the following ways: • • Remote Method Invocation (RMI)--communication between objects via sockets Lightweight persistence--the archival of an object for use in a later invocation of the same program.flush(). ObjectOutputStream s = new ObjectOutputStream(out). the writeObject method serializes the specified object. you need to know how to serialize objects by writing them to an ObjectOutputStream and reading them in again using an ObjectInputStream. This code constructs an ObjectOutputStream on a FileOutputStream. ObjectOutputStream implements the DataOutput interface that defines many methods for writing primitive data types. How to Write to an ObjectOutputStream Writing objects to a stream is a straightforward process. In this way. Object serialization is essential to building all but the most transient applications. Next. First. s. Serializing Objects Reconstructing an object from a stream requires that the object first be written to a stream. the string Today and a Date object are written to the stream with the writeObject method of ObjectOutputStream. s. ObjectOutputStream must be constructed on another stream. traverses its references to other objects recursively. writeFloat. An object is serializable only if its class implements the Serializable interface. the following gets the current time in milliseconds by constructing a Date object and then serializes that object: FileOutputStream out = new FileOutputStream("theTime").writeObject("Today").The key to writing an object is to represent its state in a serialized form sufficient to reconstruct the object as it is read. such as writeInt. relationships between objects are maintained. How to Read from an ObjectInputStream 288 . You can use these methods to write primitive data types to an ObjectOutputStream. Thus. and writes them all. s. The writeObject method throws a NotSerializableException if it's given an object that is not serializable. thereby serializing the object to a file named theTime. For example.writeObject(new Date()). Thus reading and writing objects is a process called object serialization. You need to know about object serialization from two points of view.

io. Implementing the Serializable Interface Here's the complete definition of the Serializable interface: package java. the class must implement the Serializable interface.Once you've written objects and primitive data types to a stream. You just add the implements Serializable clause to your class declaration like this: public class MySerializableClass implements Serializable { . you'll likely want to read them out again and reconstruct the objects. In this example. if you want to serialize the instances of one of your classes.. the objects were archived in a file. ObjectInputStream stream implements the DataInput interface that defines methods for reading primitive data types. The objects must be read from the stream in the same order in which they were written.readObject(). ObjectInputStream must be constructed on another stream. Thus. Like ObjectOutputStream. ObjectInputStream s = new ObjectInputStream(in). The readObject method deserializes the next object in the stream and traverses its references to other objects recursively to deserialize all objects that are reachable from it. the code uses ObjectInputStream's readObject method to read the String and the Date objects from the file. The good news is that Serializable is an empty interface. it doesn't contain any method declarations. so the code constructs an ObjectInputStream on a FileInputStream. public interface Serializable { // there's nothing in here! }. The methods in DataInput parallel those defined in DataOutput for writing primitive data types. it maintains the relationships between the objects. Providing Object Serialization for Your Classes An object is serializable only if its class implements the Serializable interface. Date date = (Date)s. Here's code that reads in the String and the Date objects that were written to the file named theTime in the previous example: FileInputStream in = new FileInputStream("theTime"). This is also straightforward. readFloat.readObject(). Next. its purpose is simply to identify classes whose objects are serializable.. 289 . String today = (String)s. In this way. Note that the return value from readObject is an object that is cast to and assigned to a specific type. That is. Use these methods to read primitive data types from an ObjectInputStream. They include methods such as readInt. Making instances of your classes serializable is easy. and readUTF.

290 . To accomplish this. The class should implement writeObject and readObject methods to save and restore only the appropriate state. Marking the field will prevent the state from appearing in the stream and from being restored during deserialization. double d. For example. including the following:    Class of the object Class signature Values of all non-transient and non-static members. class MyClass implements Serializable { String s. including members that refer to other objects You can deserialize any instance of the class with the defaultReadObject method in ObjectInputStream. you must provide either that the sensitive state of an object must not be restored from the stream or that it must be reverified by the class. the object should not implement either the Serializable interface. the private state of the object is restored. An example of Serialization : import java. Since writing and reading (of private fields) cannot be superseded outside of the class. The serialization of instances of this class are handled by the defaultWriteObject method of ObjectOutputStream. During deserialization. the class's transient fields are safe.*. int i.} You don't have to write any methods. throwing a NotSerializableException will prevent further access. To avoid compromising a class. The easiest is to mark fields that contain sensitive data as private transient. Being able to forge a file descriptor would allow some forms of illegal access. you must take care to protect sensitive information and functions. This method automatically writes out everything required to reconstruct an instance of the class. Particularly sensitive classes should not be serialized. since restoring state is done from a stream. If access should be denied.io. a file descriptor contains a handle that provides access to an operating system resource. Protecting Sensitive Information When developing a class that provides controlled access to resources. Several techniques are available to protect sensitive data in classes. Therefore the serializing runtime must take the conservative approach and not trust the stream to contain only valid representations of objects. transient and static fields are not serialized or deserialized. Some classes may find it beneficial to allow writing and reading but to specifically handle and revalidate the state as it is deserialized.

public MyClass(String s, int i, double d) { this.s = s; this.i = i; this.d = d; } public String toString() { return “s =” + s + “ , i =” + i + “, d =” + d; } } public class SerializationDemo { try { FileOutputStream fout = new FileOutputStream(“serial”); ObjectOutputStream os = new ObjectOutputStream(fout); os.writeObject(“Hello”); os.writeObject(new java.util.Date()); os.writeObject(new MyClass()); os.flush(); os.close(); } catch(Exception e) { System.out.println(e); } //object deserialization try { FileInputStream fin = new FileInputStream(“serial”); ObjectInputStream is = new ObjectInputStream(fin); String z = (String) is.readObject(); java.util.Date date = (java.util.Date) is.readObject(); MyClass obj = (MyClass) is.readObject(); is.close(); System.out.println(s); System.out.println(date); System.out.println(obj); } catch(Exception e) { System.out.println(e); } }

Summary
The System class provides three built in streams in java – in, out and err. All the api classes for performing input/output in java are a part of java.io package. There are two category of I/O classes – Byte stream and Character stream classes. There are separate classes that can be used for reading and writing into files. The File class can be used to get the properties of the file.

291

Chapter 12 : API classes in java.lang package
By default, each Java application/applet has access to the java.lang package. Inside java.lang are classes that represent primitive data types (such as int & char), as well as more complex classes. It contains classes pertaining to strings, string buffers, threads, and even the System class from which we obtain input and output streams.

12.1 Wrapper classes
Wrappers are used to enclose a simple datatype or a primitive object into an object. This is sometimes necessary because:
• • • • •

Simple datatypes are not part of the object hierarchy. Simple datatypes are passed by value and not by reference. Two methods can't refer to the same instance of a simple type. Some classes can only use members of another class and not a simple type. You can store a value of primitive type in a type-wrapper object whenever an object is required.

There are eight wrapper classes – one for each primitive data type. Primitive boolean byte char double float int long short Wrapper java.lang.Boolean java.lang.Byte java.lang.Character java.lang.Double java.lang.Float java.lang.Integer java.lang.Long java.lang.Short

All numeric wrapper classes are subclasses of the abstract class Number. The following figure shows the class hierarchy for the Number classes provided by the Java platform

292

BigInteger and BigDecimal extend the primitive data types to allow for arbitrary-precision numbers (numbers that might not fit into any of the primitive data types). Note that whereas the other classes are in the java.lang package, BigDecimal and BigInteger are in the java.math package. The Number class provides these methods
byte short int long float double byteValue(); shortValue(); intValue(); longValue(); floatValue(); doubleValue();

The classes define useful variables, such as MIN_VALUE and MAX_VALUE, that provide minimum and maximum value in the range of the data type. All wrapper objects are immutable. Once an object is created, the wrapped primitive value cannot be changed. Wrapper classes are final and hence cannot be sub classed. The Boolean class wrapper allows passing Boolean values (true and false) by reference. It contains the constants TRUE and FALSE, which define true and false Boolean objects. All the wrapper classes except Character have two constructors -- one that takes the primitive value and another that takes the String representation of the value. For instance:
Integer i1 = new Integer(50); Integer i2 = new Integer("50"); double d = 5.0; Double aD = new Double(d);

All wrapper classes have parseType methods eg parseInt(), parseShort, etc that take a String and parse it into the appropriate type. The six parser methods are parseInt, parseDouble, parseFloat, parseLong, parseByte, and parseShort. They take a String as the argument and convert it to the corresponding primitive. They throw a NumberFormatException if the String is not properly formed. For example,
double d = Double.parseDouble("4.23");

It can also take a radix(base) as the second argument: int i = Integer.parseInt("10011110",2); All wrapper classes (except Character) define a static method called valueOf(), which returns the wrapper object corresponding to the primitive value represented by the String argument. For example,

293

Integer I = Integer.valueOf("10011110",2);
Float f1 = Float.valueOf("1.5f");

Integer, Short, Byte and Long The Integer and Long classes also have the static methods toBinaryString(), toOctalString() and toHexString() which take an integer value and convert it to the appropriate String representation. The toHexString returns a string which is a hex string version of the number. It has a natural partner in the toBinaryString method which returns a string that represents the number in its binary version. The following example code will output the strings 100 followed by 10.
public class NumberFormats{ public static void main(String argv[]){ System.out.println(Integer.toBinaryString(4)); System.out.println(Integer.toHexString(16)); } }

Integer, and the longer form, Long, represent whole number values. Integers and Longs can be interchanged through the longValue() and intValue() methods, and can also be converted to floats and doubles using the floatValue() and doubleValue().
Integer my_integer = new Integer(256); Long my_long = my_integer.longValue();

One more example of converting a wrapper object value to primitive data type
Integer i = new Integer(20); byte b = i.byteValue();

Float and Double The constructors for Float and Double are shown below:
Float (double num) Float (float num) Float (String s) throws NumberFormatException Double (double num) Double (String s) throws NumberFormatException

Apart from the constants MIN_VALUE and MAX_VALUE these classes also have other constants like POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN and the following methods to test a value
public public public public boolean isNaN() static boolean isNaN(type value) boolean isInfinite() static boolean isInfinite(type value)

294

An example to show the use of isInfinite() and isNaN()
class InfNaN { public static void main(String args[]) { Double d1 = new Double(1/0.); Double d2 = new Double(0/0.); System.out.println(d1 + “ : ”+ d1.isInfinite() + “,” + d1.isNaN()); System.out.println(d2 + “ : ”+ d2.isInfinite() + “,” + d2.isNaN()); } }

This program generates the following output:
Infinity : true, false NaN : false, true

Both classes have methods to convert a value into a bit pattern or vice versa
public static int floatToIntBits(float value) public static float intBitsToFloat(int bits) public static long doubleToLongBits(double value)
public static double longBitsToDouble(long bits)

Floating point values, and the longer form, double, represent decimal (fractional) values. Floats and doubles can be interchanged through the doubleValue() and floatValue() methods, and can also be converted to integers and longs using the longValue() and intValue() methods. Its important to remember, however, that there will be a loss of precision, as integers and longs cannot retain the fractional component.
Float my_float = new Float(3.14); Double my_double = new Double (my_float.doubleValue()); // Print out double (3.14) System.out.println( "Double : " + my_double); // Print out integer (3) System.out.println( "Integer: " + my_double.intValue() );

Here's an example, called NumberDemo, that creates two Float objects and one Double object and then uses compareTo and equals to compare them:.
public class NumberDemo { public static void main(String args[]) { Float floatOne = new Float(14.78f - 13.78f); Float floatTwo = Float.valueOf("1.0"); Double doubleOne = new Double(1.0); int difference = floatOne.compareTo(floatTwo);

295

if (difference == 0) { System.out.println("floatOne is equal to floatTwo."); } else if (difference < 0) { System.out.println("floatOne is less than floatTwo."); } else if (difference > 0) { System.out.println("floatOne is greater than floatTwo."); } System.out.println("floatOne is " + ((floatOne.equals(doubleOne)) ? "equal" : "not equal") + " to doubleOne."); } }

The output from this program might surprise you a little:
floatOne is equal to oneAgain. floatOne is not equal to doubleOne.

Even though the values contained in floatOne and doubleOne are both numerically equal to 1, they are considered unequal because the objects are of different types. The numeric type-wrapper classes ( Byte, Integer, Double, Float, Long, and Short) each provide a class method named valueOf that converts a string to an object of that type. Character The Character class constructor takes a char type element as an argument:
Character c = new Character('A');

To obtain the char value contained in a Character object, call charValue() shown here,
char charValue()

The Character class contains a large set of character comparison routines, in the form of static methods.
static static static static static boolean boolean boolean boolean boolean isDigit( char c ); isLetter( char c ); isLetterOrDigit( char c ); isLowerCase( char c ); isUpperCase( char c );

static char toUpperCase( char c ); static char toLowerCase( char c );

A program is given below:

296

class IsDemo { public static void main(String args[]) { char a [] = {‘a’, ‘b’, ‘5’, ‘7’, ‘A’, ‘ for ( int i = 0; i < a.length ; i++) { if(Character.isDigit(a[i])) System.out.println(a[i]+ “is if(Character.isLetter(a[i])) System.out.println(a[i]+ “is if(Character.isWhitespace(a[i])) System.out.println(a[i]+ “is if(Character.isUpperCase(a[i])) System.out.println(a[i]+ “is if(Character.isLowerCase(a[i])) System.out.println(a[i]+ “is } } }

’}; a digit”); a letter”); whitespace”); uppercase”); lowercase”);

Character contains two methods for returning the numeric value of a character in the various number systems.
public static int digit(char ch, int radix) public static int getNumber(char ch)

and one method to return the character value of a number
public static char forDigit(int digit, int radix)

12.2 Autoboxing/Unboxing of Wrappers
In the previous section on wrapper classes for primitive type values, we discussed how to create an instance of a wrapper from a primitive value and conversely, how to obtain the primitive value held by the wrapper. This involves a a certain amount of clumsy code. For example, creating a Float object from a float primitive is straightforward:
float primitive_float = 3.0f; Float wrapper_float = new Float (primitive_float);

Going the other direction, however, requires explicitly calling the floatValue() method on the Float object:
float primitive_float = wrapper_float.floatValue();

If you are dealing with a lot of instances of wrappers and conversions, you will thus need to deal with a lot of method invocations. In J2SE 5.0, however, the code to create the wrapper object allows for this much simpler form:
Float wrapper_float = primitive_float;

297

Here, the "wrapping" is done automatically! There is no need to explicitly call the Float constructor. This "wrapping" is called "autoboxing" in the sense that the primitive value is automatically "boxed up" into the wrapper object. Autoboxing is available for all the primitive/wrapper types. Going the other way, from object type to primitive, is just as simple:
Integer wrapper_integer = 5; // primitive 5 autoboxed into an Integer int primitive_int = wrapper_integer; // automatic unboxing Integer into int

These shortcuts simplify coding and reduce errors in J2SE 5.0. For example, they can even be used in loop control and incrementing and decrementing operations.
int MAX = 100; // a primitive int type Integer counter = 1; // an Integer type Integer sum = 0; // ditto while (true) { sum += counter; if (counter == MAX) break; counter++; } System.out.println ("counter is now " + counter); System.out.println ("sum is now " + sum);

There is a lot of hidden autoboxing and unboxing going on in this simple-looking code. First, the Integer types counter and sum are autoboxed from the primitive values 1 and 0. Then, in the loop, they are unboxed to primitive values so the += operation can be applied and then reboxed to their "native" Integer types. To do the == comparison counter is unboxed so it can be compared with the int type MAX. If the break does not apply, then counter is unboxed, operated on with ++, and then reboxed. Autoboxing and unboxing work in a for loop as well:
Integer sum = 0; for (Integer counter=1; counter < MAX; counter++) { sum += counter; }

Note that both of these loops are likely to perform very slowly with all these autoboxing and unboxing operations. An optimizing compiler might be able to avoid some of the autoboxing and unboxing operations, but in general you should do long looping operations with primitive types unless there is a very good reason to use a wrapper type. Autoboxing and unboxing also work with Boolean and boolean types. For example,

298

it is conceivable that the int could be boxed into an Integer type and the second method1() used. switch now also accepts Byte.y). That might even be what you want to happen . ceil(x). int. the int is promoted to a long and the first method1() is used. max(x. toDegrees(x).y). the same behavior that applied in pre-5. But what happens if you call method1() with an int parameter? In J2SE 1. With the addition of autoboxing in 5.y). Similarly. While arguably reasonable. asin(x). that is not what happens. It cannot be subclassed as it is a final class. and Character types. round(x) IEEEremainder(x. cos(x). 12.0. Autoboxing and Overloading Autoboxing and unboxing can make method overloading interesting. With autoboxing. Short.3 Math class The Math class provides the important mathematical constants E and PI which are of type double. and do-while statements all expected boolean expressions. then the first method1() is used.0 versions must continue to hold. min(x.boolean one = true. Before 5.Math class abs 299 .4 and below. rint(x). for compatibility reasons. atan2(x.0. The reason is that existing code cannot suddenly start behaving differently when compiled and run under 5. There is nothing new there. All methods are of Math class are static. log(x). Integer. sqrt(x) abs(x). random(). short.4 and below. Through the use of unboxing. the if. The Math class cannot be instantiated as it has a private constructor.y). toRadians(x) Methods of java. // nothing new here Boolean two = true.0. tan(x) exp(x). floor(x).lang. The Math class also provides many useful math functions as methods. those flow control statements now also accept expressions that evaluate to Boolean types. the old switch statement expects a byte. // autoboxing of primitive 'true' to Boolean type if (one && two) // auto unboxing do_something (). pow(x. atan(x).it might make more sense to convert an int to an Integer than to promote it to a long. The general rule is. Consider the two overloaded methods shown here long method1 (long l) { return l+1. or char type in Java 1. } long method1 (Integer i) { return i+2. while. sin(x). } If you call method1() with a primitive long parameter.y). If you call method1() with an Integer object parameter. Group Transcendental Exponential Rounding Miscellaneous Methods acos(x). then the second method1() is used.

println(Math.floor(-. System.out.1) it will return a value of 2.0 NaN // counts up (towards zero) floor This method returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer.It strips off the sign of a number and returns it simply as a number. Thus the following will simply print out 99. System.NEGATIVE_INFINITY): Math.out.ceil(-0.println(Math.NaN): 10. System.abs(Integer.1) the result will be -1.out.59): Math.0): Math. Math.0 Infinity NaN If the value is equal to Integer. Here is a short program and its output public class MyMat{ public static void main(String[] argv){ System. If the argument is NaN or infinity.abs(1234.MIN_VALUE): -2147483648 ceil This method returns the next whole number up that is an integer.ceil(10): Math.1)). If you change that to ceil(-1.out.out.println(Math. 300 . in which case. Thus if you pass ceil(1.01): Math.abs(-99)).ceil( 9.floor(-99)). If the number is not negative you just get back the same number.NaN): 1234.ceil(-9. System.59 0.abs(-0.out.0. returns the argument Math.floor(-99.floor(99)).0 10.floor(0. it returns the value as a negative Math.abs(Float.03): Math.1)).ceil(Double.MIN_VALUE.01): // counts up (away from Math.println(Math.println(Math.0 zero) -9.0 -0.01)). System.abs(Float.println(Math.0.

min(Float.1)).max(-1.Float.out. negative or positive zero. System.min(1.out.5. } } Here is the output -1 2 1 -10 1 round public static long round(double a) public static int round(float a) 301 .println(Math.5): 1. returns the argument.out.min(-1.println(Math.0 0.max(1.5 Math.} } And the output is -100.5): -1.0 If the argument is an integer. System.max(-1.0. returns the argument.out.0 -1. If the argument is NaN. -0. 1.-10)).2)).0): -0.println(Math. 1. max and min min() returns the smallest of two values. System.out.println(Math.min(-1.println(Math.POSITIVE_INFINITY) : NaN The following code illustrates how these methods work public class MaxMin{ public static void main(String argv[]){ System. System. Math.0 99.5 Math.0 // zeros are not equivalent Math.NaN. infinity. max() returns the largest of two values.min(1.0 -99.-10)).2)).5.min(0.

rint(-5.rint( 5.0 5.MAX_VALUE is 3.5.POSITIVE_INFINITY): 9223372036854775807 Math.NEGATIVE_INFINITY): -2147483648 Math. If integers are equidistant.MAX_VALUE): 2147483647 (Float. System. returns the MAX_VALUE. Output: 1 -2 20 rint It rounds to the closest integer.0 If the argument is not a number.Rounds to the nearest integer.5): -1 Math.0 -6.5): Math.0 random Returns a random number between 0. Math. if the value is more than half way towards the higher integer.round(x)==3. if the argument is a negative infinity or less than the MIN_VALUE for the type. returns zero.5): Math.round(-2.01)).5 <= x < 3. If the value is Float.round(Double. 302 .out.println(Math.0 the Math.0 <= x < 2.0 -5.rint(-5.out.round(x)==2.MAX_VALUE Math.0.49): 6.1)).4028235E38) Here are some samples with output System.round(Float.MAX_VALUE the round method returns Integer.println(Math. So for example if the input to round is x then : 2.round(-1.0 2.49): Math.round(1. System.round(Float. If the argument is a positive infinity or greater than the MAX_VALUE for the type.rint( 5.NaN): 0 Math. So.println(Math. If the number is less than this the next lowest integer is returned.out.round(20)).5): 2 Math.round(Float. returns the MIN_VALUE.round( 1. the value is rounded up to the next integer. favours the even integer. then Math.0 and 1.

IEEEremainder(-7. The remainder operator.0 or 0.log(10): Math.0 Math. 2.5 : 2. It returns NaN if argument is negative Math.5 pow This method returns the first argument raised to the power of the second argument. The following code combines math code to produce a random number between 0 and 100.Unlike some random number system Java does not appear to offer the ability to pass a seed number to increase the randomness.pow(2. returns negative infinity. %.0 -2.0.log(-10): Math. System. Math.5): -0.0): 2.sqrt(45): Math. makes values symmetric around zero ie negative and positive values return corresponding remainders 7 % 2.println(Math.sqrt(-45): 6. If the argument is less than zero.round(Math.IEEEremainder keeps resulting values y units apart Math.IEEEremainder( 7.5 : -7 % 2.random()*100)).708203932499369 NaN IEEEremainder This method calculates the remainder as defined by IEEE-754. 2. returns positive infinity.0 log log() returns the natural logarithm of the argument.5 0.2) 4.302585092994046 NaN -Infinity exp 303 .out.log(0. Often a program will want to produce a random number between say 0 and 10 or 0 and 100. If the argument is -0. sqrt This method returns the positive square root of a number. If the argument is positive infinity.5): Math. Math. returns NaN.

76) is 874. System.out. returns positive zero.exp(5): Math.println("log(" + x + ") is " + Math.out.out.E).NEGATIVE_INFINITY): 148.println("The value of e is " + Math.println("sqrt(" + x + ") is " + Math.635.out. If the argument is positive infinity.log(x)).exp(Float. If the argument is negative infinity.4131591025766 NaN Infinity 0. } } Here's the output you'll see when you run ExponentialDemo: The value of e is 2.76.635) is 112984 log(11.45402 pow(11. 2.println("pow(" + x + ".exp(x)). System.out.NaN): Math. 304 .exp(Float. System.pow(x.635.sqrt(x)). Math. System.exp(Float.println("exp(" + x + ") is " + Math.71828 exp(11.0 An example program using Math class: public class ExponentialDemo { public static void main(String[] args) { double x = 11.008 sqrt(11. If the argument is NaN. returns positive infinity. double y = 2.exp() returns e to the power of the argument. " + y + ") is " + Math. System.635) is 3. returns NaN.41101 The trigonometric methods All results are returned in radians.POSITIVE_INFINITY): Math. y)).635) is 2.

returns -0. If the result is negative zero. returns -0.atan(90) 1. if the result is negative zero. Math. It returns a value between -PI/2 and PI/2. If the result is NaN or infinity. 305 . If the result is NaN or infinity. If the result is NaN.5707963267948966 Math. returns NaN. If the result is negative zero.0.0 Math.4480736161291701 double tan(double) Returns the tangent of the specified double value.sin(90) 0. If the result is NaN or absolute value is greater than 1.cos(90) -0.PI/2) 90. If the result is NaN or absolute value is greater than 1.tan(90) -1.asin(-0) 0. returns -0.0. a) to polar (r.toDegrees(Math. returns NaN.5596856728972892 double atan2(double) double toDegrees(double) double toRadians(double) Converts rectangular coordinates (b. returns -0.0 An example of using trigonometric functions public class TrigonometricDemo { public static void main(String[] args) { double degrees = 45.8939966636005579 double sin(double) double cos(double) Returns the cosine of the specified double value.0 double acos(double) Returns the arc cosine of the specified double value.0 Math.5707963267948966 double atan(double) Returns the arc tangent of the specified double value.Method Description Returns the sine of the specified double value. If the result is negative zero. returns NaN.acos(-0) 1. It returns a value between 0. Math. Math. If the result is NaN or infinity. Math. theta). returns NaN. Converts the argument to degrees or radians as indicated by the method name.0 Math. returns NaN. It returns a value between -PI/2 and PI/2. returns NaN.995200412208242 double asin(double) Returns the arc sine of the specified double value.toRadians(90) 1.0 and PI.

including information about the current user. key/value pairs.141592653589793 sine of 45.cos(radians))) + “degrees").out. System. len) The System class maintains a set of properties.toRadians(degrees).toDegrees(Math.out.PI). that define traits or attributes of the current working environment. System.println("The value of pi is " + Math. System.toDegrees(Math.println("The arc cosine of " + Math. As an example System. 306 . } } The output of this program is as follows: The The The The The The The value of pi is 3. the current version of the Java runtime.tan(radians)). and even the character used to separate components of a filename.0 is -0.570408475869457 12. srcpos.out.out.cos(radians)+ " is " + Math. dest[]. System. Some of the available methods are: currentTime() freeMemory() totalMemory() exit(int status) exec(String cmd) getOSName() arraycopy(src[].0 is NaN arc cosine of 45. the system properties are initialized to contain information about the runtime environment.3620448762608377 arc sine of 45.0 is -1.println("The arc tangent of” +Math. 1970).double radians = Math.out.tan(radians))) + " degrees"). System.out.asin(Math.out.atan(Math. destpos.sin(radians)).sin(radians))) + “degrees").toDegrees(Math.0 is 0.println("The cosine of " + degrees + " is " + Math.8060754911159176 cosine of 45. System.cos(radians)). in milliseconds counted from January 1.0 is NaN arc tangent of 45.4 System class The System class provides access to the native operating system's environment through the use of static methods.currentTimeMillis() retrieves the system clock setting (as a long.0 is 1.tan(radians) + " is " + Math.acos(Math.5918127259718502 tangent of 45.asin(radians) + " is " + Math. System. When the runtime system first starts up.println("The sine of " + degrees + " is " + Math.println("The tangent of " + degrees + " is " + Math.println("The arc sine of " + Math.

separator”).name").getProperty("user.vendor. You can use a key to look up one property in the properties list.out.println(name). to get the file separator character of the OS.home" "user. name = System.home" "java.version" "path.getProperty(“file. "/") Java classpath Java class version number Java installation directory Java vendor-specific string Java vendor URL Java version number Line separator Operating system architecture Operating system name Operating system version Path separator (for example.dir" "user. System. you can use the method System. ":") User's current working directory User home directory User account name Your Java programs can read or write system properties through several methods in the System class.url" "java.vendor" "java. } } 307 .Here is a complete list of the system properties you get when the runtime system first starts up and what they mean: Key "file.separator" "os.name" Meaning File separator (for example.version" "line.name" "os. For example.class.separator" "java.arch" "os.class.path" "java. or you can get the whole set of properties all at once. You can also change the set of system properties completely.version" "java. An example to get the user name : class UserNameTest { public static void main(String[] args) { String name.separator" "user.

// Get elapsed time in milliseconds long elapsedTimeMillis = System.exit(errorCode).read() reads a keystroke and returns an integer value. write and error operations. // Get elapsed time in seconds float elapsedTimeSec = elapsedTimeMillis/1000F. Once you obtain the reference to the current runtime you can call several methods that control the state and behavior of JVM. // Get elapsed time in minutes float elapsedTimeMin = elapsedTimeMillis/(60*1000F). // Get elapsed time in hours float elapsedTimeHour = elapsedTimeMillis/(60*60*1000F). // Get elapsed time in days float elapsedTimeDay = elapsedTimeMillis/(24*60*60*1000F).currentTimeMillis()-start. // Terminate System. System.println(string) displays a string to the current output device. To compute elapsed time // Get current time long start = System. // An error occurred errorCode = -1. System.5 Runtime class The Runtime class encapsulates the runtime environment. You can get the reference of the current Runtime object by calling the getRuntime() method.out..in.currentTimeMillis(). 12..The System class also provides very basic io streams for console read. 308 . Use of some methods of System class To terminate an application // No errors int errorCode = 0. // Do something . You cannot instantiate a Runtime object.

try { p = r. // Get current size of heap in bytes long heapSize = Runtime. // Get maximum size of heap in bytes. Process p = null. long heapMaxSize = Runtime.getRuntime(). class ExecDemoFini { public static void main(String args[]) { Runtime r = Runtime. The exitValue() returns the value returned by the subprocess when it is finished. p. } catch(Exception e) { System.exec(“notepad”). you can use the exec method of the Runtime object class ExecDemo { public static void main(String args[]) { Runtime r = Runtime. The waitFor() method causes your program to wait until the subprocess finishes.println(e).totalMemory().out. //The heap cannot grow beyond this size. try { p = r. long heapFreeSize = Runtime.getRuntime().exec(“notepad”).maxMemory(). Process p = null. //This size will increase // after garbage collection and decrease as new objects //are created.getRuntime(). } catch(Exception e) { System.exitValue()). } System. } } } The abstract class Process encapsulates a process. To execute an application. You can kill the subprocess created by the exec() method by destroy() method.println(e).Runtime can be used to get the size of the heap. The heap is the area in memory in which objects are created.freeMemory().out. 309 .waitFor().println(“Notepad returned :” +p. // Get amount of free memory within the heap in bytes.out. This is typically 0 if no problems occur.that is a program in execution. // Any attempt will result in an OutOfMemoryException.getRuntime().getRuntime().

The methods defined by Class are often useful in situations where runtime type information about an object is required.println(“x is the object of type:”+ clObj. clObj = clObj.} } 12.println(“y is the object of type:” +clObj. //get class reference System. and Short—to contain a number of primitive type.getSuperclass(). An example of using Class is as follows: class X { int a. you obtain a Class object by calling the getClass() method defined by Object. Float. System.getName()). Double. } class Y extends X { double c. 310 . } } The output of the program is as follows: x is object of type : X y is obtect of type : Y y’s superclass is X Summary You use an instance of one of the Number classes—Byte.getName()). when classes are loaded.out.out.getName()). Long. Integer.getClass(). Generally.println(“y’s superclass is :”+ clObj.getClass().out. float b. clObj = y. Class clObj = x. System.6 Class class Class encapsulates the run-time state of an object or interface. Objects of type Class are created automatically. You cannot explicitly declare a Class object. } class RTTI { public static void main(String args[]) { X x = new X(). Y y = new Y().

None of the above public static void main (String args[]) { System.print(Short.The Number classes include class methods and constants. Prints: -128. as well as basic arithmetic functions. and so on.MAX_VALUE)).out.toOctalString(Byte. } 311 . for generating random numbers.32768 b. Run-time error g. Run-time error g."). Prints: 0. shortValue.toHexString(Byte. and similar methods convert one numeric type to another. such as computing sine. random.65536 e.MAX_VALUE)+".255 b. This class includes the trigonometric functions.256 c. The MIN_VALUE and MAX_VALUE constants contain the smallest and largest values that can be contained by an object of that type. Prints: 0.").MAX_VALUE).toString(Byte.MAX_VALUE)+". System.128 2. System. class JJF2 { d.").MIN_VALUE+".print(Byte. such as rounding. None of the above public static void main(String args[]) { System.print(Short.out.out. Questions 1.print(Integer.out. cosine. Prints: 0. which are useful in a variety of ways. Math contains a method. } } What is the result of attempting to compile and run the program? a.out. Finally. class JJF3 { d.32767 c.out.127 e.").print(Integer. The Math class contains a variety of class methods for performing mathematical functions.out.MAX_VALUE)."). Prints: -32768.print(Integer. System. Compile-time error f.print(Byte. The valueOf method converts a string to a number.MAX_VALUE)+". The byteValue. Prints: -127. } } What is the result of attempting to compile and run the program? a.toBinaryString(Byte.out. System. System. Compile-time error f. Prints: -32767.MIN_VALUE+". and the toString method converts a number to a string.65535 3. Prints: 0. class JJF1 { public static void main (String args[]) { System.print(Integer. Math also includes functions for logarithm calculations.

ff.print(Integer.toHexString(Byte. c. Run-time error i.256. Compile-time error h.MAX_VALUE)+".} What is the result of attempting to compile and run the program? a. Compile-time error h.ffff b.7fff 5. Run-time error e. // 1 Cloneable c = i.out. Prints: 7f.80000000 f.ffffff.toHexString(Integer. Prints: 7fff. class JJF4 { d. Prints: 7fff.7fff e. None of the above public static void main(String args[]) { System.print(Long.MAX_VALUE)).127.7f b. System. Compile-time error 4. Prints: 00000000.toHexString(Integer. // 2 i = (int [])c.7f b.MAX_VALUE)+".print(Long.MIN_VALUE)+".377.out.toHexString(Short. class Green { d. Prints: ff. System.ffffff. Prints: 11111111.print(Long.177."). Prints: 8000. None of the above public static void main(String args[]) { System.ff. Prints: 1111111. Run-time error at line 2. Compile-time error at line 2.ffff. Run-time error i.ffffffff c.").ffffff g.out. Prints: 7fffffff. Prints: 0000. Prints: f.8000 6. d.7fffff f.ff c.print(Integer. }} What is the result of attempting to compile and run the program? a.7fffffff g."). Prints: ffff. System. None of the above public static void main (String args[]) { int[] i = null.MAX_VALUE)). Prints: 80000000.ffff. class JJF5 { d. } } What is the result of attempting to compile and run the program? a. 312 .out. Prints: f. b.ffff e.out. // 3 } } What is the result of attempting to compile and run the program? a.ff c. Compile-time error at line 1.toHexString(Character. Run-time error at line 1.

class EBH011 { g."+(c == c)+". Prints: true.true. b.true.true. None of the above } public static void main (String[] args) { float a = Float.out.e. None of the above 313 . Prints: false. Compile-time error at line 3.true i. } What is the result of attempting to compile and run the program? a.POSITIVE_INFINITY.false Prints: true. Run-time error j. System.true Prints: false.false.true Prints: true. c. Run-time error at line 3.false.false Prints: false. Compile-time error k. h.NaN.POSITIVE_INFINITY. double c = Double. g.true e. f.true. double b = Double.false Prints: true.false Prints: false. f.false.print((a == b)+".false."+(c != c)). d. 7.

Vector extends AbstractList and implements the List interface of the Collections Framework. and the values in a hashtable. 13. There are five legacy classes in Java – Vector. Enumerations are also used to specify the input streams to a SequenceInputStream. Successive calls to the nextElement method return successive elements of the series. but with two differences: Vector is synchronized and it contains many legacy methods that are not part of the collections framework. public abstract Object nextElement() Returns the next element of this enumeration. which has an initial size of 10. int incr) Vector(Collection c) The first form creates a default vector. The fourth form creates a vector that contains the elements of Collection c. Methods of Enumeration interface public abstract boolean hasMoreElements() Tests if this enumeration contains more elements. Here are Vector constructors: Vector() Vector(int size) Vector(int size.util package. 13. the keys of a hashtable. 314 . Properties. The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. It is similar to the ArrayList in the Collection Framework. The increment specifies the number of elements to allocate each time that a vector is resized upward. one at a time. false otherwise. Stack.2 Vector class The Vector class provides the capability to implement a growable array of objects. Hashtable and Dictionary. Throws NoSuchElementException if no more element exists. There is one legacy interface called Enumeration.1 Enumeration interface An object that implements the Enumeration interface generates a series of elements. The second form creates a vector whose initial capacity is specified by size.Chapter 13 : Utility & Legacy classes These classes are a part of java. Returns true if this enumeration contains more elements. Methods are provided to enumerate through the elements of a vector.

You can obtain the index of an element using indexOf() and lastIndexOf(). v.println(“Current capacity:”+v.addElement(new Integer(2)). import java.out.All vectors start with an initial capacity.addElement(new Integer(7)). After the initial capacity is reached the next time that you attempt to store an object in the vector. v.addElement(new Integer(3)). v.println(“First element:”+ (Integer)v. The number of elements currently in the vector is stored in elementCount. the vector automatically allocates space for that object plus extra room for additional objects.println(“Current capacity:”+v.4)). The following program uses a Vector to store various types of numeric objects.out. If you don’t specify an increment. v. the vector’s size is doubled by each allocation cycle.addElement(new Integer(1)).size()).addElement(new Double(5. class VectorDemo { public static void main(String args[]) { //initial size is 3.08)). The array that holds the vector is stored in elementData. 315 . Object elementData[]. It demonstrates several of the legacy methods defined by Vector.out. System. v. To obtain the first element in the vector call firstElement(). To retrieve the last element.out.capacity()). v. Vector defines these protected data members: int capacityIncrement.addElement(new Integer(4)).addElement(new Integer(11)). System. System.println(“Initial size :” + v. v. The increment value is stored in capacityIncrement.util.45)). v. This reduction is important. v.out. call lastElement(). To obtain the element at a specific location call elementAt().addElement(new Double(6.capacity()).capapcity()). System. because allocations are costly in terms of time. You can add an element to the Vector by calling addElement(). System.println(“Initial capacity :”+v. System. To remove an element.firstElement()). v.println(“Current capacity:”+v. The amount of extra space allocated during each reallocation is determined by the increment that you specify when you create the vector.*. System. v.out.addElement(new Integer(10)).out. int elementCount. By allocating more than just the required memory. the vector reduces the number of allocations that must take place.capapcity()). It also demonstrates the Enumeration interface. increment is 2 Vector v = new Vector().addElement(new Integer(12)).addElement(new Double(9.capapcity()). call removeElementAt().println(“Capacity after 4 additions :” + v.

out.System. while(vEnum.elements().contains(new Integer(3)) { System.08 7 9.hasMoreElements()) { System.3 Stack class Java's Stack class extends the Vector class. inspection of it's top most element. Object peek() Looks at the object at the top of this stack without removing it from the stack.println(“\nElements in vector:”).out. The output of this program is shown here: Initial size: 0 Initial capacity : 0 Capacity after 4 additions: 5 Current Capacity: 5 Current Capacity: 7 Current Capacity: 9 First element: 1 Last element: 12 Vector contains: 3 Elements in vector: 1 2 3 4 5.println(“Vector contains 3”).print(vEnum. 316 .println(). Object pop() Removes the object at the top of this stack and returns that object as the value of this function. and the addition of elements.45 6. Some of the methods of Stack are shown below: boolean empty() Tests if this stack is empty.println(“Last element:”+ (Integer)v.4 10 11 12 13. System. A Stack represents a Collection of objects that are in LIFO (Last In First Out Order). } } ”).out. if(v.nextElement() + “ } System. removal of it's top most element.out. } //enumerate the elements in the vector Enumeration vEnum = v.out. Object push(Object item) Pushes an item onto the top of this stack.lastElement()). The Stack class provides operations that allow testing for zero elements.

System. int a) { st.push(new Integer(a)). class StackDemo { static void showpush(Stack st. showpop(st).println(“stack :” +st).println(“stack : ”+st). showpop(st).out. System.println(“pop -> ”).out.println(“stack :” + st). System. 42).out.out.println(“push (”+a+ “)”).out. 99).println(“Empty Stack”). 99] pop -> 99 stack : [42.int search(Object o) Returns the 1-based position where an object is on this stack. } static void showpop(Stack st) { System.util.println(a). 66. } catch(EmptyStackException e) { System. 66] pop -> 66 stack : [42] 317 . 66).out. } public static void main(String args[]) { Stack st = new Stack().pop(). An example of using Stack import java. Integer a = (Integer) st. 66] push (99) stack : [42. } } } The following the output produced by the program stack : [ ] push (42) stack : [42] push (66) stack : [42. showpush(st.out.*. System. showpush(st. System. showpush(st. try { showpop(st). showpop(st).

the hash table is expanded. To add a key and a value.5 Hashtable class A hash table is conceptually a contiguous section of memory with a number of addressable elements. The Dictionary class defines some abstract methods. Hashtable is the class which provides hash tables in Java. If you do not specify a fill ratio.0 and 1. Hashtable inherits directly from Dictionary and implements the Map. The second version creates a hash table that has an initial space specified by size. You can use the remove() method to delete a key/value pair.75 is used. when the number of elements is greater than the capacity of hashtable multiplied by its fill ratio.pop -> 42 stack : [ ] pop -> empty stack 13. A hash table can only store objects that override the hashCode() and equals() methods that are defined by the Object. The default load factor of 0. Finally. the put() method is used. Once the value is stored. The keys and values can each be returned as an Enumeration by the keys() and elements() methods. Hash tables are a common means of organising data.4 Dictionary class The Dictionary class is an abstract class. respectively. Cloneable and Serializable interfaces. The capacity of the hash table is set to twice the number of elements in m.0. The size() method returns the number of key/value pairs stored in a dictionary and isEmpty() returns true when the dictionary is empty. so the designers of the Java programming language have provided a number of classes for easily creating and manipulating instances of hash tables. you can store the value in a Dictionary object. This ratio must be between 0. Use get() to retrieve the value of a given key. the fourth version creates a hash table that is initialized with elements in m. but they provide very fast lookup times. you can retrieve it by using its key. and it determines how full the hash table can be before it is resized upward. 318 . Any object can be used as a key and/or value. The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. Given a key and value.75 is used. in which data can be quickly inserted. which maps keys to values. float fillRatio) Hashtable(Map m) The first version is the default constructor. Dictionary is classified as obsolete. Specifically. Hash tables represent a sacrifice of memory for the sake of speed . The Hashtable constructors are shown below: Hashtable() Hashtable(int size) Hashtable(int size. 13. then 0. because it is superceded by Map in the Collections Framework.they are certainly not the most memory efficient means of storing data. deleted and found.

out. balance.22)).000 into Jane Doe’s account bal = (Double)balance.get(“John Doe”)). new Double(-19.get(“John Doe”) balance.22)).new Double(bal + 1000)).put(“Todd Hall”. Properties defines the following instance variables: Properties default.getProperties() when obtaining environmental values. System. System.08)).get(str)). String str.put(“Tom Smith”. new Double(3434.println(“John Doe’s new balance :” + balance. balance.hasMoreElements()) { str = (String)names. balance. An example of using Hashtable import java. The Properties class is used by many other Java classes.println(str + “ : ” + balance. while(names. It is used to maintain lists of values in which the key is a String and the value is also a String.put(“Jane Baker”. } } 13. double bal.util. For example.out. balance.nextElement().rehash(). new Double(1378.println(). //Show all balances in hash table Enumeration names = balance. } System. class HTDemo { public static void main(String args[]){ Hashtable balance = new Hashtable().6 Properties class Properties is a subclass of Hashtable.If you want to allocate more space for your hash table before the load factor reaches the specified value then use the rehash() method like this: ht. 319 . new Double(123. it is the type of object returned by System.put(“John Doe”.out. new Double(99. //Deposit 1.put(“Ralph Smith”.keys(). balance.34)).put(“John Doe”.*.00)).

props.html"). It will write the properties to the output stream. When you construct a Properties object. "C:\temp\work. 320 .setProperty("maxLevel". The second creates an object that uses propDefault for its default values. Methods Object setProperty(String key. To store a Properties table in a file Use the Properties store(OutputStream.store(propOut. Properties defines these constructors Properties () Properties (Properties propDefault) The first version creates a Properties object that has no default values. This allows for arbitrary nesting of levels of default properties. Assuming you have variables and an OutputStream like: OutputStream propOut = new FileOutputStream( new File("props. "true"). For example. then “default value” is returned. and “foo”. "*. String header) To create and put values in a Properties table This example creates a new Properties table and assigns a string value to four different keys. props. String value) String getProperty(String key) String getProperty(String key. One useful capability of Properties class is that you can specify a default property that will be returned if no value is associated with a certain key. “default value”). props. props. If the “name” value is not found. In both cases the property list is empty. String) method. if you call getProperty(“foo”) on a given Properties object. does not exist.setProperty("recursiveSearch". String defaultValue) Enumeration propertyNames() void load(InputStream in) void store(OutputStream out. "7"). Properties props = new Properties().$$$"). a default value can be specified along with the key in the getProperty() method – such as getProperty(“name”.This variable holds a default property list associated with a Properties object. you can pass another instance of Properties to be used as the default properties for the new instance.setProperty("fileName". props. with a header line from the String parameter. In this case. Java looks for “foo” in the default Properties object. "Macro Processor Properties").stat")).setProperty("noCopyPattern".

and any class that implements the new Appendable interface. props. 13.. For example.setProperty("sourceFile". defaultProps. args) The args parameters will be displayed in the output according to the specifiers in the format string in the first parameter. To use default properties Create a Properties table with all of the default key/value pairs.5.parseInt(props. Properties defaultProps = new Properties().Formatter class includes the method format (String format. 321 . Destinations include OutputStream.To load Properties from a file Use the Properties load(InputStream). It depends heavily on the varargs feature being introduced in 1. boolean recursiveSearch = Boolean.Formatter that allows you to do string formatting similar to the printf function in C. int maxLevel = Integer.getProperty("recursiveSearch")).. each of which includes a parameter for the destination of the formatted output. "false"). The program FormatWriteApp shows how we can use Formatter to send formatted numerical values to the console rather than using the printf() method.5 introduces a new class named java. For example.util.getProperty("noCopyPattern"). The java. Use this default table in the constructor for your regular properties table: Properties props = new Properties(defaultProps).load(propsIn). Here propsIn is the input stream. String noCopyPattern = props.serProperty("enableScrolling".getProperty("maxLevel").util.getBoolean(props. Object. an instance of File.Formatter class provides several constructors. defaultProps. You will probably want to get each property value and assign it to an internal variable and perhaps show it in the user interface.util. method. The java. "").7 Formatter class Java 1.

import java. ("boolean ("byte ("short ("int ("long ("float ("double = = = = = = = %9b %n". %9d %n".*. /** * Demonstrate the java.*. } // main } // class FormatWriteApp The output of this program look like: Text output with Formatter.format formatter.format formatter. a_double). %9d %n". a_float).out).out stream.io. formatter. Primitives converted to strings: boolean = false byte = 114 short = 1211 int = 1234567 long = 987654321 322 .format // Need to flush the data out of the buffer. = 1234567. formatter. = 114. %9d %n".Formatter capabilities for * formatting primitive types.6f. **/ public class FormatWriteApp { public static void main (String arg[]) { // Send formatted output to the System.format formatter.2e %n".flush ().3f %n". an_int). %n"). = 1211. boolean byte short int long float double a_boolean a_byte a_short an_int a_long a_float a_double = false. Formatter formatter = new Formatter ((OutputStream)System.import java.format formatter. %9.format formatter. formatter. a_short).297e-15. = -4. %9. = 987654321. formatter.format ("Text output with Formatter. %9d %n".format ("Primitives converted to strings: %n").format formatter. a_byte).close ().util. a_long).util. a_boolean). = 983. formatter.

println(date. You can return the number of milliseconds in the Date as a long. 1970. January 1. For example. pass the number of milliseconds since midnight. the System.getTime()).30e-15 In the Formatter constructor.Date. Let’s look at a simple example of creating a date using the system clock’s current date and time and returning a long value. and you can access the string that it creates via the toString() method. Greenwich Meantime to the constructor. System. The second constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight. you might do this Date d1 = new Date().out. You can directly obtain the formatted string created by the Formatter by invoking the toString() method. 323 . import java. Also. to time a block of code.600 = -4. 13. 1970. like this: Date midnight_jan2_1970 = new Date(24L*60L*60L*1000L).out argument. } } To create a Date object for a specific time.8 Date class The Date class encapsulates the current date and time. must be cast to OutputStream because otherwise there is an ambiguity over which constructor to use. using the getTime() method. Date do not allow you to obtain the individual components of date or time. you can create a Formatter with the no-argument constructor. public class DateExample1 { public static void main(String[] args) { // Get the system date/time Date date = new Date(). and don't want to send it to an output destination. such as for a graphical text component. This is often referred to as the system time of the host environment of the Java Virtual Machine (JVM). if you simply want a formatted string. which references an instance of PrintStream. January 1.util. Date class has two constructors Date() Date(long milliseconds) The first constructor initializes the object with the current date and time. The Formatter uses internally a StringBuilder.float double = 983.

to the setTime() method. GMT. The Calendar class represents a point in time (a "Date").JANUARY ) {. like this: Date midnight_jan2_1970 = new Date(). Rather than offering a number of dedicated property getters and setters (such as getMonth()). January 1. (These identifiers are raw integers.get( Calendar.MONTH ) == Calendar.) Besides the identifiers (or keys) for the fields. Greenwich Mean Time.setTime(24L*60L*60L*1000L). hours. interpreted appropriately for some locale and time zone. You can change a Date by passing the new date as a number of milliseconds since midnight. 1970.before(new Date())) { The after() method returns true if this Date is after the Date argument.d1. one would write code like this: if( calendar. January 1. The Calendar class follows an unusual idiom for allowing access to the individual fields of the interpreted date instance. to test whether a certain date (represented by the Calendar instance calendar) falls into the first month of the year.getTime() .. false if it's not. So.} 324 . For example if (midnight_jan2_1970.out. System. false if it's not. and seconds according to the local calendar.println("That took " + elapsed_time + milliseconds"). (that is a Date object). long elapsed_time = d2. which takes an identifier for the requested field as argument: int get( Calendar. 1970.// timed code goes here Date d2 = new Date(). not wrapped into an enumeration abstraction. the Calendar class defines a number of additional public static final variables holding the values for the fields.MONTH ) The identifiers for the fields are defined in the Calendar class as public static final variables. Each Calendar instance wraps a long variable containing the number of milliseconds since the epoch for the represented point in time.. The before() method returns true if this Date is before the Date argument. For example if (midnight_jan2_1970. midnight_jan2_1970.after(new Date())) { 13.getTime(). it offers only one. into days. minutes.9 Calendar class The abstract class Calendar converts a time in milliseconds since midnight.

get(Calendar. 325 . Also there are some more like GregorianCalendar (int year.getInstance().MINUTE)+”/”+ c..util.SECOND.YEAR)). It provides an implementation of the basic Calendar abstraction suitable for the interpretation of dates according to the conventions used commonly in the West. The default. initializes the object with the current date and time in the default locale and timezone. It adds a number of public constructors. MONTH_2.get(Calendar.out.print(“Updated Time:”). int month. class CalendarDemo { public static void main(String args[ ]) { //Create a calendar initialized with the current date // and time in the default locale and timezone Calendar c = Calendar.SECOND)).set(Calendar. There are several constructors of GregorianCalendar class. representing the 13th month of the year.println(c. int month.SECOND)).print(“Date :”). as well as some functions specific to Gregorian Calendars. irrespective of location (as opposed to more neutral names such as MONTH_1.10 GregorianCalendar class The class GregorianCalendar is the only commonly available subclass of Calendar. System.get(Calendar. int month.*. //set the time and print it c.HOUR. boolean isLeapYear(int year) The getInstance() method of Calendar returns a GregorianCalendar object. c. and so on).get(Calendar. FEBRUARY. System.get(Calendar. System.get(Calendar.get(Calendar.out. which is required by some (nonGregorian) calendars.MINUTE)+”/”+ c.set(Calendar. such as isLeapYear(). c. System. int dayOfMonth) GregorianCalendar (int year. int dayOfMonth.get(Calendar.println(c. } } 13. There is also a field UNDECIMBER.HOUR)+”/”+ c. An example using Calendar class import java.out. etc.HOUR)+”/”+ c. int hours.print(“Time:”).set(Calendar.10).out. System.out. int minutes) GregorianCalendar (int year. System.get(Calendar.MONTH)+1)+”/”+ c. int dayOfMonth.DATE)+”/”+ (c.println(c.Note that the months are called JANUARY.00).00).out.MINUTE.

System.util. Locale locale) Example import java. Semantically. You can also construct a GregorianCalendar object by specifying either the locale and/or timezone.println(gc.MONTH)+ ”/”+ gc.get(Calendar. in order to calculate the local time for any given date and time.int hours. with zero indicating January. but implementation of any functionality 326 .out.out.YEAR)). The month is specified by month.println(gc.println(“Current year is not a Leap year”). Here year specifies the number of years that have elapsed since 1900.get(Calendar. System.11 TimeZone and SimpleTimeZone classes The TimeZone class and its subclasses are auxiliary classes.print(“Date :”).SECOND)). } } } 13. The first version sets the time of midnight.HOUR)+”/”+ gc.println(“Current year is Leap year”). The TimeZone abstraction therefore needs to keep track not only of the additional offset to be applied if DST is in effect. Clearly.*.out.print(“Time:”). a time zone specifies a certain offset to be added to Greenwich Mean Time (GMT) also referred to as Coordinated Universal Time (UTC) to reach the local time.out. The second version also sets the hours and the minutes. int minutes. required by Calendar to interpret dates according to the selected time zone.MINUTE)+”/”+ gc.get(Calendar.get(Calendar. The third version adds seconds.get(Calendar. class GregorianCalendarDemo { public static void main(String args[]){ GregorianCalendar gc = new GregorianCalendar().get(Calendar. GregorianCalendar (Locale locale) GregorianCalendar (TimeZone timezone) GregorianCalendar (TimeZone timezone. but also of the rules that determine when DST is in effect. The following constructors create objects initialized with the current date and time using the specified time zone and/or locale.YEAR))) { System. The abstract base class TimeZone provides basic methods to handle "raw" (without taking DST into account) and actual offsets (in milliseconds!).out. System. this offset changes when daylight saving time (DST) is in effect. int seconds) All three versions set the day.get(Calendar. System.DATE)+”/”+ gc. } else { System. if(gc.out. month and year.isLeapYear(gc.

23 An example to list all timezones Date today = new Date()..getAvailableIDs().HOUR_OF_DAY). i++) { // Get time zone by time zone id TimeZone tz = TimeZone. // Get all time zone ids String[] zoneIds = TimeZone.setTimeZone(TimeZone.MINUTE). The latter class provides several ways to specify rules controlling the beginning and ending of DST.HOUR_OF_DAY). Each TimeZone also has a human-readable. // 0.HOUR).getDefault()).LONG).SECOND).get(Calendar. Also provided are static factory methods.23 // Get the current local hour-of-day cal.related to DST rules is left to subclasses. Display names come in two styles: LONG and SHORT.setTimeZone(TimeZone. // 0. surprisingly for an abstract class.get(Calendar. The base class provides the static method String[] getAvailableIDs() to obtain all installed "well-known" standard time zones. TimeZone. hour24 = cal. // 0.. so does TimeZone.. such as a giving an explicit day in a month or a certain weekday following a given date. locale-dependent display name.AM.59 int seconds = cal..getTimeZone(zoneIds[i]).inDaylightTime(today). int hour24 = cal.getDisplayName(tz. // Get the current hour-of-day at GMT cal.11 int minutes = cal.getTimeZone("GMT")).. An example of using TimeZone // Get the current time in Hong Kong Calendar cal = new GregorianCalendar(TimeZone.SHORT). i<zoneIds.get(Calendar. String longName = tz.get(Calendar. such as SimpleTimeZone. TimeZone. // Get the display name String shortName = tz. SimpleTimeZone also provides some public constructors and.getTimeZone("Hongkong")).AM_PM) == Calendar.getDisplayName(tz. Time zones are unambiguously determined by an identifier string.length. // View every time zone for (int i=0. // 0. // 0. to obtain TimeZone instances — either for a specific ID or the default for the current location.59 boolean am = cal. int hour12 = cal. 327 .get(Calendar.inDaylightTime(today).get(Calendar.

Language names are two letter ISO-639 language codes and country names are two letter ISO-3166 country codes. a system wide default locale is available for programs that do not wish to manage locales explicitly. it would use the French localization instead. but was localized for the French language in general. "").// Get the number of hours from GMT int rawOffset = tz. It is not a collection of locale-specific attributes. int hour = rawOffset / (60*60*1000).12 Locale class In Java. With this design."GB"). If the object has not been localized for a particular locale.abs(rawOffset / (60*1000)) % 60.inDaylightTime(today). Both use the standard localization mechanism. it will try to find a "close" match with a locale for which it has been localized. // A locale for the French language Locale french = new Locale("fr". While a global locale is not enforced. It is up to the object accepting the locale to do the right thing. } 13. there is no difference in how user and system objects maintain their locale-specific resources. This naming scheme is not enforced by class Locale but is rather a convention used by all Java's International classes. A default locale also makes it possible to affect the behavior of the entire presentation with a single choice. All locale-sensitive operations may be explicitly given a locale as an argument. int min = Math.useDaylightTime(). Java programs are not assigned a single global locale. Thus if a Calendar object was not localized for French Canada. an empty country string is given to the Locale constructor to signify a locale for the entire French language. Instead. Locale objects are generally created from a language name and a county name as follows: // A locale for Great Britain Locale greatBritain = new Locale("en".getRawOffset(). In the second case above. each locale-sensitive class maintains its own locale-specific information. a French Canadian locale passed to a Calendar object asks that the Calendar behave correctly for the customs of Quebec. 328 . // Is the time zone currently in a daylight savings time? boolean inDST = tz. Java locales act as requests for certain behavior from another object. This greatly simplifies multilingual programs. For example. // Does the time zone have a daylight savings time //period? boolean hasDST = tz. a locale is simply an identifier for a particular combination of language and region.

the result is in tokens hello. Locale supports a number of methods to provide user readable names for the locale and its country. Today. Today.. String nameUS = japan. These names can also be localized: Locale. When the string "hello. This allows multiple locales to be created for a single language and country combination. java.util.getDisplayLanguage(new Locale("fr". but if bReturnTokens is set to true. the first call to getDisplayLanguage() returns the language of the locale japan. am.getDisplayLanguage(). 329 . going. "US") ). "JP"). StringTokenizer(String sInput. String sDelimiter.Breaks on white space (" ". Today \"I am \" going to my home town" is tokenized on white space. StringTokenizer(String sInput. "I. going. the following specifies the Locale object for Great Britain and can be used in place of new Locale("en". localized for the default locale. "\t". In the above example. ".Breaks on sDelimiter. "\n").StringTokenizer is used to break Java String's into smaller components. Locale contains a static getter and setter method for accessing the system's default locale. the default locale is automatically set by the Java runtime to match the host's current locale." The second call to getDisplayLanguage() returns the language of the locale japan. called tokens. instead of hello. As an example..In addition. "I am ". String nameFR = japan. language and variant fields."GB"): Locale.Breaks on sDelimiter."FR")).13 StringTokenizer class When working with any general-purpose programming language. the Locale class contains a number of handy constants for creating Locale objects for commonly used languages and countries. You can create a StringTokenizer by using any one of the following three constructors: StringTokenizer(String sInput) ." 13. localized for the given locale. At start-up time. Locale japan = new Locale("ja". this feature could be used to create an "FR_FR_HOST" locale which would match the host's behavior for France rather than Java's portable behavior for France. For example. it's often necessary to break a large string into smaller components. Thus nameUS would be "Japanese. If this is not possible. then the delimiter is also returned as a token. String sDelimiter) .setDefault( new Locale("en". The first constructor doesn't check whether the input string contains substrings.UK A Locale may also be created with an optional variant name. Thus nameFR would be "japonais. boolean bReturnTokens) . the en_US locale is used.

When the string "book. tabs. the println statement is skipped and the while loop is exited. ".". The third constructor won't work if a token itself is equal (in length and value) to the delimiter and is in a substring. "". and date published. publication. where "" means string of length 0. suppose this sentence is stored in a variable named speech. and the resulting output from this snippet of code looks like this: Four score and seven years ago The while loop test checks to see if there are any tokens left in the st object. ".\". publication. the variable speech is passed into the StringTokenizer constructor method. the StringTokenizer returns four tokens with values book. author..hasMoreTokens()) { println(st. To get six. author. . "". As long as there are. author. and date published instead of the six values book.nextToken()).date published" is tokenized (this string contains . Therefore. and carriage-return characters). like this: String speech = "Four score and seven years ago". the result is book. For our purposes.. Once there are no tokens remaining. you must set the StringTokenizer's bReturnTokens parameter to true. StringTokenizer st = new StringTokenizer(speech). Because StringTokenizer is not given a field separator value as an input parameter. When the string "book. author. date published (with five tokens). and assumes that fields within the string are separated by whitespace characters (spaces.The second constructor doesn't check the consecutive appearance of delimiters.. each time through the while loop a word is printed on a separate line. A simple snippet of code to break that sentence into individual words using Java's StringTokenizer class would look like this: String speech = "Four score and seven years ago". date published (with six tokens) instead of book.\". author. The feature of setting the parameter to true is important as it gives an idea about the presence of consecutive delimiters. while (st. 330 . publication. as a token. it uses it's default field separator. } In this example.date published" is tokenized on ". the println statement is executed. which is the same as its delimiter) on string . author. (the comma character). publication. publication. publication. One of the most famous sentences in American history begins with the words "Four score and seven years ago".

} void dbTest() { DataInputStream dis = null.txt. each field is separated by a colon character.println("Last Name: " + lname). dis = new DataInputStream(bis).println("City: " + city). including their first name. BufferedInputStream bis = new BufferedInputStream(fis).io.out. ":"). System.nextToken(). String fname = st. it's a simple matter to break the record into it's four fields using the nextToken() method of the StringTokenizer class.nextToken(). } } 331 . Homer:Simpson:Springfield:??? Hank:Hill:Arlen:Texas Because we know that the fields of each record are separated by the colon character.*. System.readLine()) != null) { StringTokenizer st = new StringTokenizer(dbRecord. import java. ":"). Each record contains information about a customer. // read the first record of the database while ( (dbRecord = dis. class TokenTest { public static void main (String[] args) { TokenTest tt = new TokenTest(). It shows how to break a record (separated by colon characters) into tokens typically called "fields". and the city and state of their address. tt. After that. Within a record.out. The following two records are from a hypothetical customer file named customer.In this example a text file is used. String city = st. like this: StringTokenizer st = new StringTokenizer(dbRecord.txt").nextToken().println("First Name: " + fname). String dbRecord = null. String lname = st.out. import java. String state = st.*.println("State: " + state + "\n"). try { File f = new File("customer. last name. we specify that the colon character should be the field delimiter (or field separator) when we call the StringTokenizer constructor.nextToken().util.out.dbTest(). System. System. FileInputStream fis = new FileInputStream(f).

These are:    Whitespace characters -. The StreamTokenizer class can recognize various comment styles of programming languages.println("IOException error trying to close the file: " + e. } finally { // if the file opened okay. make sure we close it if (dis != null) { try { dis. TT_EOL.getMessage()).out.catch (IOException e) { // catch io errors from FileInputStream or readLine() System. you might look at the StreamTokenizer class instead.14 StreamTokenizer class As the name of the class suggests.their lexical significance is limited to separating words Word characters -. characters are assigned one of three categories. In the implementation of this class. and the scanner uses the significance of the current character to decide what to do. got an IOException error: " + e. TT_Number and Word. 332 .*. Like the StringTokenizer.close(). } } // end if } // end finally } // end dbTest } // end class The simple method we've shown here is a powerful way of breaking a String into tokens.println("Uh oh. but that is where the similarity ends. Note also that we do not need to know how big the file is in advance in this case.io.they should be aggregated when they are adjacent to another word character Ordinary characters -. import java. a StreamTokenizer object expects its input to come from an InputStream class. } catch (IOException ioe) { System.getMessage()).they should be returned immediately to the parser Having created an instance of the class streamTokenizer we can use the nextToken method to read tokens from the input stream.out. and offers a number of control flags that can be set to various states. this class converts the input stream into chunks that your parsing code can interpret. This means that every possible input character is assigned a significance. we simply test the current token's type agaist the class integer constant TT_EOF (this has a value of -1). If you need a more powerful tokenizer. There a four possible predefined types of token: TT_EOF. 13. StreamTokenizer is a table-driven lexical analyzer.

java").inputStream).TT_NUMBER: System.println("TT_WORD: sval = " + inStream. default: System.out.nextToken().TT_EOF: System. int tokenType = 0. } while (tokenType != StreamTokenizer. break.println("TT_EOL"). break. case StreamTokenizer.sval).println("Unknown: nval = " + inStream.TT_EOF). outputTtype(tokenType. // Process the file and output the number of tokens in the file do { tokenType = inputStream. */ Method to output the ttype of a stream token and private static void outputTtype(int ttype. case StreamTokenizer.import java. StreamTokenizer inputStream = new StreamTokenizer(file).out.println("TT_NUMBER: nval = " + inStream. class TokenizerExample5 { public static void main(String[] args) throws IOException { FileReader file = new FileReader("HelloWorld.out. numberOfTokens++. StreamTokenizer inStream) { switch (ttype) { case StreamTokenizer.nval).out. int numberOfTokens = -1.sval).out.TT_WORD: System. 333 .println("TT_EOF"). } /* OUTPUT TTYPE: its value.TT_EOL: System. break.*. case StreamTokenizer. break.util.out.nval +" sval = " + inStream. // Output result and close file System.println("Number of tokens = " + numberOfTokens).

0 Returns random double (true or false) Returns random number with mean 0. static Random randGen = new Random(). except nextGaussian(). // For reproducible testing Random methods The most common methods are those which return a random number.0 and standard deviation 1. it's necessary to add 1 to scale the number into the range 1-6.0 Returns random double >=0.nextBoolean() double d = r.0 Example: Generating a number from 1 to 6 Because nextInt(6) returns a number from 0-5.nextFloat() double d = r.} } } break. //Default seed comes from system time. In these examples. 334 .nextLong() float f = r.nextDouble() boolean b = r.nextInt(int n) int i = r. Random constructors Random r = new Random().0 and < 1. These methods return a uniform distribution of values. x is a Random object.util.Random. To use the Random class create an object of this class (giving a seed to the constructor if you wish).nextInt() long l = r. int spots = randGen.0 and < 1. Random r = new Random(long seed).nextGaussian() Returns random int >= 0 and < n Returns random int (full range) Returns random long (full range) Returns random float >= 0.random() method and Random class. public class RandomNumber { public static void main(String[] args) { Random generator = new Random(). then call one of the methods below to get a new random number. 13.nextInt(6) + 1.15 Random class Java provides two mechanisms for creating random numbers – Math. A program to generate a random double random import java. int i = r.

} } 13. This example demonstrates how to create and use a BitSet. thus it can be used to create a thread of execution.util package schedules instances of a class called TimerTask. TimerTask implements the Runnable interface. // Flip all bits in the bitset bits.16 BitSet class A BitSet class creates a special type of array that holds bit values.and(bits2).get(2). The BitSet class represents a set of bits. b = bits. // Clear a bit bits. It automatically grows dynamically. bits2. // 100 = decimal 4 // false // true // 1110 // 0100 // 1010 // 0101 // 0001 // 1111 13. // Set a bit on bits.clear(1). // Setting a range of bits BitSet bits2 = new BitSet(). // Or'ing two bitsets bits.or(bits2). // Andnot'ing two bitsets bits.andNot(bits2). // Retrieving the value of a bit boolean b = bits. 4).set(2).out. 335 .double num1 = generator.length()).println("A random double number: " + num1). The BitSet class implements a bit-vector of an arbitrary size.17 Timer and TimerTask classes The Timer class in the java. bits.xor(bits2). System. // Xor'ing two bitsets bits.set(1. // Create the bitset BitSet bits = new BitSet(). // And'ing two bitsets bits. which is also known as a bitfield.nextDouble().flip(0.get(0).

//Terminate the timer thread } } public static void main(String args[]) { new Reminder(5).util.Timer to schedule a task to execute once 5 seconds have passed. seconds*1000). Create a thread by instantiating the Timer class. */ public class Reminder { Timer timer. Instantiate the timer task object (new RemindTask()).println("Time's up!"). /** * Simple demo that uses java. The run method contains the code that performs the task. you first see this: Task scheduled.out. the following code schedules a task for execution at 11:01 p. } class RemindTask extends TimerTask { public void run() { System.out. timer. the subclass is named RemindTask. System.*. Another way of scheduling a task is to specify the time when the task should execute. This example uses the schedule method.schedule(new RemindTask().println("Task scheduled. Schedule the timer task for execution. For example. } } When you run the example. • • • • Implement a custom subclass of TimerTask. with the timer task as the first argument and the delay in milliseconds (5000) as the second argument.cancel().util. Five seconds later.m. 336 ."). you see this: Time's up! This simple program illustrates the basic parts of implementing and scheduling a task to be executed by a timer thread.import java. In this example. timer. public Reminder(int seconds) { timer = new Timer().: //Get the Date corresponding to 11:01:00 pm today.

• • • • Invoke cancel on the timer. long period) task. 1). calendar.HOUR_OF_DAY. remove all references to the Timer object. calendar.set(Calendar.set(Calendar. 23). Eventually. timer. Make the timer's thread a "daemon" by creating the timer like this: new Timer(true).getInstance(). because the program needs to keep running until the timer's task executes. if it has changed.schedule(new RemindTask(). when it is ready to notify observers of this change. Stopping Timer Threads By default. Making the timer thread a daemon wouldn't work. long delay. The Reminder example uses the first scheme. When an object of such a subclass undergoes a change. calendar.exit method. which makes the entire program (and all its threads) exit. Date time = calendar. You can do this from anywhere in the program. Observing classes must implement the Observer interface which defines the update() method. If the only threads left in the program are daemon threads.getTime(). it must call setChanged(). a program keeps running as long as its timer threads are running. 0).18 Observable class The Observable class is used to create subclasses that other parts of your program can observe. Date scheduleAtFixedRate(TimerTask scheduleAtFixedRate(TimerTask delay.MINUTE. After all the timer's scheduled tasks have finished executing.Calendar calendar = Calendar. observing classes are notified. it must call 337 . such as from a timer task's run method. Invoke the System. invoking the cancel method from the timer task's run method. Secondly. you should use one of the schedule methods when smoothness is important and a scheduleAtFixedRate method when time synchronization is more important. Date firstTime. 13. First. timer = new Timer().SECOND. An object that is being observed must follow two simple rules. the program exits. the timer's thread will terminate. time). The update() method is called when an observer is notified of a change in an observed object. Performing a task repeatedly Here are all the Timer methods you can use to schedule repeated executions of tasks: schedule(TimerTask task. long period) When scheduling a task for repeated execution. long period) time. long period) task. long schedule(TimerTask task.set(Calendar. You can terminate a timer thread in four ways.

This interface defines only the one method shown here: void update (Observable observOb. The update() method is called when a change in the observed object takes place. this object is passed to Observer’s update() method as its second parameter. If the object calls notifyObservers without having previously called setChanged. value is:”+ (String)arg). Object arg) { System. and arg is the value passed by notifyObservers(). Here Watcher implements Observer. you must implement the Observer interface.println(“update() called. } } class ObserverDemo { public static void main(String args []) { BeingWatched observed = new BeingWatched(). } } // This is the class being observed class BeingWatched extends Observable { String value. This causes the update() method in the observing object(s) to be called. The observed object must call both setChanged() and notifyObservers() before update() will be called. This class is being monitored by BeingWatched. notifyObservers(value). Object arg) Here. There can be more than one observers. class Watcher implements Observer { public void update (Observable obj. no action will take place. An example of using Observer. The Observer Interface To observe an observable object.value = value. Notice that notifyObserevers() has two forms: one that takes an argument and one does not.util. void changeValue(String value) { this.*. You can use the second parameter for passing any type of object that is appropriate for your application.notifyObservers(). import java. observOb is the object being observed. setChanged(). Otherwise null is passed to update(). 338 . If you call the notifyObservers() with an argument.out. When the value in the Watcher is changed the notifyObserver passes the changed value to the BeingWatched Object. Watcher observing = new Watcher().

} } 13.changeValue(args[0]).getInstance(Locale.util.getSymbol()).4 has added the Currency class.*.getDefaultFractionDigits()). Symbol : $ Default fractional digits : 2 339 . It defines no constructors.println(“Symbol :” + c. class CurDemo { public static void main (String args []) { Currency c = Currency.out.println(“Default fractional digits :”+ c.out. The following program demonstrates the use of Currency: import java. } } The output is shown here. */ observed./** Add the observing to the list of observers for observed object. System.19 Currency class Java 2 version 1. observed. System.US).addObserver(observing). This class encapsulates information about a currency.

regardless of whether or not an upper or lowercase 'w' was used? With regular expressions you can describe this requirement by composing a pattern made from a series of metacharacters and literals. So. then l.)(\w+)(\. as denoted by the \w. tabs. Let's step it up a notch.\w+)? The (\w+) grouping (it appears twice -.examine the one at the start) looks for word characters. This effectively rules out williamstown as a match because the second l in williamtown is not followed by a word boundary -. locate and manipulate complex patterns of text. This must be followed by a literal @ character. We may only have wanted to search for will and Will.Chapter 14 : Regular Expression Processing Using regular expressions and the java. The interesting part is the [Ww] grouping -. 14. Let's examine one more regular expression (\w+)@(\w+\.regex package. 340 .it indicates that any one of the letters enclosed within the brackets (in this case. The parentheses are not actually required here. Consider the following sentence: My name is Will and I live in williamstown. this regular expression will match text that begins with an uppercase or lowercase w. The + indicates that one or more word characters must appear (not necessarily the same one). These metacharacters actually form a miniature language in their own right. How could we find all occurrences of the text 'Will'. you can easily describe. and not for words that simply contain these 4 characters in sequence. The above regular expression will actually match 2 occurrences of will -the name Will and the first 4 characters of text in williamstown. Here is such a pattern: [Ww]ill This one's pretty straightforward. either an uppercase 'W' or a lowercase 'w') is acceptable. Here's an improved version: \b[Ww]ill\b The \b is how we describe a word boundary. and the beginning and end points of a line. and is followed by the literals i.it's followed by an i. A word boundary will match the likes of spaces. and then another l. but they do divide the expression into groupings.1 What is a Regular Expression? A regular expression is a series of metacharacters and literals that allow you to describe substrings in text using a pattern.util.

The (\w+) grouping is identical to the first grouping -.\w+)* grouping should mostly make sense at this point -.it looks for one or more word characters.au Java Safe Regular Expressions 341 . joe@optus. as you've no doubt realised already. So.au wilma@mjinteractive. You must always escape metacharacters in this way if you want to match on their literal meaning. As an example. A few examples that meet the requirements of the complete regular expression: fred@vianet.net francisfordcoppola@myisp. The period has been escaped using a backslash because the period character is itself a regex metacharacter (a wildcard that matches any character). A few examples that meet the requirements so far: billy@webworld. we use * to denote that the preceding metacharacter. here are a few examples that meet the requirements so far: billy@ joe@ francisfordcoppola@ The (\w+\.we're looking for a period followed by one or more word characters. our regular expression is intended to match email addresses. you can interpret (\.) grouping is similar. we use parentheses to group together a series of metacharacters.iinet.\w+)* as 'match a period followed by one or more word characters. Let's take a look at a few examples that would meet the requirements so far: billy@webworld.net.com joe@optus.com barney@comcorp. but expects a period to follow in order to make a match. literal or group can occur zero or more times. In our example.com The (\. \w\d* would match a word character followed by zero or more digits.net. francisfordcoppola@myisp. and match that combination zero or more times'. the (\w+)@ portion. So.Based on this first portion of our example regex. But what's with the * after the closing parentheses? In the world of regular expressions. so the * applies to the whole group.

You will sometimes want to tell the regex engine that your target string is not a single line of code. Take note that the Pattern object was retrieved via the Pattern class's static compile method -you cannot instantiate a Pattern object using new.\\w+)*". // Compile and get a reference to a Pattern object. If you need to.MULTILINE is another useful one.2 Pattern class This class lets you compile your regular expression -. This is done by calling the matcher() factory method defined by Pattern as shown here Matcher matcher(CharSequence str) Here str is the character sequence that the pattern will be matched against. For example.compile(emailRegEx). 14. Consider the following example: String emailRegEx = "(\\w+)@(\\w+\\.MULTILINE ).compile(myRegEx.Any backslash delimited metacharacters in java will need to be escaped.)(\\w+)(\\. and not just a subsequence of it. Pattern.CASE_INSENSITIVE to tell the regex engine to match ASCII characters regardless of case. our example email address regex would have to be rewritten as follows: String emailRegEx = "(\\w+)@(\\w+\\. 14. if you wanted to compile a regex with multiline and case insensitivity support. you can combine multiple flags by using the java | (vertical bar) operator.this effectively optimises it for efficiency and use by multiple target strings (strings which you want to test the compiled regular expression against). which simply determines whether the character sequence matches the pattern. The Pattern class has a number of flags that you can use as a second argument to its compile() method. This is because the backslash character has its own special meaning in Java. boolean matches() 342 . you could do the following: Pattern.CASE_INSENSITIVE | Pattern. rather. For instance.)(\\w+)(\\. Once you have a Pattern object you can use it to get a reference to a Matcher object.3 Matcher class Once you have created a Pattern object. The simplest pattern matching method is matches(). it contains several lines that have their own termination characters. you will use it to create a Matcher. Pattern. This is called the input sequence. you can use Pattern.\\w+)*". Pattern pattern = Pattern. So.

out. it may have been desirable to extract the host name portion of the email address and the username portion. The while loop runs conditionally based on the results of the Matcher class's find() method. and the substring location information. System. Understanding Groups Matcher. or 'subgroups' of the matched text? In our email example. The above example is continued below: String targetString = "You can email me at g_andy@example. it was simply a matter of using the Matcher's start() and end() methods to find out where the matched substrings occurred in the target string. Be careful: any attempts to use the matcher before calling find() will result in the unchecked IllegalStateException being thrown at runtime. Matcher matcher = pattern. The index one past the end of the current match is obtained by calling end(). You can obtain the index within the input sequence of the current match by calling start().println("Found a match: " + matcher.out. at which point it will return true.println("End position: " + matcher. Each call to find() begins where the previous one left off. Take a look at the output: Found a match: g_andy@example. notice that we used the Pattern class's matcher() method to obtain a Matcher object.end()).net to get more info". Have a look at a revised version of our Matcher driven while loop: 343 .println("Start position: " + matcher. returned by the group() method.matcher(targetString). But what if you were also interested in subsections.net Start position: 42 End position: 58 As you can see. In the body of our while loop we retrieved the matched substring using the Matcher class's group() method.out. } First up.com or andy@example. while (matcher. This method will parse just enough of our target string to make a match.To determine if a subsequence of the input sequence matches the pattern use find(). You can obtain a string containing the last matching sequence by calling group().com Start position: 20 End position: 38 Found a match: andy@example. System.group()). it prints the matched email address.find()) { System. On each occasion.start()). // Find all the matches.group() will retrieve a complete match from the target string. Our while loop executes twice: once for each email address in our target string. // Get a Matcher based on the target string.

This is particularly important when you are working with groups that are nested within other groups. // Compile regex and switch off case sensitivity. Pattern pattern = Pattern. Here' the output: I like to watch xxxx and xxxx . } As you may recall. System. Matcher matcher = pattern.group(1) + " and the ISP is " + matcher. in particular.matcher(target)..com. located using Matcher. The first group. group(1) retrieves the username portion of the email address and group(2) retrieves the ISP portion. The Username is andy and the ISP is example. The replaceAll() method takes a replacement string and replaces all matches with it.replaceAll("xxxx") ). When crafting your own regular expressions it is. represents the entire match.compile(thePattern. String target = "I like to watch bBC1 and BbC2 .out. The replaceFirst() method is very similar but will replace only the first occurrence of a match. The Username is " + matcher. // Blot out all references to the BBC.group(2)). Pattern. Have a look at the following code: // Matches 'BBC' words that end with a digit. Here is the output for the above example: Found a match: g_andy@example.group(0) + ". Further groups can be found using the same group(int index) method.net. // Get the Matcher for the target string. String thePattern = "bbc\\d". A minor oversight in this example is that the period itself is captured as part of the subgroup returned by group(2)! Keep in mind that subgroups are indexed from left to right based on the order of their opening parentheses.println("Found a match: " + matcher. The Username is g_andy and the ISP is example.I suppose MTV is okay too".group(0).I suppose MTV is okay too BackReferences 344 .CASE_INSENSITIVE). the more specific Matcher. // The target string. up to you how you logically subgroup your patterns..while (matcher.println(matcher.find()) { System. As you can see.out. are worth a mention here. The Matcher class has a number of interesting methods: String replaceAll(String replacementString) and String replaceFirst(String replacementString). as in the example. groups are represented as a set of parentheses wrapped around a subsection of your pattern. of course. Found a match: andy@example.group() or.

Here's a pattern that will do the job: (\w)(\w)(\1) In this case. mum. in concept.replaceAll("$2") would replace all matches in a target string with the value matched by the second subgroup of the regular expression. 14. 345 . but uses a dollar sign instead of a backslash.StringTokenizer. You can use the boolean matches(String regex) method to quickly determine if a string exactly matches a particular pattern. There are 5 such methods available. int limit) methods let you split a string into substrings based on a regular expression. sos. It works in the same way. the String[] split(String regEx) and String[] split(String regEx.wow. Basically. It's simple. matcher.Backreferences allow you to access captured subgroups while the regex engine is executing. that kind of thing. Basically. you would simply substitute \1 with \2 if you wanted to backreference the second group.4 String Class RegEx Methods The Java String class has been updated to take advantage of regular expressions. String replacement) and String replaceAll(String regex. So. similar to the java. And finally. this means that you can refer to a subgroup from an earlier part of a match later on in the pattern. but in many cases. the third parenthesised group will only match when the character at this position is the same as the character in the first parenthesised group. the (\1) group contains a backreference to the first match made in the pattern. String replacement) methods allow you to do quick and dirty text replacements. only much more powerful. Of course. These last two methods are.util. Imagine that you needed to inspect a target string for 3-letter words that started and ended with the same letter -. The Matcher object's replacement methods (and the String class's counterparts) also support a notation for doing backreferences in the replacement string. The appropriately named String replaceFirst(String regex. tremendously useful.

: Month/Day/Year.out.).format( new Date() ). LONG. The output will look different in different countries. and FULL (in increasing order of verbosity). static final DateFormat getDateInstance() static final DateFormat getDateInstance(int style) static final DateFormat getDateInstance(int style. the programmer can rely on the class to use an appropriate date format.text 15. it defines several static factory methods to obtain instances (of concrete subclasses) initialized for a given locale and a chosen style. Note that concrete subclasses may choose to break this idiom.1 DateFormat class While Calendar and related classes handle the locale-specific interpretation of dates.println(now). String now = df. The commands DateFormat df = DateFormat. the DateFormat classes assist with the transformation of dates to and from human-readable strings. taking an additional ParsePosition or FieldPosition argument. an additional localization issue arises: not only the language. However. The DateFormat utility tries to manage these differences for the application programmer. Instead. One takes or returns a Date instance and the other takes or returns a general Object.getDateTimeInstance(). Germany: Day.Year. programmer-defined date formats. but also the date format is locale-dependent (U. as are the employed TimeZone and NumberFormat objects. respectively. formatted according the conventions of the default locale. Given a locale and a style. it defines four different format styles: SHORT.S. Locale locale) The String format(Date) and Date parse(String) methods then perform the transformation. to allow handling of alternatives to Date in subclasses. Also available are (abstract) methods for piece-wise parsing or formatting. There are two versions for each of these methods. The class defines several public static 346 . The abstract base class DateFormat does not require (and does not permit) the definition of arbitrary. MEDIUM. When representing points in time.Month. etc. System. The abstract base class DateFormat does not define static methods for formatting (date to text) or parsing (text to date).Chapter 15 : API classes in java. Instead. print the current date and time (as returned by "new Date()"). the locale and style can no longer be changed once the DateFormat has been instantiated. additional factory methods are available to obtain instances treating only the time or date part. Since the standard formats always include both date and time. The Calendar object used internally to interpret dates is accessible and can be modified.

LONG).out.util. Date d = firstFlight.out. df = DateFormat.util. df = DateFormat. df = DateFormat.JAPAN).getDateInstance(DateFormat. Locale.format(date)). import java.println(“Japan :”+df.getTime(). Locale.US). System. Calendar.getDateInstance(DateFormat.*. DateFormat df = DateFormat.println(“Korea :”+df.KOREA).text. and getting and outputting the corresponding String in the following program: import java.format(date)).getDateInstance(DateFormat. } } One more example that specifies the date style and locale import java. You can put the whole process of creating a GregorianCalendar object. System.FULL. System.UK). System.println(“UK :”+ df.text.println("First flight was " + s).MEDIUM.format(d).SHORT.getDateInstance(DateFormat. 17). } } Sample output is shown below: 347 . DateFormat df = DateFormat.getDateInstance(DateFormat. public class Flight { public static void main(String[] args) { GregorianCalendar firstFlight = new GregorianCalendar (1903.out. Locale.*. System. Locale. String s = df.out. converting it to a Date.LONG.variables with names ending in _FIELD to identify the various possible fields for use with FieldPosition In the following example the getTime() method of GregorianCalendar returns a Date corresponding to the GregorianCalendar object. public class DateFormatDemo { public static void main (String args[]) { Date date = new Date().println(“US :”+ df.format(date)).format(date)). import java.*.DECEMBER.*.out.

SHORT.*. System. It provides all of the aforementioned functionality.getTimeInstance( DateFormat.getTimeInstance(DateFormat.text.format(date)).Locale.Locale. 15. Locale locale) The style argument is one of the following values: DEFAULT. May 8.println(“UK :”+df. SHORT. } } Sample output from the program is shown here: Japan : 20:25 UK : 20:25:14 CDT Canada : 8:25:14 o’clock PM CDT The DateFormat class also has a getDateTimeInstance() method that can format both date and time information. DateFormat df = DateFormat.Japan : 02/05/08 Korea: 2002-05-08 UK: 08 May 2002 US: Wednesday. These are int constants which cause different details about the time to be presented. It is available in these versions: static final DateFormat getTimeInstance() static final DateFormat getTimeInstance(int style) static final DateFormat getTimeInstance(int style.println(“Japan :”+df. Locale.format(date)).out.println(“Canada :”+df.CANADA). df = DateFormat.FULL. LONG or FULL.*.LONG. If the style and/or locale is not specified defaults are used.2 SimpleDateFormat class The only commonly available concrete subclass of DateFormat is SimpleDateFormat. The pattern can be specified as an argument to the constructors of this class or set explicitly. System. df = DateFormat.UK). The argument locale is one of the static references of Locale. import java.JAPAN).getTimeInstance(DateFormat.format(date)). System.util. An example of using it is shown below: import java. public class TimeFormatDemo { public static void main(String args[]) { Date date = new Date(). additionally allowing the definition of arbitrary dateformatting patterns.out. 348 . 2002 The getTimeInstance() method returns an instance of DateFormat that can format time information.out. MEDIUM.

String logEntry = formatter. One example of using SimpleDateFormat import java. public class test { public static void main (String args[]) { Date date = new Date(). M or MM causes the month to be displayed as one or two digits. } } One more example to format and parse it back.util.The constructor normally takes a formatting string made from the following symbols: Char a d h k m s w y z : Meaning Char Meaning AM or PM D Day of year Day of month E Day of week Hour (1-12) F Day of week in month Hour (1-24) G Era (AD or BC) Minute H Hour in Day (0-23) Second K Hour in Day (0-11) Week of year M Month Year S Millisecond Timezone W Week of month Separator / Escape character SimpleDateFormat(String formatString) In most cases. SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd hh:mm"). String rptDate = sdf. Three or more repetitions of M cause the month to be displayed as a text string.format(now). the number of times a pattern letter is repeated determines how many digits are presented. the number of times a symbol is repeated determines how that data is presented. For numbers.*.*. import java.println(rptDate+"\n").format(date). Text information is displayed in an abbreviated form if the pattern letter is repeated less than four times. System. // Create a formatter with the following pattern: //Hour(0-23):Minute:Second SimpleDateFormat formatter = new SimpleDateFormat( "HH:mm:ss" ).out. Otherwise unabbreviated form is used.text. Date now = new Date(). 349 .

" If the symbols encapsulated in SimpleDateFormat don't meet your needs.out. for (int i = 0. 15. The first element in the array argument of setShortWeekdays is a null String.parse( logEntry ).3 DateFormatSymbols class The format method of the SimpleDateFormat class returns a String composed of digits and symbols. 350 . 1998." the symbols are "Friday" and "April. } Note the ParseException that needs to be caught. The full source code for this example is in DateFormatSymbolsDemo. String [] defaultDays = symbols. The SimpleDateFormat constructor accepts the modified DateFormatSymbols object as an argument.length. among others. days of the week. } catch ( ParseException exc ) { exc.getShortWeekdays(). i++) { System.print(defaultDays[i] + " "). } System."US")). i < defaultDays.println(). You can change symbols that represent names for months.printStackTrace(). Therefore the array is one-based rather than zero-based. April 10. in the String "Friday.out. Here is the source code: DateFormatSymbols symbols = new DateFormatSymbols( new Locale("en". It is thrown when the beginning of the input string cannot be parsed. you can change them with the DateFormatSymbols. For example.// To read the string back in try { Date sometime = formatter. The following table lists the DateFormatSymbols methods that allow you to modify the symbols: DateFormatSymbol Methods Example of a Symbol the Method Modifies setAmPmStrings PM setEras AD setMonths December setShortMonths Dec setShortWeekdays Tue setWeekdays Tuesday setZoneStrings PST Setter Method The following example invokes setShortWeekdays to change the short names of the days of the week from lowercase to uppercase characters. and time zones.

and a percentage formatter. your number will automatically use the comma as the decimal separator and the period as the grouping separator--just the opposite of the custom in the US. The three factory methods you use to create built-in format objects are the getNumberInstance(). a currency formatter.format(today). System. pf = NumberFormat. You don't use the new operator to construct your NumberFormat objects. The first step is to create a NumberFormat object. nf = NumberFormat.setShortWeekdays(capitalDays). cf. 351 . symbols. To use your NumberFormat object. Here's an example: NumberFormat nf. "SUN". passing either a double primitive value or a Double object.println (“Total amount: "+fmt. i++) { System. symbols). for instance. } System. "TUE". System.4 NumberFormat class Using Java's NumberFormat class.getPercentInstance(). "WED". i < modifiedDays.out.getCurrencyInstance(). "SAT"}.out. for (int i = 0. pf. You have your choice of three built-in formatting styles: a generic number formatter. String result = formatter. Date today = new Date(). and getPercentInstance(). SimpleDateFormat formatter = new SimpleDateFormat("E". you simply call its format() method. getCurrencyInstance(). For example. you can automatically format numbers according to the local conventions in use where your application is run. If your application is run in Germany.getNumberInstance().String[] capitalDays = {“". instead you use very specific methods called factory methods. cf = NumberFormat. The preceding code generates this output: Sun SUN WED Mon MON Tue TUE Wed WED Thu THU Fri FRI Sat SAT 15. String [] modifiedDays = symbols.getCurrencyInstance().getShortWeekdays().println(result). "FRI". "THU".out. "MON".print(modifiedDays[i] + " ").format(amount)).out.length. NumberFormat fmt = NumberFormat.println().

out.246). because the numeric values are all the same.21). The format method accepts the Double as an argument and returns the formatted number in a String.toString()). This code example shows how to format currency in a locale-specific manner: Double currency = new Double(9876543. bear in mind that the NumberFormat class is unaware of exchange rates. The output generated by the preceding lines of code is as follows: 9 876 543. such as Double. it returns a String that includes the formatted number and the appropriate currency sign.You can use the NumberFormat methods to format primitive-type numbers.21 F is not equivalent to 9.out.21 DM de_DE $9. You format currencies in the same manner as numbers.println(amountOut + " " + currentLocale. Double amount = new Double(345987.getCurrencyInstance(currentLocale).876. To get the locale-specific formatter. Of course.21 en_US At first glance this output may look wrong to you.getNumberInstance(currentLocale). The output from this example shows how the format of the same number varies with Locale: 345 987. Invoking the getNumberInstance method returns a locale-specific instance of NumberFormat. you'll probably need to format and to display currencies. NumberFormat currencyFormatter = NumberFormat. String amountOut = numberFormatter.876. When you invoke the format method. such as double.543.543. The methods belonging to the NumberFormat class format currencies but do not convert them. String currencyOut = currencyFormatter.543.987. The following code sample shows how to format a percentage. NumberFormat numberFormatter = NumberFormat. invoke the getPercentInstance method. However.println(currencyOut + " " + currentLocale.21 F fr_FR 9. You can also use the methods of the NumberFormat class to format percentages. With this formatter.246 345.246 fr_FR de_DE en_US If you're writing business applications.75 is displayed as 75%. 352 .21 DM. System. System. 9 876 543.987.876.format(currency). a decimal fraction such as 0.format(amount).toString()). except that you call getCurrencyInstance to create a formatter. The following code example formats a Double according to Locale. and their corresponding wrapper objects.246 345.

These classes offer a great deal of flexibility in the formatting of numbers. but they can make your code more complex.out. ' Interpretation A digit // leading zeros show as 0 A digit // leading zeros show as absent The locale-specific decimal separator The locale-specific grouping separator (comma) The locale-specific negative prefix Shows value as a percentage Separates a positive number format (on left) from an optional negative number format (on right) Escapes a reserved character so it appears literally in the output You specify the formatting properties of DecimalFormat with a pattern String. NumberFormat percentFormatter = NumberFormat. . System. The applyPattern() method can be used to change this pattern. prefixes and suffixes.($#. For example: "$#. 353 . The pattern determines what the formatted number looks like.5 DecimalFormat class You can use the DecimalFormat class to format decimal numbers into locale-specific strings. grouping (thousands) separators. Applications that require highly customized number formatting and parsing may create custom DecimalFormat class objects by passing a suitable pattern to the DecimalFormat() constructor method. a DecimalFormatSymbols object suitable for the default locale is used. This class allows you to control the display of leading and trailing zeros.println(value + " " + pattern + " " + output).00)" Char 0 # . and the decimal separator.format(value). The format method accepts a double value as an argument and returns the formatted number in a String: DecimalFormat myFormatter = new DecimalFormat(pattern).getPercentInstance(currentLocale). String percentOut = percentFormatter. 15. If one is not specified.Double percent = new Double(0. such as the decimal separator.00.format(percent). % . you can use the DecimalFormatSymbols in conjunction with the DecimalFormat class. The example that follows creates a formatter by passing a pattern String to the DecimalFormat constructor.##0.##0. A DecimalFormatSymbols object can be optionally specified when creating a DecimalFormat object. Decimal format patterns consists of a string of characters from the following table. If you want to change formatting symbols. String output = myFormatter.75).

## 000000. } } The preceding example created a DecimalFormat object for the default Locale.78 9 123. that is to be formatted.78 9 123456.###. The value is the number. but the pattern has only two. The first character in the pattern is the dollar sign ($).345.67 ###. rptNumb = df.000 $###.### 000123. String rptNumb. If you want a DecimalFormat object for a nondefault Locale. DecimalFormat df = new DecimalFormat("000"). you instantiate a NumberFormat and then cast it to DecimalFormat.### ¥12. and the period is a placeholder for the decimal separator.text.format(value). represents the formatted number.format(numb).out. a double . The pattern specifies leading and trailing zeros. Note that it immediately precedes the leftmost digit in the formatted output. System.79 ###. The pattern specifies the currency sign for Japanese yen (¥) with the Unicode value 00A5. The pattern is the String that specifies the formatting properties.*.###. public class test { public static void main (String args[]) { int numb = 3. the comma is a placeholder for the grouping separator. The format method handles this by rounding up.The output for the preceding lines of code is described in the following table.78 12345.println(rptNumb+"\n"). DecimalFormat df = (DecimalFormat)nf.456.780 $12. The output. Output from DecimalFormatDemo Program value pattern output 123456.67 \ u00A5###. Here's an example: NumberFormat nf = NumberFormat.67 12345. because the 0 character is used instead of the pound sign (#). 354 . df.getNumberInstance(loc). The value has three digits to the right of the decimal point. which is a String.applyPattern(pattern). String output = df.### 123.345. Here is an example of how DecimalFormat can be used: import java.78 9 123456.67 Explanation The pound sign (#) denotes a digit.###.

unusualSymbols.S.## the comma is the thousands-separator and the period represents the decimal point. unusualSymbols. DecimalFormat weirdFormatter = new DecimalFormat(strange. Running the previous code example results in the output that follows.###.format(12345. These symbols include the decimal separator. The unusual format is the result of the calls to the setDecimalSeparator. DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale). For example. and the percent sign. which is in the second column. The next example demonstrates the DecimalFormatSymbols class by applying a strange format to a number. such as spreadsheets and report generators. In these cases you'll want to invoke the applyLocalizedPattern method on the DecimalFormat object.print(.System. English. weirdFormatter.### ###. in the pattern ###. You can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method.##0. This convention is fine.### ###. 355 . the minus sign. provided that your end users aren't exposed to it.456. unusualSymbols).6 Format class The class Format provides several overloaded Format.out.toString()). String strange = "#.### 123. For these applications the formatting patterns specified by the end users should use localized notation. allow the end users to define their own formatting patterns. varies with Locale: ###.###".789 123 456. among others.setGroupingSeparator('^').456. this example prints the number in a bizarre format: 1^2345|678 15. String bizarre = weirdFormatter.println(bizarre).789 en_US de_DE fr_FR So far the formatting patterns discussed here follow the conventions of U.) static methods to output a single number or string with formatting descriptions similar to the printf function in C.setDecimalSeparator('|').###. and setGroupingSize methods. setGroupingSeparator.###. System. However. The formatted number..setGroupingSize(4).out.789 123. some applications.###. the grouping separator.println(pattern + " " + output + " " + loc.678). When run.

print("0. An instance of the format must first be created with the desired formatting description.5g").format (q). class FormatDemo { public static void main(String args[]) { double q = 1.out.println ("1. // The # symbol indicates trailing blanks q = 1.text.0. // Create an instance of the format pattern // and then create the string with the method format String qValStr = new Format ("%0. q).println ("1. System.0.For example.out.out. where arg is a number type. String str = new Format("0.0 = " + qValStr). The following program shows the use of Format class.0 = " + qValStr).0 = " + qValStr). This can be done in a convenient single line approach by appending the method invocation to the instantiation operation as shown here: double q =10. the class provides several overloaded format(arg) methods.5f"). qValStr = new Format ("%0. System.0.0/3. Format. // q = 3.0/3.println ("1. qValStr = new Format ("%0.format(q) which results in the string variable str referencing "3.format (q).3333 To send formatted outputs directly to a string.2e").4f".0.0.out. System.0 = " + qValStr).*. System.0/3. will result in an output of 3.println ("1000. 356 . // q = 1000.0/3.333e+000".0/2.0/3.0/3.0/2.format (q).3f"). double q =10.0/3. import java.3e").0. // Can change the format pattern: qValStr = new Format ("%0.0/4567.format (q).

357 . // Negative infinity q = -1.0 = " + qValStr).0/0.3e").0/2. qValStr = new Format ("%0.out.out. percentages.0 = 0. } } Output of this program: 1. you can design a custom format using patterns.0 = 6.0/4567.0.format (q).0/3. System. or currency.text package.0/0. System.println ("3.out.println ("-1.println ("0. // NaN q = 0.2e").0/0.57e-004 -1.0/0.0 = NaN Summary To format a number to display to an end user.0 = 3.33333 1.0 = -Inf 0. System.0 = 0.format (q).0 = " + qValStr).0 = " + qValStr).333 1.0/0. you can get a default format for decimal numbers.0 = 0.0/3.5 1000. When using NumberFormat.0/4567.0/3.qValStr = new Format ("%0. Or.0.33e+002 3. qValStr = new Format ("%0.0/0.format (q).3e"). you use the NumberFormat class in the java.

but you would be able to differentiate between a collection of references to Integers and collection of references to Bytes. Collections are used to store. and a second class called GenSample that calls it. when the element is extracted from the collection an Object is returned that must be cast to an Integer in order to ensure type safety.e. A Java collection is a flexible data structure that can hold heterogeneous objects where the elements may have any reference type. Integer) before storing it in the collection. class BasicGeneric <A> { 358 . Using generics. A generic (also known as a parametrized type) is a type that has one or more type parameters. The type parameters then appear in the type's methods. to keep track of what types of objects your collections contain. All this makes Java programs unnecessarily hard to read and maintain. A collection with a generic type has a type parameter that specifies the element type to be stored in the collection. The type parameters are a comma separated list of identifiers delimited by angle brackets.2 Generics The motivation for adding generics to the Java programming language stems from the lack of information about a collection's element type. Now. and to transmit data from one method to another. the need for developers to keep track of what type of elements collections contain. and the need for casts all over the place. since you cannot have collections of primitive data types you must convert the int to the corresponding reference type (i. 16.java contains a very simple generic class called BasicGeneric. Generics allow you to define a class or interface once and instantiate it with a variety of types. By convention. To use a generic you supply an actual type argument for each type parameter and in doing so constrain the generic type to act only on the argument types.1 What is a Collection? A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.Chapter 16 : Collections Framework and Generics 16. a collection is no longer treated as a list of Object references. type parameters are uppercase letters. It is your responsibility. Collections typically represent data items that form a natural group. you include type parameters following the type name. consider adding an int to a collection. As an example. either as the type of arguments in the method's parameter list or as the type of its return value. however. Defining and Using Generic Types To define a generic. retrieve and manipulate data. GenSample. and are more likely to fail with runtime errors.

This syntax can be confusing at first glance. Integer data02 = basicGeneric. It is a generic type. BasicGeneric <Integer> basicGeneric = new BasicGeneric<Integer>(data01). we don't assign a type to A. } } Here you can see the brackets that surround the capital letter A: <A>.test01("This generic data")).out.getData(). BasicGeneric does not work with any specific type. But it is quite sensible when you begin to understand generics.data = data. As a result.println(sample.private A data. } public static void main(String [] args) { GenSample sample = new GenSample(). String data02 = basicGeneric. BasicGeneric<String> basicGeneric = new BasicGeneric<String>(data01). return data02. But when you declare an instance of this class.getData(). System. This syntax specifies that the class is a generic type. public BasicGeneric(A data) { this. Notice also that the class declares a variable of type A – data. } } public class GenSample { public String test01(String input) { String data01 = input. System. } public A getData() { return data. you must specify the type with which you want to work: BasicGeneric<String> basicGeneric 359 . } public int test02(int input) { Integer data01 = new Integer(input).out. return data02.test02(12)).println(sample.

algorithms are reusable functionality. these interfaces generally form a hierarchy. Also.3 What Is a Collections Framework? A collections framework is a unified architecture for representing and manipulating collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages like Java. rather than the low-level plumbing required to make it work. Implementations: concrete implementations of the collection interfaces. these are reusable data structures. Benefits of Collection Framework • • • • It reduces programming effort: By providing useful data structures and algorithms. 16. These algorithms are said to be polymorphic because the same method can be used on many different implementations of the appropriate collections interface. our APIs will interoperate seamlessly even though they were written independently. There was little consistency among these ad-hoc collections sub-APIs. programs can be easily tuned by switching collection implementations. BasicGeneric will act as if it were declared from the very beginning to work with that specific type. each such API had a little "sub-API" devoted to manipulating its collections. If my network administration API furnishes a Collection of node names. a collections framework frees you to concentrate on the important parts of your program.util package. because you're freed from the drudgery of writing your own data structures. which is to say that it will return a generic type. By facilitating interoperability among unrelated APIs. so you had to learn each one from scratch and it was easy to make mistakes 360 . or even at compile time. The collections framework is a part of java. Algorithms: methods that perform useful computations. you'll have more time to devote to improving the quality and performance of the rest of the program. But that does not mean that the function will not have a type at run time. high-quality implementations of useful data structures and algorithms. the collections framework frees you from writing oodles of adapter objects or conversion code to connect APIs. After you declare an instance of BasicGeneric. All collections frameworks contain three things: • • • Interfaces: abstract data types representing collections. It reduces the effort to learn and use new APIs: Many APIs naturally take collections on input and output. and your GUI toolkit expects a Collection of column headings. In the past. It allows interoperability among unrelated APIs: The collections interfaces will become the "lingua franca" by which APIs pass collections back and forth. like searching and sorting. In essence. Finally. because the various implementations of each interface are interchangeable. you will have specified the type of A. After that. and that type only.The method getData() returns a value of type A. In essence. It increases program speed and quality: The collections framework does this primarily by providing high-performance. on objects that implement collection interfaces.

The core collection interfaces are the heart and soul of the collections framework. the problem goes away.. With the advent of standard collections interfaces. It fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces. and to pass them from one method to another. The basic purpose of these interfaces is to allow collections to be manipulated independently of the details of their representation. the declaration of the Collection interface is: public interface Collection<E> . Some types of collections allow duplicate elements. For example.. Set 361 . such as Set and List. The <E> syntax tells you that the interface is generic. Some are ordered and others unordered. and is used to pass collections around and to manipulate them when maximum generality is desired.• • when using them. It reduces effort to design new APIs: This is the flip-side of the previous advantage: designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections. Collection The Collection interface is the root of the collection hierarchy. Specifying the type allows the compiler to verify (at compile time) that the type of object you put into the collection is correct. The Collection interface is the least common denominator that all collections implement. 16. thus reducing errors at runtime. When you declare a <code> Collection instance you can and should specify the type of object contained in the collection.4 Collection Interfaces The core collection interfaces are the interfaces used to manipulate collections. They just use the standard collections interfaces. and others do not. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces. The core collections interfaces are shown below: Note that all of the core collection interfaces are generic.

Lists can contain duplicate elements. Every Queue implementation must specify its ordering properties. It is used to represent sets like the cards comprising a poker hand. extraction. or the processes running on a machine. it allows you to convert the type of the collection. queues provide additional insertion. In other words. initializes the new collection to contain all the elements in the specified Collection. The user can access elements by their integer index (position). Whatever the ordering used. which order elements according to a supplied comparator. this interface models the mathematical set abstraction. The SortedMap interface is used for apps like dictionaries and telephone directories. Map A Map is an object that maps keys to values. Other kinds of queues may use different placement rules. As you might expect. List A List is an ordered collection (sometimes called a sequence). SortedSet A SortedSet is a Set that maintains its elements in ascending order. Maps cannot contain duplicate keys: Each key can map to at most one value. 362 . The user of a List generally has precise control over where in the List each element is inserted. It is the Map analogue of SortedSet. SortedMap A SortedMap is a Map that maintains its mappings in ascending key order. Among the exceptions are priority queues. or the elements' natural ordering. known as a conversion constructor.5 The Collection Interface The Collection interface is used to pass around collections of objects where maximum generality is desired. For example. whatever the given collection's subinterface or implementation type. the head of the queue is that element that would be removed by a call to remove or poll. The Set interface extends Collection and contains no methods other than those inherited from Collection. In a FIFO queue. all new elements are inserted at the tail of the queue. 16. This constructor. but do not necessarily. the courses making up a student's schedule. by convention all general-purpose collection implementations have a constructor that takes a Collection argument.A Set is a collection that cannot contain duplicate elements. Besides basic Collection operations. Queues typically. and inspection operations. Queue A collection used to hold multiple elements prior to processing. order elements in a FIFO (first-in-first-out) manner.

which may be a List. al. a Set. System. and then objects of type String are added to it. } } 363 . and to return true if the Collection was modified as a result.println(“Contents of al : ” + al).Suppose.size()). The following program shows a simple use of ArrayList. The list is then displayed.add(“B”). Some of the elements are removed and the list is displayed again. to add and remove an element from the collection (add. The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't. al. the remove method is defined to remove a single instance of the specified element from the Collection. Similarly. al.println(“Size of al after deletions :” +al. An arraylist is created . al. for example. //Remove elements from arraylist al.add(“C”). The interface has methods to tell you how many elements are in the collection (size. //display the array list System.remove(“F”). assuming that it contains the element to start with. System.add(“E”). isEmpty).println(“Size of al after additions:” + al. class ArrayListDemo { public static void main(String args[]) { //create an array list ArrayList al = new ArrayList(). System.add(“D”). al.out.util.out. and to provide an iterator over the collection (iterator). import java.*. or another kind of Collection.println(“Contents of al:”+al).println(“Initial size of al :”+al.add(“A”). al. and returns true if the Collection changes as a result of the call. It guarantees that the Collection will contain the specified element after the call completes.size()).out. that you have a Collection<String> c. initially containing all the elements in c: List<String> list = new ArrayList<String>(c).out. remove). //add elements to arraylist al. The following idiom creates a new ArrayList (an implementation of the List interface). given that a Collection represents a group of objects. to check whether a given object is in the collection (contains).add(“F”).out. System.size()). The interface does about what you'd expect.remove(“E”).

364 .out.println(o). The hasNext method returns true if the iteration has more elements. You get an Iterator for a collection by calling its iterator method.out.D] Traversing Collections There are two ways to traverse collections: with the for-each construct and using iterators.The output of this program is shown here: Initial size of al : 0 Size of al after additions : 6 Contents of al : [C. class ArrayListDemo2 { public static void main(String args[]) { ArrayList al = new ArrayList().D.A.util.println(o). The remove method removes from the underlying Collection the last element that was returned by next. and to remove elements from the collection selectively.F] Size of al after deletions : 4 Contents of al : [C. The following code shows an example import java.*. al. al. The following code uses the for-each construct to print out each element of a collection on a separate line: for (Object o : collection) System.B. } } } Iterators An Iterator is an object that enables you to traverse through a collection. The remove method may be called only once per call to next and throws an exception if this rule is violated.E.add(new Float(1.B. and the next method returns the next element in the iteration. al. if desired.add(“ABC”). For-Each Construct The for-each construct allows you to concisely traverse a collection or array using a for loop The for Statement. for(Object o : al) { System.A.0)).add(new Integer(10)).

Note that Iterator. You need to iterate over multiple collections in parallel.remove(). } } System. class IteratorDemo { public static void main(String args[]) { ArrayList al = new ArrayList().add(“E”). An example that shows the use of Iterator: //Demonstrate Iterators import java. You could implement these shorthand operations using the basic operations. al. if(((String)element).equals(“E”)) { itr. } } The output of this program is as follows : A B C D E [A.C. al.out.remove is the only safe way to modify a collection during iteration.hasNext()) { Object element = itr. though in most cases such implementations would be less efficient. You need to replace elements in a list or array as you traverse it. The bulk operations are: 365 .*. so you cannot call remove.out.add(“B”).D] Collection Interface Bulk Operations The bulk operations perform an operation on an entire Collection.util. System. The for-each construct hides the iterator.println(al). //use Iterator to display contents of al Iterator itr = al.add(“C”).out. the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress. Therefore.iterator().next().print(element+ “ ”). Use an iterator instead of the for-each construct when: • • • You need to remove the current element. al. //add elements to arraylist al.B.println(). al.add(“A”). System. while(itr. the for-each construct is not usable for filtering.add(“D”).

• • • • • containsAll: Returns true specified Collection. al. The array operations allow the contents of a Collection to be translated into an array. For example.*. Collection Interface Array Operations The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. addAll: if the target Collection contains all of the elements in the Adds all the elements in the specified Collection to the target Collection. clear: Removes all elements from the Collection.out. The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c: Object[] a = c. That is. al. import java. An example of converting an ArrayList into an array. The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c: String[] a = c. //add elements to array list al.toArray(new String[0]). Suppose that c is known to contain only strings (perhaps because c is of type Collection<String>). and retainAll methods all return true if the target Collection was modified in the process of executing the operation. removeAll: Removes from the target Collection all its elements that are also contained in the specified Collection. al.add(new Integer(1)). The simple form with no arguments creates a new array of Object. class ArrayListToArray { public static void main(String args[]){ ArrayList al = new ArrayList(). retainAll: Removes from the target Collection all its elements that are not also contained in the specified Collection. System. //get array Object [] ia = al. it retains in the target Collection only those elements that are also contained in the specified Collection.util. The addAll.add(new Integer(3)).toArray(). removeAll. 366 .println(“Contents of al:”+al). int sum=0.add(new Integer(4)).toArray(). suppose that c is a Collection.add(new Integer(2)). The more complex form allows the caller to provide an array or to choose the runtime type of the output array.

i < ia. is the best-performing implementation but it makes no guarantees concerning the order of iteration. at a cost that is only slightly higher. generally chaotic ordering provided by HashSet. and adds the restriction that duplicate elements are prohibited. It models the mathematical set abstraction. which stores its elements in a hash table.} } //sum of array elements for(int i=0. The output of the program is shown below: Contents of al: [1. LinkedHashSet spares its clients from the unspecified. Here is a generic method that encapsulates the above idiom. } System. LinkedHashSet. and LinkedHashSet HashSet. Here's a simple but useful Set idiom. The Java platform contains three general-purpose Set implementations: HashSet. TreeSet. TreeSet. but is substantially slower than HashSet. orders its elements based on the order in which they were inserted into the set (insertion-order).3. c.6 The Set Interface A Set is a Collection that cannot contain duplicate elements. returning a set of the same generic type as the one passed in: 367 .println(“Sum is:”+sum). allowing Set instances to be compared meaningfully even if their implementation types differ. orders its elements based on their values. Suppose you have a Collection. The Set interface contains only methods inherited from Collection.) initially containing all the elements in c Here is a minor variant of this idiom that preserves the order of the original collection while removing duplicate element: Collection<Type> noDups = new HashSet<Type>(c).out. which stores its elements in a red-black tree. which is implemented as a hash table with a linked list running through it. and you want to create another Collection containing the same elements but with all duplicates eliminated. Two Set instances are equal if they contain the same elements.4] Sum is: 10 16. which by definition. Set also adds a stronger contract on the behavior of the equals and hashCode operations. cannot contain duplicate.length . i++) { sum += (Integer)ia. It works by creating a Set. The following one-liner does the trick: Collection<Type> noDups = new HashSet<Type>(c).2.

and a list of the words with duplicates eliminated: import java. Similarly.add(a)) { System. left.out. public class FindDups { public static void main(String args[]) { Set<String> s = new HashSet<String>(). Here's a program that takes the words in its argument list and prints out any duplicate words. rather than by its implementation type (HashSet). as it gives you the flexibility to change implementations merely by changing the constructor. saw.size()+" distinct words:" + s). The add method adds the specified element to the Set if it's not already present. If either the variables used to store a collection or the parameters used to pass it around are declared to be of the collection's implementation type rather than its interface type. If the program uses any nonstandard operations that are present in the original implementation type but 368 .println("Duplicate: " + a). The isEmpty method does exactly what you think it does. the number of distinct words. This is a strongly recommended programming practice. all such variables and parameters must be changed in order to change the collection's implementation type.out.println(s. The iterator method returns an Iterator over the Set. and returns a Boolean indicating whether the element was added.util. } Set Interface Basic Operations The size operation returns the number of elements in the Set (its cardinality). } } Now let's run the program: java FindDups i came i saw i left The following output is produced: Duplicate: i Duplicate: i 4 distinct words: [i.public static <E> Set<E> removeDups(Collection<E> c) { return new LinkedHashSet<E>(c). came] Note that the code always refers to the collection by its interface type (Set). } } System. for (String a : args) { if (!s. the remove method removes the specified element from the Set if it's present and returns a Boolean indicating whether the element was present.*.

) To calculate the union. the set difference of s1 . the best all-around Set implementation in the Java platform. difference. The resulting idioms follow: Set<Type> union = new HashSet<Type>(s1).addAll(s2): Transforms s1 into the union of s1 and s2.retainAll(s2): Transforms s1 into the intersection of s1 and s2.containsAll(s2): Returns true if s2 is a subset of s1. which is.not in the new one.addAll(s2). However. when applied to sets. saw] Set Interface Bulk Operations The bulk operations are particularly well suited to Sets. the program will fail. Referring to collections only by their interface prevents you from using any nonstandard operations. The implementation type of the Set in the preceding example is HashSet. (s2 is a subset of s1 if set s1 contains all the elements in s2.) s1.) s1.) s1. 369 . merely change the set's implementation type from HashSet to TreeSet. (The union of two sets is the set containing all the elements contained in either set. which makes no guarantees as to the order of the elements in the Set.s2 is the set containing all the elements found in s1 but not in s2. as already mentioned. the caller must copy one set before calling the appropriate bulk operation. Making this trivial one-line change causes the command line in the previous example to generate the following output: java FindDups i came i saw i left Duplicate word: i Duplicate word: i 4 distinct words: [came. any general-purpose Set implementation could be substituted. union. (For example. or set difference of two sets nondestructively (without modifying either set). intersection. If you want the program to print the word list in alphabetical order.retainAll(s2). Suppose s1 and s2 are Sets.removeAll(s2). intersection.removeAll(s2): Transforms s1 into the (asymmetric) set difference of s1 and s2. left. Set<Type> intersection = new HashSet<Type>(s1). The implementation type of the result Set in the preceding idioms is HashSet. Here's what the bulk operations do: • • • • s1. Set<Type> difference = new HashSet<Type>(s1). (The intersection of two sets is the set containing only the elements that are common to both sets. they perform standard set-algebraic operations. i.

Set Interface Array Operations The array operations don't do anything special for Sets beyond what they do for any other Collection. Here's how the resulting program looks: import java. The following code calculates the symmetric set difference of two sets nondestructively: Set<Type> symmetricDiff = new HashSet<Type>(s1).retainAll(s2)). The words that occur only once are the set difference of these two sets. Suppose that you want to know which words in the argument list occur only once and which occur more than once but that you do not want any duplicates printed out repeatedly. tmp.removeAll(dups).add(a)) { dups. for (String a : args) { if (!uniques. which we know how to compute. System.out.println("Duplicate words: " + dups).out.util. } } } When run with the same same argument list used earlier (i came i saw i left). the program yields the output: Unique words: [left. Set<String> dups = new HashSet<String>().Let's revisit the FindDups program. one containing every word in the argument list and the other containing only the duplicates. public class FindDups2 { public static void main(String args[]) { Set<String> uniques = new HashSet<String>().println("Unique words: " + uniques). symmetricDiff. } // Destructive set-difference uniques. saw.add(a).removeAll(tmp). System. Set<Type> tmp = new HashSet<Type>(s1). came] Duplicate words: [i] A less common set-algebraic operation is the symmetric set difference: the set of elements contained in either of two specified sets but not in both.addAll(s2). symmetricDiff. Set Implementations 370 . This effect can be achieved by generating two sets.*.

add(“D”). class HashSetDemo { public static void main(String args[]) { //create a hash set HashSet hs = new HashSet().add(“B”).F] 16. ts. Access and retrieval times are quite fast which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.D.7 The List Interface A List is an ordered Collection (sometimes called a sequence). ts.add(“E”). hs.B.*. } } The output from this program is shown here: [A.util.out. ts. TreeSet stores objects in ascending order.add(“D”). An example of TreeSet is shown below: import java. the List interface includes operations for the following: 371 . ts. An example of using HashSet.add(“A”).HashSet extends AbstractSet and implements the Set interface.add(“B”). In addition to the operations inherited from Collection. ts.util. System. hs. hs. It creates a collection that uses a hash table for storage.add(“A”).C.*.println(hs). Lists may contain duplicate elements. class TreeSetDemo { public static void main(String args[]) { TreeSet ts = new TreeSet().out. hs. System.E. hs. } } The LinkedHashSet extends HashSet and maintains a linked list of entries in the set in the order in which they were inserted.add(“C”). ts.add(“E”).println(ts).add(“C”).add(“F”). import java.

which is generally the better-performing implementation. List fixes several minor API deficiencies in Vector. you're already familiar with the general flavor of List. Also. For consistency's sake. 372 . Comparison to Vector If you've used Vector.elementAt(k)). the method add(int. List Iteration: Extend Iterator semantics to take advantage of the list's sequential nature. The Vector equivalent is: gift.setElementAt(v. 5). which replaces insertElementAt(Object. The List equivalent is: gift.elementAt(j). and LinkedList which offers better performance under certain circumstances.setElementAt("golden rings". The Vector equivalent is: v.get(k))). i). it becomes apparent that shorter names are highly desirable. E). ArrayList. You may already have noticed that the set method. v.set(i.times(v. Vector has been retrofitted to implement List. int). Search: Search for a specified object in the list and return its numerical position. reverses the order of the arguments so that they match the corresponding array operation. "golden rings"). The Java platform contains two general-purpose List implementations. which replaces the Vector method setElementAt. The List equivalent is: v.get(j). Range-view: Perform arbitrary range operations on the list.times(v.• • • • Positional Access: Manipulate elements based on their numerical position in the list. Consider the following assignment statement: a[i] = a[j]. When you consider that these two operations are the List analogue of square brackets for arrays.set(5. also reverses the order of the arguments. Consider this assignment statement: gift[5] = "golden rings". Commonly used Vector operations such as elementAt and setElementAt.times(a[k]). have been given much shorter names.

Like the Set interface. Thus. The search operations indexOf and lastIndexOf behave exactly like the identically named operations in Vector. int j) { E tmp = a.get(i). tmp). Here's a non-destructive form of this idiom.addAll(list2). This call is the positional access analogue of Collection's addAll operation. The add and addAll operations always append the new element(s) to the end of the list. List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. a. lastIndexOf(setSize) have been replaced by a single range-view operation (subList).set(i. which produces a third List consisting of the second list appended to the first: List<Type> list3 = new ArrayList<Type>(list1). The set and remove operations return the old value that is being overwritten or removed. Here's a little method to swap two indexed values in a List: public static <E> void swap(List<E> a. The addAll operation inserts all of the elements of the specified Collection starting at the specified position.addAll(list2). Positional Access and Search Operations The basic positional access operations (get. takes advantage of ArrayList's standard conversion constructor.set(j. list3. the following idiom concatenates one list to another: list1. add and remove) behave just like their longernamed counterparts in Vector (elementAt. setElementAt. the Vector counterparts (setElementAt and removeElementAt) return nothing (void). a. Two List objects are equal if they contain the same elements in the same order. assuming you're already familiar with them from Collection.get(j)).The various range operations in Vector (indexOf. set. which is far more powerful and consistent. in its non-destructive form. Collection Operations The operations inherited from Collection all do about what you'd expect them to do. insertElementAt and removeElementAt) with one noteworthy exception. The elements are inserted in the order they are returned by the specified Collection's iterator. a. The remove operation always removes the first occurrence of the specified element from the list. } 373 . Note that the idiom. int i.

add(a). i--) swap(list. regardless of its implementation type. randomly permutes the specified List using the specified source of randomness. } } An example that demonstrates the use of various algorithms 374 . Collections. Here's another polymorphic algorithm that uses the swap method above: public static void shuffle(List<?> list. } This algorithm. for (String a : args) { list. which is included in the Java platform's Collections class.shuffle(list). } Collections.util. you get the following tiny program. new Random()). in that it doesn't implement the (optional) add and remove operations: Arrays are not resizable.out.asList(args).util. i .size().out.Of course there's one big difference.*.asList and calling the library version of shuffle that uses a default source of randomness. i > 1. Random rnd) { for (int i = list.nextInt(i)). Taking advantage of Arrays. public class Shuffle { public static void main(String args[]) { List<String> list = new ArrayList<String>(). public class Shuffle { public static void main(String args[]) { List<String> list = Arrays. repeatedly swapping a randomly selected element into the current position. assuming an unbiased source of randomness) and fast (requiring exactly list. The resulting List is not a general-purpose List implementation. This method does not copy the array.*.println(list). Unlike most naive attempts at shuffling. it's fair (all permutations occur with equal likelihood.size()-1 swaps). rnd. This is a polymorphic algorithm: It swaps two elements in any List. The Arrays class has a static factory method called asList that allows an array to be viewed as a List. System.println(list). and vice-versa.shuffle(list. whose behavior is identical to the previous program: import java. System. It's a bit subtle: It runs up the list from the bottom. Changes in the List write through to the array.1. The following program uses this algorithm to print the words in its argument list in random order: import java. } } We can make this program even shorter and faster.

out. System. display(array).sort(al.add(new Integer(20)).print(li. } //display. //Sort list using comparator Collections.println(“List sorted in reverse:”).iterator(). Collections.add(new Integer(-8)).max(al)). } } An example that shows the use of Arrays class import java.out.out. System. for(int i=0.r). while(itr.import java. System.print(li.println().min(al)). class AlgorithmDemo { public static void main(String args[]) { ArrayList al = new ArrayList(). display(array). i++) { array[i] = -3 * i. class ArraysDemo { public static void main(String args[]) { //allocate and initialize array int array[] =new int[10].shuffle(al).util. al.add(new Integer(8)). 375 . } System.reverseOrder().println(“List shuffled:”). //display randomized list itr = al. al.print(“Sorted:”). System.out. //create a reverse order Comparator Comparator r = Collections. while(itr.sort(array). al. System.out. al.println().out.hasNext()) { System.out.out. } System.iterator().println(“Maximum:”+Collections.next()+ “ ”).hasNext()) { System.*. i< 10. //Get iterator Iterator itr = al.println(“Minimum:”+Collections.print(“Original contents:”).util.next()+ “ ”). sort and display System.*. Arrays.out.out.add(new Integer(-20)).

) { Type t = i. and obtain the current position of the iterator.println().print(index). //binary search for –9 System. whereas the latter refer to the element after the cursor. whereas next moves it forwards. The previous operation moves the cursor backwards. int index = Arrays.i++) { System. } System. i.6. display(array). } } The output is as follows: Original contents : 0 –3 –6 –9 –12 –15 –18 –21 –24 –27 Sorted : -27 –24 –21 –18 –15 –12 –9 –6 –3 0 After fill: -27 –24 –1 –1 –1 –1 –9 –6 –3 0 After sorting again: -27 –24 –9 –6 –3 –1 –1 –1 –1 0 The value –9 is at location 2 Iterators The Iterator returned by List's iterator operation returns the elements of the list in proper sequence. System.listIterator(list.length.-9).out.hasPrevious().2.binarySearch(array. System. display(array). //sort and display Arrays. } static void display(int array[]) { for(int i= 0 .i<array.out.//fill and display Arrays. 376 . Here's the standard idiom for iterating backwards through a list: for (ListIterator<Type> i = list. The three methods that ListIterator inherits from Iterator (hasNext.print(“The value –9 is at location:”). The hasPrevious and the previous operations are exact analogues of hasNext and next. modify the list during iteration.size()).out.out.-1).fill(array.sort(array). that allows you to traverse the list in either direction.print(“After fill:”). called a ListIterator.out. The former operations refer to the element before the (implicit) cursor.print(“After sorting again:”). System. List also provides a richer iterator.out.print(array[i]+ “ ").previous(). next. and remove) do exactly the same thing in both interfaces.

The first call to previous returns the same element as the last call to next. // Object not found } 377 . and a call to nextIndex when the cursor is after the final element returns list. but you have to be a bit careful.equals(i. the cursor is always between two elements. In a list of length n. It should also come as no surprise that the number returned by nextIndex is always one greater than the number returned by previousIndex. Intuitively speaking. i. the form with an int argument returns a ListIterator positioned at the specified index.previousIndex(). ) { if (o==null ? i. The index refers to the element that would be returned by an initial call to next. Calls to next and previous can be intermixed.next())) { return i. The figure below shows the five possible cursor positions in a list containing four elements. These calls are typically used either to report the position where something was found or to record the position of the ListIterator so that another ListIterator with identical position can be created.indexOf: public int indexOf(E o) { for (ListIterator<E> i = listIterator().. The form with no arguments returns a ListIterator positioned at the beginning of the list. from the gap before the first element to the gap after the last one.next()==null : o. Similarly. and previousIndex returns the index of the element that would be returned by a subsequent call to previous. It should come as no surprise that the nextIndex method returns the index of the element that would be returned by a subsequent call to next. there are n+1 valid values for index.size(). the first call to next after a sequence of calls to previous returns the same element as the last call to previous. An initial call to previous would return the element whose index was index-1. the one that would be returned by a call to previous and the one that would be returned by a call to next.} . } } return -1. To make all of this concrete. This implies the behavior of the two boundary cases: a call to previousIndex when the cursor is before the initial element returns -1. inclusive. The n+1 valid index values correspond to the n+1 gaps between elements.hasNext(). Note the argument to listIterator in the preceding idiom.. here's a possible implementation of List. The List interface has two forms of the listIterator method. from 0 to n.

. i. List<E> newVals) { for (ListIterator<E> i = s. The reason is that i.){ if (val==null ? i. i++) { ..listIterator(). The Iterator interface provides the remove operation to remove from the Collection the last element returned by next. } } } The only bit of trickiness in this example is the equality test between val and i.equals(i. E val.hasNext(). for (E e : newVals) i. inclusive. } 378 .next. E newVal) { for (ListIterator<E> i = s. exclusive. subList(int fromIndex. this operation removes the last element returned by next or previous. returns a List view of the portion of this list whose indices range from fromIndex. The following polymorphic algorithm uses set to replace all occurrences of one specified value with another: public static <E> void replace(List<E> s.remove(). The add method inserts a new element into the list. We have to special-case an val value of null in order to prevent a NullPointerException. int toIndex). The ListIterator interface provides two additional operations to modify the list: set and add. immediately before the current cursor position.listIterator().nextIndex() would return the index of the element that we are about to examine. For ListIterator. E val.Note that the indexOf method returns i.set(newVal). i < toIndex.previousIndex() though it is traversing the list in the forward direction. to toIndex. i.hasNext().equals(i. and we want to return the index of the element that we just examined.next())) { i.add(e).next()==null : val. The set method overwrites the last element returned by next or previous with the specified element. } } } Range-View Operation The range-view operation. ) { if (val==null ? i. This method is illustrated in the following polymorphic algorithm to replace all occurrences of a specified value with the sequence of values contained in the specified list: public static <E> void replace(List<E> s. This half-open range mirrors the typical for loop: for (int i = fromIndex.next())) { i.next()==null : val.

Note that the above idioms return the index of the found element in the subList.parseInt(args[1]).util. int cardsPerHand = Integer. such as the replace and shuffle examples above. import java. the following idiom removes a range of elements from a list: list.clear().As the term view implies. That is to say. return hand. deckSize). Here's a program using the dealHand method in combination with Collections. For example. Here's a polymorphic algorithm whose implementation uses subList to deal a hand from a deck. For many common List implementations.size(). The program takes two command line arguments: the number of hands to deal and the number of cards in each hand. handView. so changes in the former List are reflected in the latter. List<E> handView = deck. public static <E> List<E> dealHand(List<E> deck. the returned List is backed by the List on which subList was called.indexOf(o). This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). List<E> hand = new ArrayList<E>(handView). toIndex). not the index in the backing List.n. 379 . the performance of removing elements from the end of the list is substantially better than that of removing elements from the beginning. works with the List returned by subList.shuffle to generate hands from a normal 52-card deck.clear(). toIndex). Any polymorphic algorithm that operates on a List.subList(fromIndex. int j = list.*. Any operation that expects a List can be used as a range operation by passing a subList view instead of a whole List.subList(fromIndex.lastIndexOf(o). int n) { int deckSize = deck.subList(deckSize .parseInt(args[0]). } Note that this algorithm removes the hand from the end of the deck. such as ArrayList. toIndex).subList(fromIndex. class Deal { public static void main(String[] args) { int numHands = Integer. Similar idioms may be constructed to search for an element in a range: int i = list. it returns a new List (the "hand") containing the specified number of elements taken from the end of the specified List (the "deck"). The elements returned in the hand are removed from the deck.

cardsPerHand)). it's highly recommended that you use the List returned by subList only as a transient object: to perform one or a sequence of range operations on the backing List. "clubs"}."8". the greater the probability that you'll compromise it by modifying the backing List directly or through another sublist object. 4 of spades. 380 . "9". "diamonds". king of diamonds] [4 of diamonds."10". 5 of spades. 2 of diamonds. 9 of clubs] [8 of spades. 3 of spades. 3 of hearts. } } Collections."3". List<String> deck = new ArrayList<String>().// Make a normal 52-card deck String[] suit = new String[] {"spades". The semantics of the List returned by subList become undefined if elements are added to or removed from the backing List in any way other than via the returned List. 6 of clubs. for (int i = 0."5".add(rank[j] + " of " + suit[i]). String[] rank = new String[] {"ace". "hearts". jack of spades.length."jack". j++) { deck.shuffle(deck). The longer you use the sublist instance."7". ace of spades. List Algorithms Most of the polymorphic algorithms in the Collections class apply specifically to List. queen of diamonds. for (int i=0. } } } Running the program produces the following output: java Deal 4 5 [8 of hearts. ace of clubs."king"}. some care must be exercised when using it. i<numHands. 6 of diamonds. Thus."2". i++) { for (int j = 0. i <suit.length."6". Note that it is legal to modify a sublist of a sublist and to continue using the original sublist (though not concurrently).out. i++) { System."4"."queen". Here's a summary of these algorithms. ace of hearts] Although the subList operation is extremely powerful. queen of hearts] [7 of spades. jack of hearts. Having all these algorithms at your disposal makes it very easy to manipulate lists.println(dealHand(deck. j <rank.

Besides basic Collection operations. stable sort. order elements in a FIFO (first-in-first-out) manner. The offer method. Each Queue method exists in two forms: one throws an exception if the operation fails. swap: Swaps the elements at specified positions in in a List.8 The Queue Interface A Queue is a collection for holding elements prior to processing. which Queue inherits from Collection. but not necessarily. reverse: Reverses the order of the elements in a List. Whatever ordering is used.) shuffle: Randomly permutes the elements in a List. which is intended solely for use on bounded queues. The add method. the head of the queue is the element that would be removed by a call to remove or poll. binarySearch: Searches for an element in an ordered List using the binary search algorithm. all new elements are inserted at the tail of the queue. In a FIFO queue. and inspection operations.           sort: Sorts a List using a merge sort algorithm. inserts an element unless it would violate the queue's capacity restrictions. which provides a fast. copy: Copies the source List into the destination List. replaceAll: Replaces all occurrences of one specified value with another. Other kinds of queues may use different placement rules. lastIndexOfSubList: Returns the index of the last sublist of one List that is equal to another. removal. the other returns a special value (either null or false. differs from add only in that it indicates failure to insert an element by returning false. which order elements according to a their values. fill: Overwrites every element in a List with the specified value. (A stable sort is one that does not reorder equal elements. 16. in which case it throws IllegalStateExcepion. 381 . Among the exceptions are priority queues. rotate: Rotates all of the elements in a List by a specified distance. indexOfSubList: Returns the index of the first sublist of one List that is equal to another. queues provide additional insertion. depending on the operation). Every Queue implementation must specify its ordering properties. The regular structure of the interface is illustrated in the following table: Queue Interface Structure Throws exception Returns special value add(e) Insert Remove remove() Examine element() offer(e) poll() peek() Queues typically.

i >= 0. In the following example program. element throws NoSuchElementException while peek returns false.isEmpty()) result. Queue implementations generally do not define element-based versions of the equals and hashCode methods but instead inherit the identity-based versions from Object. Then the values are removed from the queue and printed at one second intervals. 382 . i--) queue. Thread. as null is used as a special return value by the poll and peek methods.add(queue. a queue is used to implement a countdown timer.parseInt(args[0]).util. Under these circumstances. The LinkedList implementation (which was retrofitted to implement Queue) is an exception. while (!queue. but you should refrain from taking advantage of this. in descending order. but do not remove. but it illustrates the use of a queue to store elements prior to subsequent processing: import java. for (int i = time. List<E> result = new ArrayList<E>(). Queue implementations generally do not allow insertion of null elements.sleep(1000). The element and peek methods return.*.out. The program is artificial in that it would be more natural to do the same thing without using a queue.remove()). while(!queue. The remove and poll methods differ in their behavior only when the queue is empty. For historical reasons. They differ from one another in precisely the same fashion as remove and poll: if the queue is empty. Again this program is artificial.add(i). but it illustrates the behavior of priority queues: static <E> List<E> heapSort(Collection<E> c) { Queue<E> queue = new PriorityQueue<E>(c). in that there is no reason to use it in favor of the sort method provided in Collections. } } } In the following example. The queue is preloaded with all the integer values from a number specified on the command line to zero. public class Countdown { public static void main(String[] args) throws InterruptedException { int time = Integer.println(queue.isEmpty()) { System.remove()). remove throws NoSuchElementException. while poll returns null. Queue<Integer> queue = new LinkedList<Integer>(). it permits null elements. a priority queue is used to sort a collection of elements.The remove and poll methods both remove and return the head of the queue. Exactly which element gets removed is a function of the queue's ordering policy. the head of the queue.

import java.add(“B”).C. ll. } } The output of this program is shown here Original Contents ll after ll after contents of ll : [F. ll. System.A.set(1. class LinkedListDemo { public static void main(String args[]) { //create a linked list LinkedList ll = new LinkedList(). 383 . //get and set value Object val = ll. The following program illustrates several methods supported by LinkedList.add(“A”).E] of ll after deletion: [A. System. //add elements to linked list ll.out. “A2”).D.addLast(“E”).println(“ll after change:” + ll).(String)val+ “changed”).removeFirst().util.remove(“F”). System.addFirst(“F”).9 The Map Interface A Map is an object that maps keys to values.D. A map cannot contain duplicate keys: Each key can map to at most one value. //remove first and last elements ll.println(“ll after deleting first and last:”+ ll).*. ll.add(1. ll.out. ll.get(1).Dchanged] 16.add(“D”).E] deleting first and last: [B.out.out. ll.println(“Original contents of ll:”+ll).} return result. ll. ll.add(“C”). //remove elements from linked list ll.B.B. System.println(“Contents of ll after deletion:” + ll).remove(2). ll.removeLast().D] change: [B.

m. and LinkedHashMap. Map allows you to iterate over keys. Their behavior and performance are precisely analogous to HashMap. // Initialize frequency table from command line for (String a : args) { Integer freq = m. values.) Here are the major differences: • • • provides Collection views instead of direct support for iteration via Enumeration objects. as the key is the primary access mechanism for a Hashtable. That argument is a conditional expression that has the effect of setting the frequency to one if the 384 . import java. you're already familiar with the general flavor of Map. Hashtable was retrofitted to implement Map.println(m. Map provides a safe way to remove entries in the midst of iteration. System. which returns true if the Hashtable contains a given value. The Map interface eliminates this source of confusion by renaming the method containsValue. this improves the consistency of the interface: containsValue parallels containsKey. } System. The frequency table maps each word to the number of times it occurs in the argument list. Here's a program to generate a frequency table of the words found in its argument list. TreeMap. TreeMap. Hashtable did not. size. (freq == null ? 1 : freq + 1)). } } The only thing tricky about this program is the second argument of the put statement. while Hashtable is a concrete implementation. Integer>(). Also. containsKey.size() + " distinct words:").*. and LinkedHashMap. public class Freq { public static void main(String args[]) { Map<String. Also. containsValue. get. Map fixes a minor deficiency in the Hashtable interface. Map Finally. Given its name.println(m). Hashtable does not provide the third option. and isEmpty) behave exactly like their counterparts in Hashtable. Comparison to Hashtable If you've used Hashtable.util.put(a. Integer> m = new HashMap<String. Map Interface Basic Operations The basic operations (put.get(a). Hashtable has a method called contains. or key-value pairs. you'd expect this method to return true if the Hashtable contained a given key. Collection views greatly enhance the expressiveness of the interface. (Of course Map is an interface.out.out.The Java platform contains three general-purpose Map implementations: HashMap.

is=2. all Map implementations provide constructors that take a Map object and initialize the new Map to contain all the key-value mappings in the specified Map. to=3. more subtle use. be=1. up=1} Similarly. In addition to its obvious use of dumping one Map into another. The following one-liner creates a new HashMap initially containing all of the same key-value mappings as m: Map<K. me=1. Making this fourcharacter change causes the program to generate the following output from the same command line: 8 distinct words: {be=1. it=2. Doing so results in the following output: 8 distinct words: {if=1. it=2. if=1. me=1. V>(m). is=2. This standard Map conversion constructor is entirely analogous to the standard Collection constructor: It allows the caller to create a Map of a desired implementation type that initially contains all of the mappings in another Map. me=1. delegate=1} This flexibility provides a potent illustration of the power of an interface-based framework. it=2. Try running this program with the command: java Freq if it is to be it is up to me to delegate The program yields the following output: 8 distinct words: {to=3. is=2} Suppose you'd prefer to see the frequency table in alphabetical order. Like the Set and List interfaces. if=1. By convention. Two Map instances are equal if they represent the same key-value mappings. it has a second.word has never been seen before or one more than its current value if the word has already been seen. regardless of the other Map's implementation type. up=1. suppose you have a Map. be=1. named m. For example. you could make the program print the frequency table in the order the words first appear on the command line simply by changing the implementation type of the map to LinkedHashMap. V> copy = new HashMap<K. The putAll operation is the Map analogue of the Collection interface's addAll operation. to=3. Map Interface Bulk Operations The clear operation does exactly what you think it does: it removes all the mappings from the Map. delegate=1. up=1. Map strengthens the requirements on the equals and hashCode methods so that two Map objects can be compared for logical equality without regard to their implementation types. All you have to do is change the implementation type of the Map from HashMap to TreeMap. delegate=1. 385 .

result. in combination with the Map conversion constructor. i. Here's a static factory method demonstrating this technique: static <K.println(key).util do. assuming that the backing map supports element removal to begin with.keySet()) System. provides a neat way to implement attribute map creation with default values. values: The Collection of values contained in the Map.) 386 . return result. V> Map<K. There's no reason that a Map can't always return the same object each time it is asked for a given Collection view. removeAll. Here's an example illustrating the standard idiom for iterating over the keys in a Map with a for-each construct: for (KeyType key : m. V>(defaults). as well as the Iterator.keySet().remove(). At first. With all three Collection views. many people worry that these idioms may be slow because the Map has to create a new Collection instance each time a Collection view operation is called.putAll(overrides). V>defaults. (Yet again. Map<K. as multiple keys can map to the same value. This Collection is not a Set. and with an iterator: // Filter a map based on some property of its keys for (Iterator<Type> i=m. V> result = new HashMap<K.isBogus()) i. retainAll. V> overrides) { Map<K.Suppose a Map is used to represent a collection of attribute-value pairs. } Collection Views The Collection view methods allow a Map to be viewed as a Collection in these ways:   keySet: the Set of keys contained in the Map.next(). This is precisely what all the Map implementations in java. the putAll operation. V> newAttributeMap( Map<K.out.hasNext(). this assumes that the backing Map supports element removal. ) if (i. and clear operations.remove operation.iterator(). The Collection views support element removal in all its many forms: the remove. The Collection views provide the only means to iterate over a Map. calling an Iterator's remove operation removes the associated entry from the backing Map.

and two sets representing required attributes and permissible attributes.keySet().) The following snippet determines whether the attribute map conforms to these constraints and prints a detailed error message if it doesn't: static <K. System. Fancy Uses of Collection Views: Map Algebra When applied to the Collection views.. that is. } return valid.keySet). V> attrMap. and it's unnecessary for the entrySet view. missing. } if (!permittedAttrs.equals(m2.containsAll(requiredAttrs)) { Set<K> missing = new HashSet<K>(requiredAttrs). don't modify the backing Map. Set<K>permittedAttrs) { boolean valid = true.out. Here are a few that do.out. if(!attrs. All the idioms presented thus far have been nondestructive. Set<K> requiredAttrs.println("Illegal attributes: " + illegal). as the backing Map's put and putAll provide the same functionality.. valid = false. A similar idiom gets you the common values. removeAll and retainAll) are a surprisingly potent tool.keySet()).The Collection views do not support element addition under any circumstances. (The permissible attributes include the required attributes.keySet().containsAll(attrs)) { Set<K> illegal = new HashSet<K>(attrs). commonKeys.retainAll(m2.keySet())) { . illegal. } Suppose you have a map that represents a collection of attribute-value pairs.removeAll(permittedAttrs). Set<K> attrs = attrMap. V> boolean validate(Map<K.removeAll(attrs). the bulk operations (containsAll.println("Missing attributes: " + missing). Suppose that you want to know whether two Map objects contain mappings for all the same keys: if (m1. } Suppose that you want to know all the keys common to two Map objects: Set<KeyType>commonKeys = new HashSet<KeyType>(m1. valid = false. It would make no sense for the keySet and values views. System. Suppose that you want to remove all the key-value pairs that one Map has in common with another: 387 .

it makes a temporary copy of the Map.removeAll(m2.removeAll(Collections. and it removes from the temporary copy all entries whose (manager) value is a key in the original Map. m.keySet(). represent precisely the employees that we're looking for.sort(l). Suppose you want to remove from one Map all the keys that have mappings in another: m1. Now suppose you want to know who all the "individual contributors" (or nonmanagers) are. a static factory method that returns an immutable Set with the single. you may have a bunch of employees whose managers no longer work for the company (if any of Simon's direct-reports were themselves managers). This example is a bit tricky. The keys in the temporary copy. Employee>(managers). The following code tells you all of the employees whose manager no longer works for the company: Map<Employee.values(). then.removeAll(managers.removeAll(managers.values(). 16. Once you've done this.. Note that this idiom makes use of Collections. What happens when you start mixing keys and values in the same bulk operation? Suppose that you have a Map.keySet().10 Object Ordering A List l may be sorted as follows: Collections. Thus. managers. Suppose that you want to fire all the employees who report directly to some manager.entrySet(). First. the remaining entries in the temporary Map comprise all the entries from the original Map whose (manager) values are no longer employees.. Employee> m = new HashMap<Employee.values()). We'll be deliberately vague about the types of the key and the value objects.singleton. Remember that the original Map has an entry for each employee. that maps each employee in a company to the employee's manager. so long as they're the same. .singleton(simon)). It doesn't matter.keySet()). specified element.keySet()).entrySet()). The following snippet tells you exactly what you want to know: Set<Employee> individualContributors = new HashSet<Employee>(managers.removeAll(m2. 388 . Simon: Employee simon = . Set<Employee> slackers = m. individualContributors.keySet()).m1. managers.

Collections. The Comparable interfaces provides a natural ordering for a class. it will be sorted into chronological order. BigDecimal Boolean File String Date CollationKey Natural Ordering UnSigned numerical Signed numerical Boolean. The compareTo method compares the receiving object with the specified object and returns a negative integer. or greater than the specified object. Although elements of different types be mutually comparable. or a positive integer as the receiving object is less than. lastName. Collections. The following table summarizes some of the more important Java platform classes that implement Comparable: Classes Implementing Comparable Class Character Byte. which allows objects of that class to be sorted automatically. Long.*. Writing Your Own Comparable Types The Comparable interface consists of a single method: public int compareTo(T o).If the list consists of String elements.FALSE < Boolean.sort will throw a ClassCastException. Similarly. Double. public final class Name implements Comparable<Name> { private final String firstName.sort(list) will throw a ClassCastException . Elements that can be compared to one another are called mutually comparable. The following class representing a person's name implements Comparable: import java. it will be sorted into alphabetical order. equal to. Float. How does this happen? String and Date both implement the Comparable interface. the method throws a ClassCastException. zero. If it consists of Date elements. none of classes listed here permit interclass comparison. Short. Integer.TRUE System-dependent lexicographic on path name Lexicographic Chronological Locale-specific lexicographic If you try to sort a list whose elements do not implement Comparable. if you try to sort a list whose elements cannot be compared to one another. If the specified object cannot be compared to the receiving object. BigInteger. 389 . This is all you really need to know about the Comparable interface if you just want to sort lists of comparable elements or to create sorted collections of them.util.

These collections will break if you modify their elements or keys while they're in the collection. the class is somewhat limited: It doesn't support middle names. Name n = (Name) o. } public int compareTo(Name n) { int lastCmp = lastName.compareTo(n. so that none of the other methods will ever throw a NullPointerException. Both of these behaviors are required by the general contracts of the respective methods. it demands both a first and a last name. return n. All other things being equal. it illustrates several important points: • • • • objects are immutable.hashCode(). (Equal objects must have equal hash codes. This ensures that all Name objects are well formed. this. This is essential for any class that redefines the equals method.lastName).firstName)). Nonetheless. The constructor checks its arguments for null. or of an inappropriate type. } public String lastName() { return lastName. immutable types are the way to go. } public int hashCode() { return 31*firstName. String lastName) { if (firstName == null || lastName == null) { throw new NullPointerException(). } } To keep the example short. especially for objects that will be used as elements in Sets.equals(firstName) && n.lastName = lastName. The compareTo method throws a runtime exception under these circumstances. return (lastCmp != 0 ? lastCmp : firstName. The hashCode method is redefined. } public boolean equals(Object o) { if (!(o instanceof Name)) return false.firstName = firstName.lastName.) The equals method returns false if the specified object is null. or as keys in Maps.equals(lastName).compareTo(n. and it is not internationalized in any way.public Name(String firstName.hashCode() + lastName. } public String toString() { return firstName + " " + lastName. } public String firstName() { return firstName.firstName. } this. Name 390 .

This is always a good idea. you're done: you just return the result. If the most significant parts are equal. List<Name> names = Arrays. the last name). First. The various collection types' toString methods depend on the toString methods of their elements. here's what it prints: [Oscar Grouch. Karl Marx] There are four restrictions on the behavior of the compareTo method. If there were more parts. you compare the most significant part of the object (in this case. these restrictions ensure that the natural ordering is a total order on the objects of a class that implements it. Technically speaking. This is exactly what you want in a natural ordering. } } If you run this program. you'd proceed in the obvious fashion. you go on to compare the next-most-significant parts. In this case. Attempting to sort a list of objects that violate these restrictions has undefined behavior. keys and values. It would be very confusing if the natural ordering were unnatural! Take a look at how compareTo is implemented. new Name("Groucho".sort(names).• The toString method has been redefined to print the Name in human-readable form. you can just use the natural ordering of the part's type. let's talk a bit more about Name's compareTo method. which represents equality. "Marx"). especially for objects that are going to get put into collections. where last names take precedence over first names.*. Collections. If the comparison results in anything other than zero.out. new Name("Oscar".println(names). Just to show that it all works.asList(nameArray). John Lennon. because it's quite typical. so read the documentation for Comparable if you're writing a class that implements it. and the natural (lexicographic) ordering is exactly what's called for. System. new Name("Karl". there are only two parts: first name and last name. comparing parts until you found two that weren't equal or you were comparing the least-significant parts. which we won't go over now because they're fairly technical and boring and are better left in the API documentation. 391 . "Grouch") }. "Lennon"). Often. this is necessary to ensure that sorting is well-defined. Since this section is about element ordering. "Marx"). In this case. It's really important that all classes that implement Comparable obey these restrictions. public static void main(String[] args) { Name nameArray[] = { new Name("John". here's a program that builds a list of names and sorts them: import java. It implements the standard name-ordering algorithm. Groucho Marx.util. at which point you'd return the result of the comparison. the part is a String.

.hireDate(). public int number() { . the compare method throws a ClassCastException. Writing a compare method is nearly identical to writing a compareTo method.. The compare method has to obey the same four technical restrictions as Comparable's compareTo method. equal to.hireDate()).Comparators What if you want to sort some objects in an order other than their natural order? Or what if you want to sort some objects that don't implement Comparable? To do either of these things. or a positive integer as the first argument is less than. . public Date hireDate() { .. or greater than the second. The compare method compares its two arguments. If either of the arguments has an inappropriate type for the Comparator.. Here's a program that will produce the required list: import java. the boss has asked us for a list of employees in order of seniority.util.. public static void main(String[] args) { 392 . zero. } }.. // Employee Database static final Collection<Employee> employees = .. but not much. } Comparable<Employee> { } } } Let's assume that the natural ordering of Employee instances is Name ordering (as defined in the previous example) on employee name.. class EmpSort { static final Comparator<Employee> SENIORITY_ORDER = new Comparator<Employee>() { public int compare(Employee e1. Much of what was said about Comparable applies to Comparator as well. Like the Comparable interface.*.compareTo(e1. This means that we have to do some work. the Comparator interface consists of a single method: int compare(T o1. T o2). you'll need to provide a Comparator. Unfortunately. returning a negative integer. Suppose that you have a class called Employee: public class Employee implements public Name name() { . Employee e2) { return e2. except that the former gets both objects passed in as arguments. an object that encapsulates an ordering.. . for the same reason: a Comparator must induce a total order on the objects it compares..

There is one negative int that remains negative when negated. The second will be seen as a duplicate element and will be ignored. SENIORITY_ORDER). but it does have one deficiency: it cannot be used to order a sorted collection. When you're sorting a List.number() == e2.out. rather than vice versa. In other words.hireDate()). The reason is that the employee who was hired most recently is least senior: sorting in order of hire date would put the list in reverse seniority order. it's fatal.println(e). 393 .compareTo(r2. If you use this Comparator to insert multiple employees hired on the same date into a TreeSet. Note that the Comparator passes the hire date of its second argument to its first.MIN_VALUE == Integer.number() ? 0 : 1)). if (dateCmp != 0) return dateCmp. but when you're using the Comparator to order a sorted collection. any two employees who were hired on the same date will compare as equal. simply tweak the Comparator so that it produces an ordering that is compatible with equals.hireDate(). This means that this comparator equates objects that the equals method does not. The Comparator in the program is reasonably straightforward.number() ? -1 : (e1. The way to do this is to do a two-part comparison (as we did for Name).MIN_VALUE The Comparator in the preceding program works fine for sorting a List. such as TreeSet. where the first part is the one that we're interested in (in this case. the employee number is the obvious attribute. tweak it so that the only elements that are seen as equal when using compare are those that are also seen as equal when compared using equals.sort(e. only the first one will be added to the set. this doesn't matter.hireDate(). In particular. because it generates an ordering that is not compatible with equals. Another technique that people sometimes use to achieve this effect is to maintain the argument order but to negate the result of the comparison: //Don't do this!! return -r1. It relies on the natural ordering of Date applied to the values returned by the hireDate accessor method.number() < e2. as the latter is not guaranteed to work! The reason for this is that the compareTo method can return any negative int if its argument is less than the object on which it is invoked.compareTo(e1. Employee e2) { int dateCmp = e2. Collections. In this case. To fix this problem. You should always use the former technique in favor of the latter. the hire date). System. return (e1.} } List<Employee>e = new ArrayList<Employee>(employees). Here's the Comparator that results: static final Comparator<Employee> SENIORITY_ORDER = new Comparator<Employee>() { public int compare(Employee e1. Strange as it may seem. -Integer.hireDate()). and the second part is an attribute that uniquely identifies the object.

ts. subtle bugs.r2.bstr. } One last note: You might be tempted to replace the final return statement in the Comparator with the simpler: return r1.out.next().println(element + “ ”).add(“A”). as the signed integer type is not big enough to represent the difference of two arbitrary signed integers.compareTo(astr).*. } 394 .empNumber(). The resulting comparator violates one of the four technical restrictions that we keep talking about (transitivity) and produces horrible.empNumber() .add(“B”). //A reverse comparator for Strings class MyComp implements Comparator { public int compare(Object a. //display elements while(i. people get burned by it. //add elements to tree set ts.util. ts. ts. ts.add(“C”). This is not a purely theoretical concern. i . Object b) { String astr.add(“E”).add(“F”).add(“D”). Don't do it unless you're absolutely sure that no one will ever have a negative employee number! This trick does not work in general. If i is a large positive integer and j is a large negative integer.hasNext()) { Object element = i.j will overflow and will return a negative integer.iterator(). } //no need to override equals } class CompDemo { public static void main(String args[]) { //create a tree set TreeSet ts = new TreeSet(new MyComp()).}. //Get an iterator Iterator i = ts. ts. //reverse comparison return bstr. astr = (String)a. System. An example of using Comparator: import java. bstr = (String)b.

it also provides a constructor that takes a SortedSet and returns a new TreeSet containing the same elements sorted according to the same criterion. the tree is now sorted in the reverse order F E D C B A 16. Endpoints: Returns the first or last element in the sorted set.out. to sort the new TreeSet according to the same criterion (comparator or natural ordering). it returns a set that sorts its elements according to their natural order. It would have been better to check dynamically if the specified collection were a SortedSet instance. the toString method of the Java platform's SortedSet implementations returns a string containing all the elements of the sorted set. sorted according to the elements' natural order or according to a Comparator provided at SortedSet creation time. As the following output shows. Note that it is the compile-time type of the argument. and if so. If null is passed to this constructor. if any. 395 . order. this constructor creates an instance that sorts its elements according to their natural order. • Although the interface doesn't guarantee it. all general-purpose Collection implementations provide a standard conversion constructor that takes a Collection. Comparator access: Returns the Comparator.11 The SortedSet Interface A SortedSet is a Set that maintains its elements in ascending order. the SortedSet interface provides operations for: • • • Range view: Allows arbitrary range operations on the sorted set. SortedSet implementations also provide by convention a constructor that takes a Comparator and returns an empty set sorted according to the specified Comparator. Standard Constructors By convention. Because TreeSet took the approach that it did. SortedSet implementations are no exception. In TreeSet.} } System. in order. Set Operations The operations that SortedSet inherits from Set behave identically on sorted sets and normal sets with two exceptions: • The Iterator returned by the iterator operation traverses the sorted set in The array returned by toArray contains the sorted set's elements in order. not its runtime type. that determines which of these two constructors is invoked (and whether the sorting criterion is preserved). used to sort the set.println(). In addition to the normal Set operations.

Thus.subSet(from.size()." are contained in the dictionary: count = dictionary.subSet("doorbell". Although it isn't entirely obvious.out. the following one of code tells you how many words between "doorbell" and "pickle. merely request the subSet from lowEndpoint to successor(highEndpoint).subSet("doorbell"." are contained in a SortedSet of strings called dictionary: int count = dictionary.size(). Thus. Thus. A similar trick can be used to print a table telling you how many words begin with each letter: for (char ch = 'a'. as is the case for lists.println(from + ": " + dictionary. Similarly. including its low endpoint but excluding the high one. A range view of a sorted set is really just a window onto whatever portion of the set lies in the designated part of the element space. the following one-liner removes all the elements beginning with the letter "f": dictionary. the successor of a string s in String's natural ordering is s + "\0" (that is. "pickle").clear(). This is feasible because the endpoints of a range view of a sorted set are absolute points in the element space rather than specific elements in the backing collection. but there is one big difference. System. to).subSet("f". it's okay to use range views on sorted sets for long periods of time.valueOf(ch). Rather than indices. which contains both of its endpoints. unlike range views on lists. and vice versa. Range views of a sorted set remain valid even if the backing sorted set is modified directly. using the set's Comparator or the natural ordering of its elements. whichever the set uses to order itself. the endpoints are objects and must be comparable to the elements in the sorted set.size()). String to = String. the range is half open. instead of an open interval. the following one-liner tells you how many words between "doorbell" and "pickle. ch <= 'z'.valueOf(ch++). "pickle\0")." including "doorbell" but excluding "pickle. "g"). ) { String from = String.Range-View Operations The range-view operations are somewhat analogous to those provided by the List interface. like subList. Sorted sets provide three range-view operations. Like subList. s with a null character appended)." including "doorbell" and "pickle. } Suppose that you want to view a closed interval. Changes to the range view write back to the backing sorted set. 396 . The first. takes two endpoints. If the element type allows for the calculation of the successor of a given value in the element space. subSet.

SortedSet<String>> volume2 = dictionary. Endpoint Operations The SortedSet interface contains operations to return the first and last elements in the sorted set. This is a fine way to go one element backward from a point in the interior of a sorted set. which contains neither endpoint. up to but not including the specified object. One thing you'd like to do with a SortedSet is to go into the interior of the set and iterate forward or backward. This method is provided so that sorted sets can be copied into new sorted sets with the same ordering. Comparator Accessor The SortedSet interface contains an accessor method called comparator that returns the Comparator used to sort the set.subSet("doorbell\0".headSet(o).last(). beginning with the specified object and continuing to the end of the backing SortedSet. requiring a lookup for each element returned. The former returns a view of the initial portion of the backing SortedSet.A similar technique can be used to view an open interval. or null if the set is sorted according to the natural order of its elements. the following code allows you to view the dictionary as two disjoint "volumes" (a — m and n — z): SortedSet<String> volume1 = dictionary. "pickle"). 397 .headSet("n"). last allows a workaround for a deficiency in the SortedSet interface. To calculate the number of words between "doorbell" and "pickle. The latter returns a view of the final portion of the backing SortedSet. headSet and tailSet. called (not surprisingly) first and last. both of which take a single Object argument. The following idiom obtains the first element that is less than a specified object o in the elementspace: Object predecessor = ss. there's no easy way to go backwards. but this is very inefficient. The open-interval view from lowEndpoint to highEndpoint is the half-open interval from successor(lowEndpoint) to highEndpoint. Unfortunately.tailSet("n"). The SortedSet interface contains two more range-view operations.size(). Thus. It's easy enough to go forward from the interior: Just get a tailSet and iterate over it. It is used by the SortedSet constructor. It could be applied repeatedly to iterate backward." excluding both: count = dictionary. In addition to their obvious uses.

If null is passed to this constructor. this constructor creates an instance that orders its entries according to their keys' natural order. SortedMap implementations also provide by convention a constructor that takes a Comparator and returns an empty map sorted according to the specified Comparator. Endpoints: Returns the first or the last key in the sorted map. the toString method of the Collection views in all the Java platform's SortedMap implementations returns a string containing all the elements of the view. The arrays returned by the Collection views' toArray operations contain the keys. because Object is a supertype of String. or entries in order. no such relationship exists for instantiations of generic types. It would have been better to check dynamically if the specified Map instance were a SortedMap. The 398 . it returns a set that sorts its mappings according to their keys' natural order. Although it isn't guaranteed by the interface. if any. in order. values. 16. sorted according to the keys' natural order. In TreeMap. and if so.16. In fact. used to sort the map. that determines whether the SortedMap constructor is invoked in preference to the ordinary map constructor. sorted according to the same criterion.13 Relationships Among Generics You might expect that a Stack<Object> is a supertype of a Stack<String>. it also provides a constructor that takes a SortedMap and returns a new TreeMap containing the same mappings as the given SortedMap. Note that it is the compile-time type of the argument. SortedMap implementations are no exception. Standard Constructors By convention. Map Operations The operations that SortedMap inherits from Map behave identically on sorted maps and normal maps with two exceptions: • • The Iterator returned by the iterator operation on any of the sorted map's Collection views traverse the collections in order. not its runtime type. to sort the new map according to the same criterion (comparator or natural ordering). The Map interface provides operations for the normal Map operations and for: • • • Range view: Performs arbitrary range operations on the sorted map. Because TreeMap took the approach that it did. all general-purpose Map implementations provide a standard conversion constructor that takes a Map. Comparator access: Returns the Comparator. or according to a Comparator provided at SortedMap creation time.12 The SortedMap Interface A SortedMap is a Map that maintains its entries in ascending order.

printall(list)... } } List<Object> list = new ArrayList<Object>().out. On the other hand.out.14 Wildcard Types To get around the puzzle posed by the first version of the printAll method you can specify that the argument to printAll is a collection whose element type matches anything. Suppose you would like to write a method that prints out a collection of objects.lack of a super-subtype relationship among instantiations of a generic type when the type arguments possess a super-subtype relationship can make programming polymorphic methods challenging. printall(list).. } } 399 . regardless of the type of objects contained in the collection: public void printAll(Collection<Object> c) { for (Object o : c) { System. //error If you try this you will notice that the last statement produces a compilation error. List<Object> 16. instantiations of generic types related by inheritance for the same type argument are compatible: public void printAll(Collection<Object> c) { for (Object o : c) { System. } } You might choose to create a list of strings and use this method to print all the strings: List<String> list = new ArrayList<String>().println(o).out. written as Collection<?>: public void printAll(Collection<?> c) { for (Object o : c) { System.println(o). //this works is compatible with Collection<Object> because the two types are instantiations of a generic supertype and its subtype and the instantiations are for the same type argument.. Since ArrayList<String> is not subtype of Collection<Object> it cannot be passed as argument to the print method even though the two types are instantiations of the same generic type with type arguments related by inheritance. namely Object. . .println(o).

For example. } This allows drawAll to accept collections of any subclass of Shape. it is also not legal to add an object to a collection of an unknown type that has a bound. However. Static and non-static methods as well as constructors can have type parameters. it cannot be called with Collection<Circle>. T obj) 400 . However.15 Defining and Using Generic Methods Not only types can be parameterized. In summary. methods can be parameterized too. Rectangle. To enable passing a subtype of Shape as the type argument. Bounded wildcards are useful when you have partial knowledge about the type argument.. which is a member of every type.The ? type is known as a wildcard type. It is also possible to constrain a wildcard with a lower bound. since we know that the type argument will be some type of shape. a wildcard with an upper bound is specified as <? extends Type> and stands for all types that are subtypes of Type. this method has limited usefulness: for example. and so on). because ? stands for some unknown type and it's not possible to know if the type of the object you want to add is a subtype of the unknown type. You can also constrain (or bound) the wildcard by a type. Note that just as it is not possible to add an object to a collection of unknown type. suppose you have a class hierarchy consisting of a geometric shape (Shape) and its subtypes (Circle. you could express the type parameter of the shape collection as a wildcard. For example the following Collections class method fills a List of type <? super T> with objects of type T: static <T> void fill(List<? super T> list. A wildcard with a lower bound is specified as <? super Type> and stands for all types that are supertypes of Type. 16. The type parameter section is delimited by angle brackets and appears before the method's return type.. } } Since we have seen that it is not legal to pass in a subtype of Shape (for example. The syntax for declaring method type parameters is the same as the syntax for generics. The drawing program that references these objects invokes a method drawAll to draw a collection of these shapes: public void drawAll(Collection<Shapes> shapes) { for (Shape s: shapes) { s. The only exception is null.draw(). Circle) as the type argument for the generic collection passed to drawAll. you cannot add objects to this collection. You can always extract objects from this collection because the returned type is always guaranteed to be Object. the wildcard should be bounded by the superclass Shape as follows: void drawAll(Collection<? extends Shapes> shapes) { .

The type parameters are inferred from the invocation context. } 401 . i++) { list. i < 10.fill(list. .. The type parameters of generic methods generally are independent of any class or interface-level type parameters.add("").Generic methods allow you to use type parameters to express dependencies among the types of one or more arguments to a method or its return type (or both). as in this invocation of the fill method: public static void main(String[] args) { List<String> list = new ArrayList<String>(10). } String filler = args[0]. One difference between generic types and generic methods is that generic methods are invoked like regular methods.. filler). for (int i = 0. Collections.

1 5 An array creation expression must have either a dimension expression or an initializer. The dollar sign $ and underscore _ are considered Java letters. then a compile-time error is generated. A char is a 16 bit unsigned value. then an array will be created that has the required dimensions to accommodate the values specified in the initializer. then a compile-time error is generated. Similarly. array name). '\'' (single quote). Please note that the square brackets within an array declaration may appear as part of the type or part of the declarator (i. but none are Java keywords. All of these are keywords of the Pascal None of the above programming language. The first 4 6 8 letter can not be a number. Remark The escape sequences are as follows: '\b' (backspace). '\n' (newline).1. Yes. If only the dimension expression is present. you must memorize the escape sequences! Just remember "big farms need red tractors". Java avoids the possibility of an incompatible dimension expression and initializer by not allowing both to appear in the 16 Answer 1 a 2 g 3 l 4 d f h 5 6 b d a e 402 . if neither is present. The maximum value is 2 . '\t' (horizontal tab).e. then an array with the specified dimension is created with all elements set to the default values.Answers Chapter 2 No. If only the initializer is present. '\"' (double quote). If both are present. '\\' 1 (backslash). the single None of the above argument is indeed an array of components of type String. so none of '\u0000' to '\uffff' 0 to the char values are negative and the minimum 65535 value is zero. The Java Language Specification requires that the main method must accept a single argument that is an array of components of type String. '\f' (formfeed). In each of the three class declarations. The first letter of an identifier can be any Unicode character that is a Java letter. '\r' (carriage return).

Answer 7 a Prints: 3. and the declaration contains the initializer {{1. Each subarray contains components of type int.8. The fourth (0x0031) is declared as a hexadecimal literal. '\061' ) are declared in octal format. or char then the left operand is promoted to a 32 bit int and all four bytes are shifted. and each is a reference to a subarray of type int[].10}}. '\61'. The initializer creates an array containing three components. If the left-hand operand of the shift operator is of type byte.3}. a1[0][2] = a1[1st subarray][third component] = 3. {4.6}.2. If the promoted type of the left-hand operand is of type int. The array access expression. An array variable a1 is declared.5. The sign of an integral numeric type is changed by inverting all of the bits and by adding one. All of the declarations are legal. because either the dimension expression or the initializer must be removed. so the elements of the array referenced by a1 are of type int. short. because it needs either a dimension expression or an initializer. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.9. The first three ( 061.{7. Chapter 3 No. they are not automatically initialized.8 Remark same array creation expression. A compile-time error is generated by the array creation expression for a1. The fifth ('\u0031') is a Unicode escape sequence.4.No. Answer Remark Variables declared inside of a block or method are called local variables.true Prints: 10 403 . Both operands of the conditional and operator and the conditional or operator must be of type boolean. A compile-time error is generated at 5. then the shift 1 f Compile-time error 2 j Compile-time error 3 f None of the above 4 5 d e Prints: true.

2. Answer 6 c Prints: 5 7 b Prints: 2. Suppose the left operand were divided by the right operand. The results demonstrate that the conditional operator (?:) groups from right-toleft.{7. The two statements. is always true. In this case.8. The array access expression. A compile-time error is generated as a result of the attempt to access length as though it were a method. {{1. The tricky feature of this question is the reversal of i and j to produce the deceptive array access expression. For integral types. a1[j][i].9}}. The remainder operator returns the remainder of the division operation. then the least significant six bits of the right hand operand are used. a compound assignment expression of the form E1 op= E2 can be rewritten as E1=(T) ((E1)op(E2)) where T is the type of E1.{4. and the five least significant bits are 00001.6}.true 8 b Prints: FFT Remark distance is always within the range of 0 to 31. int a=1 followed by a += ++a + a++. Note: If the type of the left hand operand is long. a1[0][1] = a1[first subarray][second element] = 2. (y == ((y/x)*x+(y%x))).3}. the identity. Cases one and three have no break statement. The array variable a1 is declared with the initializer.5.No. Generally speaking. Chapter 4 No. 1 c 3 Answer Remark The length member of the array type is an attribute. a=(int)((1)+(++a + a++)). Further evaluation produces a=(int) ((1)+(2 + 2)). The output is 147258369. If the argument of the print statement had been a1[i][j] then the output would have been 123456789. and is specified by the least significant 5 bits of the right-hand operand. the shift distance is 33. so the shift distance is one bit. inclusive. so the 2 b Prints: 147258369 3 c Prints: v w x x y z z 404 . can be rewritten as the single statement. The expression used to assign variable b1 is equivalent to the expression used to assign variable b2.

d and e is zero. the value of x is 6. and must be initialized explicitly before 405 . Remark 1 d e f The JLS requires the main method to be declared static. An attempt to run GRC2 from the command line fails.No. success. 2 e f The JLS requires the main method to be declared public. 3 e 4 5 c c The local variable y has not been initialized so Compile-time error at the attempt to access the variable results in a line 5. b. success. so the variable. The main methods of GRC2 and GRC3 are not declared public and can not be invoked from the command line. On the final pass. The zero is converted to a String and Prints: 0null concatenated with s. is incremented to the value. the value of x is 3 and the variable. On the first pass through the loop. The numeric sum of variables a. In this example. so 5 is subtracted from x. c. the value of x is 3. Compile-time error Local variables are not initialized automatically. the value of x is 1. the value of x is 4. each of the three main methods are not declared static. Answer Remark next case is also executed and x and z are printed twice. so 3 is added to x. An attempt to run GRC9 from the command line results in an error at runtime. On the third pass. compile-time error. is incremented from zero to one. 4 c Prints: 61433 Chapter 5 No. An attempt to run GRC8 from the command line results in an error at runtime. On the second pass. so 1 is subtracted from x. Answer An attempt to run GRC7 from the command line results in an error at runtime. An attempt to run GRC3 from the command line fails. The boolean expression of the do loop is now false. On the fourth pass. The result is an error at run-time. 2. so control passes out of the loop.

The arguments of the method invocation expressions.No. so the result is a compile-time error. are applicable to the two method invocation expressions. requires an explicit cast to type int. Although the reference variable r2 is assigned the value of reference variable r1 in method m1. m(double i). short. If one of the two operands of a numeric expression is of type long and if the other operand is of type int. then it will be promoted 406 . m(float i) and m(double i). so any argument that can be passed to m(float i) can also be passed to m(double i) without generating a compile-time type error. m(double i). The local variable i3 will not be initialized if i1 is less than or equal to zero. For that reason. The assignment expression. the more specific of the two. the reference pet2 remains unchanged in the main method. but r2 can not be used to force pet2 to reference a different instance. m(float i) is chosen rather than the less specific.float 8 c Prints: Bird. Object references are passed by value: the invoked method gets a copy of the object reference. A method invocation conversion can widen an argument of type float to match a method parameter of type double. The reference parameter r1 can be used to modify the state of the instance referenced by pet1. is chosen over the less specific. the more specific of the two. A method invocation conversion can widen an argument of type int or long to match either of the two method parameter types float or double. we can say that m(float i) is more specific than m(double i). The index for the first element of an array is zero so the first argument printed by this program is the second argument on the command line following the name of the class. so both methods. a = c + a. are of types int and long respectively. m(float i). Answer 6 b Prints: BCD 7 a Prints: float. Since both methods are applicable. m(a1) and m(b1). char or byte. Since both methods are applicable.Cat 9 d 4 Remark attempting to access the value.

The method parameter c2 is declared final.3 impact outside of m1. short.) The type long result can not be assigned to a variable of type int without an explicit cast. so it can not be assigned to type byte without an explicit cast. The char 2 type variable c2 is not a compile-time constant.". Since the char type variable c2 is not a compile-time constant. Instead. In method m2. or int and the value 6 7 8 falls within the range of the variable on the left and if the variable is of type byte. then the char value is assignable to type byte.No. the method parameter c2 is not a compile-time constant. (Note: The rule does not apply to the shift operator. The declared result type of method m2 is byte. In method m2. The compiler will implicitly do a narrowing conversion for an assignment statement if the right hand operand is a compile time constant of type byte. Compile-time error at There is a compile-time error at 2. short. Array references are passed by value: the invoked method gets a copy of the array reference. the value of c2 is assigned at run time to the value of the argument. is a return statement with an expression. variable c2 is not a compile-time constant. so the value of c2 can not be changed within method m2. A compiletime error occurs if the type of the expression is not assignable to the declared result type of the method. the value of variable c2 is not Answer 407 . The value of method parameter c2 is set at run time to the value of the argument that is provided when m2 is invoked at line 3. char. If a char value is a compile-time constant. The return statement attempts to return the value of the char type variable c2. and if the value falls within the range of type byte. "return c2. or char. because the value of c2 is not known at compile time. 10 b 11 f g h 12 d Remark to type long. For that reason. c2. the change has no Prints: 1. Although the reference parameters i1 and i2 are reassigned inside of m1. the statement. and the result of the expression will be of type long.

the expression color2 instanceof Blue is rejected at compile-time. Since Red is not a subclass or a superclass of Blue. the expression. is accepted at compile-time. protected and public. The type of the object instance referenced by color1 is Red. Please note: The expression. can be applied to a field.No. the expression j error color1 instanceof Color would evaluate to true at runtime. Answer Remark assignable to the return type of method m2 without an explicit cast. The reference color1 refers to an instance of Compile-time type Red. A static field is sometimes called a class variable. color1 instanceof Blue. the declaration of method m1 does not. Remark The type of the reference color2 is Red. so c1 is a compile-time constant. Since Red is not Blue or a subclass of Blue. A variable declaration that is immediately contained by b final a block such as a method body is called a local variable. x instanceof T. color1 instanceof Blue. A field is a class member. While the declaration of method m2 produces a compile-time error. color1. If the program had been able to compile and run. would be false at run-time. A non-static field is sometimes called an instance variable. is of type Color. The reference. The c private d protected access modifiers. The abstract modifier may be applied to methods but not to fields Answer 1 2 408 . the expression color1 instanceof Color would evaluate to true at run-time. produces a compile-time error whenever the cast expression (T)x produces a compiletime error. The value \u0001 falls within the range of type byte. Since Red is a subclass of Color. so the value of the compile-time constant c1 is assignable to the return type of method m1 without an explicit cast. Chapter 6 No. color1 instanceof Blue would evaluate to false at run-time. The local variable c1 is declared final and the value is set at compile time. A final field can not have its value assigned e public more than once. Since Color is a superclass of Blue. The expression. private. the expression.

The size of the subarrays has not been specified. the compiler will not create an implicit default constructor. 3 4 A local class can be b declared abstract. An abstract class can not be instantiated. so the compiler attempts to create a default constructor. the array referenced by a2 contains two reference variables. the array referenced by a3 contains three reference variables. private. and invokes its superclass constructor. The initial value of each subarray reference is null. In other words. are not applicable to any class that is not a member class. then the class must also be declared abstract. an anonymous class can not be declared abstract. protected or public. no modifier). If a class C is declared as a member of an enclosing class then C may be declared using no access modifier or any of the three access modifiers. then the compiler will implicitly create a default constructor that accepts no parameters. private and protected. At line 5. A class can be declared abstract even if it does not contain an abstract method. The declaration A11[] a1 = new A11[1] declares a variable a1 that references an array that contains one component of type A11. A local class can be abstract. The declaration A11[][][] a3 = new A11[3] [][] declares a variable a3 that references an array that contains three components of type A11[][]. and each is able to reference a subarray. a compiler error is generated at marker 2. Compile-time error at 2. Since class A does not have a noparameter constructor. However. Answer The compiler attempts to create a b default d constructor for class B.e. generates a compile-time error. the attempt by class B to invoke the no parameter constructor of A would fail. anonymous class or a member of an enclosing class or interface. The dimensions of the subarrays have not been specified.No. has no throws clause. As a result. and each is able to reference a subarray. 5 c d 3 4 5 e 6 b Prints: A11 Remark If no constructor is declared explicitly. then C may be declared with the public modifier or with package access (i. The class declaration. a reference to the array 409 . In other words. The other two access modifiers. An anonymous class can not be extended. The declaration A11[][] a2 = new A11[2] [] declares a variable a2 that references an array that contains two components of type A11[]. The initial value of the subarray references is null. If a class declaration contains an abstract method. Since class A has an explicitly declared constructor. therefore. An abstract class can never be declared final. Class B does not have an explicit constructor declaration. because all of the letters of the reserved word class must be lower case. Class Basics4 {}. if class C is not a local class.

after line 6. because the default constructor does not declare Exception in the throws clause. and produces the output. protected. The constructors for class B and class C both invoke the constructor for A. and each element of the array referenced by a2 is a reference to the array referenced by a1. Answer Remark referenced by a1 is assigned to each of the two components of the array referenced by a2. 1 c Compile-time error at 3. Chapter 8 No. each component of the array referenced by a3 is a reference to the array referenced by a2. both B and C must declare Exception in their throws clause.No. so the reference may be cast to type Sub. 1 e Answer None of the above Remark Line 4 does not generate a compile-time error. The constructor for class A declares Exception in the throws clause. In other words. and package access methods of class A. Chapter 7 No. Every element of the multi-dimensional array referenced by a3 contains a reference to a single instance of class A11. 2 d Compile-time error at 3. a2[0] = a2[1] = a1. 410 . The reference named base actually refers to an instance of type Sub. and the array referenced by a1 contains a reference to an instance of class A11. Both class A and B are declared in the same package. Since the constructors for B and C invoke the constructor for A implicitly. The print method invokes the toString method on the instance. so class B has access to the public. Answer Remark The compiler creates a constructor for class C implicitly. A compiletime error is generated at marker 3. The implicitly created constructor accepts no parameters and has no throws clause. At line 6. a reference to the array referenced by a2 is assigned to each of the three components of the array referenced by a3. a3[0] = a3[1] = a3[2] = a2. A11.

1 Remark Both Error and Exception are subclasses of Throwable. so the minimum byte value is -(2 ) and the maximum value is (2 1).32767 411 . The switch statement throws a Level1Exception that can not be caught by the nested catch clause. under normal operating circumstances. so the minimum short value is -(2 ) and the maximum value is (2 . 1 Answer d Prints: -128. The escape sequence \r should be used instead. the default label of a switch statement should not be reached. 3 4 \u000d is interpreted as a line terminator. The escape sequence \n should be used instead. The outer finally block is executed as control passes out of the try statement. A short is a 16 bit signed value. 1 c d Answer Remark The compiler interprets \u000a as a line terminator.true 3 b Prints: 0. 2 d Answer Prints: true. None of the String literals are declared using double quotes. so the nested finally block is executed as control passes to the first of the two outer catch clauses. but all above of the declarations here use single quotes.1).127 Remark A byte is an 8 bit signed value.1. 7 7 15 15 2 b Prints: -32768. then an assert statement can be placed after the default label to verify that an unexpected condition has not not occurred.1. 4 With assertions enabled it prints 210210 followed by an b e AssertionError message. 2 e Chapter 12 No.0.No. The nested catch clause is able to catch a Level2Exception or any subclass of it.0. Similarly. With assertions disabled it prints 210210-1 Chapter 10 No. If.

The last of the octal digits represents the right most three bits of binary value. The sign bit is zero for positive numbers and one for negative numbers. Answer 3 a Prints: 1111111. The most positive byte value is represented as a sign bit that is set to zero and all of the other bits set to one. The first of the three digits represents the left most two bits of the binary value. can be assigned to a reference of the int array type. In this case. so only seven bits are printed. int[].No. so any array reference can be assigned to a reference of type Cloneable. the left most two bits are zero and one.ffff. The right hex digit represents the right most four bits of the binary value. Note that the Integer. An eight bit binary value is represented as two hexadecimal digits. The Integer. The second octal digit represents the next three bits of the binary value.177.7fffffff 6 g None of the above 7 f Prints: true. The sign bit is set to zero for positive numbers and is set to one for negative numbers. The minimum byte value in hexadecimal format is 80 and in decimal format is -128.127. The left most bit of a signed value is the sign bit.7f 4 c Prints: 7f. The maximum byte value in hexadecimal format is 7f and in decimal format is 127.toOctalString method does not print a leading zero as is required for an octal literal value. The left most bit is the sign bit. The left most bit is the sign bit. The int array object referenced by the Cloneable reference. The byte value of decimal -1 is ff in hexadecimal. c.true Remark A byte is an 8 bit signed value. An int is a 32 bit signed value. A short is a 16 bit signed value. NaN is 412 . The positive infinity of type float is promoted to the positive infinity of type double. The left hex digit represents the left most four bits of the binary value. The null literal is converted to an int array type with the value null. The sign bit is zero for positive numbers and one for negative numbers. An eight bit binary value is represented as three octal digits. A char is a 16 bit unsigned value. A byte is an 8 bit signed value.7fff 5 f Prints: 80000000.false.toBinaryString method does not print leading zeros. All array types implement the Cloneable interface.

413 .No. Answer Remark not equal to anything including itself.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.