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


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


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


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.


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.


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

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

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

there is a new. The following figure illustrates how this works.0 release was an improved experience on the desktop client. first you translate a program into an intermediate language called Java bytecodes —the platform-independent codes interpreted by the interpreter on the Java platform.Improved Desktop Client The last great theme of the 5. improved Swing look and feel called Ocean.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 Unicode. interpretation occurs each time the program is executed. With the compiler. The Java programming language is unusual in that a program is both compiled and interpreted. The Java Web Start and Java Plug-In technologies (both used to run Java applications downloaded over the Web) have been improved.0 include core XML support. you either compile or interpret a program so that you can run it on your computer.4. 1.2 have received further improvements. There is support for OpenGL and better performance on Unix X11 platforms. Other new features in J2SE 5. 12 . improvements to Java's database connectivity package known as JDBC. and an improved. the GTK and XP look and feels introduced in J2SE 1. Compilation happens just once. In addition. In addition to better performance because of a faster startup time and smaller memory footprint. highcompression format for JAR files that can greatly reduce download times for applets and other networked applications. The interpreter parses and runs each Java bytecode instruction on the 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.

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

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

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

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

or interpret and run applets in any Web browser with a Java VM built in such as Netscape or Internet Explorer. The Java interpreter is invoked at the command line on Unix and DOS shell operating systems as follows: java ExampleProgram At the command line. To these ends. Interpreting and running a Java program means invoking the Java VM byte code interpreter.} 1. Double Slashes Double slashes (//) are used in the C/C++ programming language. } } 17 . 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.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.out. //A Very Simple Example class ExampleProgram { public static void main(String[] args){ System. and doc 1. and tell the compiler to treat everything from the slashes to the end of the line as text. you can interpret and run applications on any Java VM. C-style.13 Interpreting and Running the Program Once your program successfully compiles into Java bytecodes. or to generate API documentation. you should see: I'm a Simple Program 1.println("I'm a Simple Program").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. to comment-out lines of code to isolate the source of a problem for debugging purposes.

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

and the program does not return data to the Java VM interpreter (void) when it ends. Java is important because of its cross-platform functionality. but because it is the only class in the program. It has no fields or accessor methods. and is the control point from which the controller class accessor methods are called to work on the data. Java is not only a programming language it’s a platform. It can be used for embedded as well as mobile applications. Also Java is a secure language. 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). Summary In this chapter you learnt the history of Java and how the Java language has evolved.The code in the main method executes first when the program starts. Java can be used for simple as well as complex applications. it has a main method. 19 .

The Java programming language does not support the explicit use of addresses like other languages do. A reference is called a pointer. positive value: (2-2-23)*2127. in contrast to that of a primitive type.1 Data Types The Java programming language has two categories of data types: primitive and reference.Chapter 2 : Data types. classes. positive value: 2-149 20 . You use the variable's name instead. A variable of primitive type contains a single value of the appropriate size and format for its type: a number. Min. int anInt = 4. variables and Arrays 2. or a boolean value. a character. 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. and interfaces are reference types. 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. The value of a reference type variable. Arrays. or a memory address in other languages. is a reference to (an address of) the value or set of values represented by the variable.

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

words or even objects). Note that Java is case sensitive so A1 and a1 are different identifiers.which allows for up to 65K worth of characters.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. 22 . There are rules which govern what is allowable. 2. identifiers and other text within programs.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 */ Identifiers must be chosen according to certain rules: • • • • they can contain letters. other special characters or punctuation marks a Java keyword must not be used. the underscore character ( _ ) or dollar character ($) they cannot start with a number they must not include spaces. numbers. e. most of which can easily be stored within one byte. the code for the class JTRectangle is stored in the file JTRectangle. this is sometimes called camel hump notation.g. For reasons of compactness Java uses a system called UTF-8 for string literals. objects. Naming Conventions Class identifiers begin with a capital letter. This means it can deal with Japanese Chinese. This can result in a considerable saving by comparison with using Unicode where every character requires 2 bytes. Most of the text data within a program uses standard ASCII. and just about any other character set known. Although Unicode can represent almost any character you would ever likely to use it is not an efficient coding method for programming. for example: cubeRoot. firstNumber. classes. 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. variables and attributes (attributes could be numbers. The filename for the class code is the same as the name of the class.

so you cannot use them as names in your programs either.7 Variables A variable is an item of data named by an identifier. Attributes identifiers start with a lowercase letter. which generally looks like this: type name In addition to the name and type that you explicitly give a variable. false. You can perform arithmetic operations.0 2. a variable has scope. The variable's name must be a legal identifier --an unlimited series of Unicode characters that begins with a letter.4 **** new in J2SE 5. You must explicitly provide a name and a type for each variable you want to use in your program. 2. 23 . on integer variables. A variable's data type determines the values that the variable can contain and the operations that can be performed on it. Integers can contain only integral values (both positive and negative). 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. 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. To give a variable a type and a name.6 Java Language Keywords true. and null are not keywords but they are reserved words.Object identifiers start with a lowercase letter. You use the variable name to refer to the data that the variable contains. such as addition. you write a variable declaration.

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

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

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

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

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

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

d. d. e. 1 2 3 4 5 6 7 8 30 . #i4. j. class Identifiers { } Compile-time errors are generated at which lines? a. h. h. b. 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. c. i$7. _i2. f. f. i_3. e. An attempt to run GRC4 from the command line fails. $i5. An attempt to run GRC6 from the command line fails. d. Which of these words belongs to the set of Java keywords? a. g. value virtual xor None of the above 4. Compile-time error at line 2. b. Compile-time error at line 3. // // // // // // // // 1 2 3 4 5 6 7 8 e. g. %i6. 8i. b. c. f. k. l. None of the above 3. c.2. label to type until i. An attempt to run GRC5 from the command line fails. qualified record repeat restricted int int int int int int int int i1. Compile-time error at line 1. g.

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

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

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

The following table summarizes the binary arithmetic operations in the Java programming language. System.22. 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.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.out.println(" y = " + y).0 or infinity. .out. then NaN returned ArthmeticException thrown if op1 & op2 are integer types and op2 is zero. public class ArithmeticDemo { public static void main(String[] args) { //a few numbers int i = 37. double y = 7. These operators are + (addition).println(" j = " + j).out.2.println(" i = " + i). System. double x = 27.println(" x = " + x). and % (modulo).(subtraction).475. int j = 42. * (multiplication). System.println("Variable values."). ArthmeticException thrown if op1 & op2 are integer types and op2 is zero.out.0.1 Arithmetic Operators The Java programming language supports various arithmetic operators for all floating-point and integer numbers. 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..out. //adding numbers 34 .. System. System. / (division).

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

.println("Variable values. System.Decrements op by 1. evaluates to the value of op after it was incremented op-. or char -op Arithmetically negates op 3. System.. evaluates to the value of op before it was ++op Increments op by 1. evaluates to the value of op after it was decremented 3."). int k = 42. The postfix version. 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.out. short.println(" j = " + j). ++op/--op. The prefix version. evaluates to the value of op before it was decremented --op Decrements op by 1.2.+ - +op Promotes op to int if it's a byte. and decrement operator (--)decrements its operand by 1. op++/op--. int j = 42.2 Increment and Decrement Operators Increment operator (++) increments its operand by 1. 36 .can appear before (prefix) or after (postfix) its operand. evaluates the value of the operand before the increment/decrement operation.2. evaluates to the value of the operand after the increment/decrement operation.out. != returns true if the two operands are unequal. Either ++ or -.println(" i = " + i).out.3 Relational Operators A relational operator compares two values and determines the relationship between them. Operator ++ ++ --- Use incremented Description op++ Increments op by 1. For example. System.

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

The left-hand bits are filled with 0s as needed. the following statement shifts the bits of the integer 13 to the right by one position: 13 >> 1.| ^ op1 | op2 op1 ^ op2 either op1 or op2 is true. For example. The binary representation of the number 13 is 1101. the & operation performs the bitwise AND function on each parallel pair of bits in each operand. op1 op2 0 0 1 1 0 1 0 1 Result 0 0 0 1 38 . as shown in the following table.4 Bitwise Operators A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left. 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. This table summarizes the shift operators available in the Java programming language. 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 result of the shift operation is 1101 shifted to the right by one position-110. The shift occurs in the direction indicated by the operator itself. 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 AND function sets the resulting bit to 1 if the corresponding bit in both operands is 1. or 6 in decimal.2.

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

DRAGGABLE = 2. public static void main(String[] args) { int flags = 0. } } 40 .. SELECTABLE = 4. EDITABLE = 8.").println("Both conditions are true. <=. } } flags = flags | EDITABLE. if ((flags & VISIBLE) == VISIBLE) { if ((flags & DRAGGABLE) == DRAGGABLE) { System.println("Flags are Visible and Draggable. you could then write: if ((flags & VISIBLE) == VISIBLE) { .").println("Flags are now also Editable. flags = flags | DRAGGABLE. } } } 3. !=."). flags = flags | VISIBLE. >. as follows: if (x == 2) { if (y != 2) { System. } A program example is given below: public class BitwiseDemo { static static static static final final final final int int int int VISIBLE = 1.5 Logical Operators The relational operators you've learned so far (<.out. if ((flags & EDITABLE) == EDITABLE) { System.To test for visibility.out.out.2. 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.. ==) are sufficient when you only need to check one condition. >=.

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

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. The Java approach makes sense if you consider that for an AND.println("Not equal! "+Output). } else { System.out. then m/n is very undefined. public class MyClass1{ public static void main(String argv[]){ int Output=10. } } } 42 . 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. because the left hand side is always evaluated first.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. 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). Even if n is zero this line will never cause a division by zero. For instance consider this code. if((b1==true) && ((Output+=10)==20)) { System. the overall result will be false. If. if the first operand is false it doesn't matter what the second operand evaluates to. This can have an effect with those clever compressed calculations that depend on side effects. And if m is also zero. 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. if the first operand has turned out true. If n is zero then the left hand side is true and there's no need to evaluate the right hand side. Mathematically this makes sense because m/0 is in some sense infinite which is greater than two. Also for a logical OR. 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. boolean b1 = false. Still it's possible to force them. Take the following example.println("We are equal "+Output). upon reflection.out. This isn't a perfect solution though because m may be 0 or it may be negative. boolean b = (n == 0) || (m/n > 2).

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

2. For instance one common operation is setting the value of a variable to the maximum of two quantities. The condition. If it is true the first value. In Java you might write if (a > b) { max = a. a. Using the conditional operator you can rewrite the above example in a single line like this: max = (a > b) ? a : b. a > b). create arrays. Conditional or ternary operator Used to declare arrays. or b.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. } else { max = b.%= &= |= ^= <<= >>= >>>= 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 ?: [] . is tested. is 44 . is returned. If it is false. b. (a > b) ? a : b. ( params ) ( type ) new instanceof Description Shortcut if-else statement. The value of a variable often depends on whether a particular boolean expression is or is not true and on nothing else. (a the second value. } 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. the conditional operator. 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. ?:.

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

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

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

7778 20 -6.556 260 126.44444 60 15.778 300 148.0) * (fahr-32.66667 40 4. while (fahr <= upper) { double celsius = (5.2222 200 93.3333 220 104. double fahr = lower.0). All other operators (see precedence table above) are evaluated left to right.444 240 115. } } } Here's the output: 0 -17.0 / 9.667 280 137. fahr = fahr + step.1111 180 82.8889 140 60 160 71.5556 80 26. System.6667 100 37.double step = 20.7778 120 48. Operator Associativity The following operators have Right to Left associativity.out.println(fahr + " " + celsius).0. 48 .889 Everything inside the parentheses will be calculated before anything outside of the parentheses is calculated.

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

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. This result then must be cast if it goes to a lower precision type: float x. The program below uses both ints and doubles. Otherwise. Otherwise. class IntAndDouble { 50 . // OK since i will be promoted to float j= i*y. The symbol A indicates that the precision is increasing so an automatic cast occurs without the need for an explicit cast. x= i*y. For example. the other is converted to float.i=3. Mixed Types in an Expression If an expression holds a mix of types. the other is converted to double. The Java VM specification states the following rules for promotion in an expression of two operands. Otherwise. if either operand is of type float. as in x+i: • • • • If either operand is of type double. both operands are converted to type int.y=3. // 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". 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. int j. N indicates that the conversion is not allowed. 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 lower precision or narrower value operand is converted to a higher precision or wider type. for example. The symbol C indicates that an explicit cast is required since the precision is decreasing. the other is converted to long.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

|| (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;


} }


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


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;


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:

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:


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

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.

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


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


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;


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


Methods surround and hide the object's nucleus from other objects in the program. A method is a function (subroutine) associated with an object. an object can be easily passed around in the system. of the object. Also.1 What Is an Object? The real-world objects share two characteristics: They all have state and behavior. The object diagrams show that the object's variables make up the center. The access level determines which other objects and classes can access that variable or method. You can represent real-world objects by using software objects. 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. A particular object is called an instance. A software object implements its behavior with methods. 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.Chapter 5 : Class Fundamentals and OOP 5. 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. Information hiding: An object has a public interface that other objects can use to communicate with it. A software object maintains its state in one or more variables. 73 . 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. or nucleus.

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

Messages provide two important benefits.   An object's behavior is expressed through its methods. You do not want to 75 . and minimising it makes for more reusable and maintainable classes. 5. The expectated behaviour of a class or method is referred to as its 'contract'.4 Features of Object Oriented Programming There are four features of OOP.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. 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.4. This allows you to change those details where necessary. so (aside from direct variable access) message passing supports all possible interactions between objects. The interconnectness between pieces of code is called 'coupling'.• • • 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. No other information or context is required. without breaking compatibility.

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

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

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

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

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

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

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

A final method cannot be overridden by subclasses

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

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.


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


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


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.


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

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.


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.

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

Indicates that the value of this member cannot change.

Marks member variables that should not be serialized.

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


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.


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.


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

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 can specify that method to be a class method rather than an instance method. 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. sets their x values. let's change the AnIntegerNamedX class such that its x variable is now a class variable: class AnIntegerNamedX { static int x.showing that each instance of the class AnIntegerNamedX has its own copy of the instance variable x and each x has a different value.x = 2 anotherX. For example. and its two methods are now class methods: class AnIntegerNamedX { 89 . specify that the variable is a class rather than an instance variable. 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). } } Now the exact same code snippet from before that creates two instances of AnIntegerNamedX. For example. and then displays them produces this. when declaring a member variable. you change the value of x for all instances of AnIntegerNamedX. You can. different. To specify that a method is a class method. output. public int x() { return x. Class methods can only operate on class variables--they cannot access the instance variables defined in the class. The system creates a single copy of a class variable the first time it encounters the class in which the variable is defined. Class methods can only operate on class variables and cannot access the instance variables defined in the class. Similarly. Let's change the AnIntegerNamedX class such that its member variable x is once again an instance variable. When you invoke setX() on either instance. Similarly. myX. To specify that a member variable is a class variable. All instances of that class share the same copy of the class variable. when declaring a method. you can specify that a method is a class method rather than an instance method. use the static keyword in the method declaration. } public void setX(int newX) { x = newX. use the static keyword.

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

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

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

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

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

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

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

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

access by any other class anywhere. access levels determine which members of those classes your classes can use. protected May be accessed by other classes in the same package or from any subclasses of the class in which they are declared. 2. if you distribute new versions of your classes at a later point. when you write a class. even if these are subclasses. Constructors. Default . private no modifier 98 . public . such as naming methods. you can change or eliminate these private attributes and methods without worrying that these changes will affect the subclasses.accessible only within the class. May be accessed only from within the class in which they are declared.accessible by the package classes and any subclasses that are in other packages . First. when you use classes that come from another source. May only be accessed from within the package in which they are declared. 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. you need to decide what access level every member variable and every method in your class should have. protected . Even methods in subclasses in the same package do not have access. private . you can prevent the subclass code from interfering with the internal workings of your classes. 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.1. Also. Access levels affect you in two ways. 4. you may distribute your class files to other users who can make subclasses of them. Inner Classes. For example. By making some of your data and methods private.(also known as "package private") accessible to classes in the same package but not by classes in other packages. 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. These access rules allow one to control the degree of encapsulation of your classes. Methods and Field variables may be accessed from wherever their class is accessed. 3. such as the classes in the Java platform. Second.

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

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

} public int getAge(){ return iAge. } 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. 5. Note: If you do not write your own constructor. The default constructor initializes all non-initialized fields and variables to zero. 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.14 Constructors Classes have a special method called a constructor that is called implicitly when a class instance is created. You are asked to put in code to check for these error conditions. is to create methods that access a private field containing the age value. with names like setAge and getAge. 101 . can be changed whilst the way it looks to the outside world (the interface) remains the same. So wherever your programs change the age value.You might store it simply with a public integer variable int iAge. which calls the no-arguments constructor of its parent class. you write if statements that check for the range. The empty constructor is called the default constructor. public void setAge(int iStudentAge){ iAge = iStudentAge. (the actual lines of program code). 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. 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. 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. The class constructor always has the same name as the class and no return type. The Object Oriented approach to this problem using encapsulation. the compiler adds an empty constructor. By this approach the implementation of code.

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

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

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

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

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

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

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

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

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

private int pot. it might as well be static. . A non-static nested class is generally used only inside the class in which it is nested.for non-static nested classes. The same is true -. you must first have an object that belongs to the containing class. Looking at an example will help. Otherwise. however. Consider a class that represents poker games. Two copies of the nested class in different objects differ because the instance variables and methods they refer to are in different objects. . . 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. // The amount of money that has been bet.NestedClassName. and there it can be referred to by its simple name. . From outside the containing class. make it non-static. This copy has access to all the instance methods and instance variables of the object. } // end class Player private Deck deck. a non-static nested class has to be referred to as variableName. In fact. It's as if each object that belongs to the containing class has its own copy of the nested class. In order to create an object that belongs to a non-static nested class. class Player { // Represents one of the players in this game. This is true for non-static nested classes. 111 . .) The nested class object is permanently associated with the containing class object. This class might include a nested class to represent the players of the game. This structure of the PokerGame class could be: class PokerGame { // Represents a game of poker. where variableName is a variable that refers to the object that contains the class. and will hopefully convince you that non-static nested classes are really very natural. The non-static members of a class specify what will be contained in objects that are created from that class. . This is actually rather rare. the object "this" is used implicitly. 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 least logically -. // A deck of cards for playing the game. (When working inside the 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 following example creates the Outer instance on a separate line. Players of that poker game use the deck and pot for that game. containing a nested class Inner: Outer. (A Player object could be created outside the PokerGame class with an expression such as "new Inner(). or the current this object is not an instance of the outer class. you can use: 112 . This is the most natural way for players to behave. Outer. however.Inner y = x. then. this is rather rare.) The Player object will have access to the deck and pot instance variables in the PokerGame object. Write code in a non-static method of the outer class to construct an instance of the nested class. the syntax in the second line is the one you use when you already have an instance of the outer class. but it had to construct an instance of Outer first.} // end class PokerGame If game is a variable of type PokerGame. That's the effect of making the Player class non-static. You may encounter nested classes of both kinds in the Java platform API and be required to use them. Each PokerGame object has its own deck and pot and Players. a new Player object would be created by saying "new Player()". Outer x = new Outer(). If Inner is static. If Player were a static nested class.Inner y = new Outer(). Inner x = new Inner(). playes of another poker game use the other game's deck and pot. The above creates an instance of Inner called Inner(). constructs an instance of Inner where Inner is a nested class defined in the current class. independent of a particular poker game. In an an instance method of a PokerGame object. Given a class. just as for any other class. A Player object represents a player of one particular poker game.Player()". game contains its own copy of the Player class. on the other hand. Outer. it would represent the general idea of a poker player. Again. conceptually. 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. You must create an instance of the outer class first. Write code to construct an instance on a nested class where either no this object exists.

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

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

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

parseDouble(args[0]). } } 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.703031 There's one limitation of enum types: although enum types are classes.radius = radius.surfaceGravity(). public double surfaceGravity() { return G * mass / (radius * radius). 116 . } } In addition to its properties. In other words.surfaceWeight(mass)).397260 on NEPTUNE is 199.this. it's not possible for one enum type to extend another enum type. } public double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(). Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet.values()) { System.552719 on URANUS is 158. } public double radius() { return radius. you cannot define a hierarchy of enums. for (Planet p : Planet. 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.207413 on PLUTO is 11. p.279007 on JUPITER is 442.out.847567 on SATURN is 186.000000 on MARS is 66. Enumerated types in switch statement An example of using enumerated type in switch statement.67300E-11.374842 on EARTH is 175. } public double mass() { return mass. } //universal gravitational constant (m3 kg-1 s-2) public static final double G = 6. p.printf("Your weight on %s is %f%n".107583 on VENUS is 158. double mass = earthWeight/EARTH.

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

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

You can control access to member variables and methods in the same way: by using an access specifier. You create an object from a class by using the new operator and a constructor. 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. You can explicitly drop a reference by setting the variable holding the reference to null. Questions 1. Compile-time error at line 2. c. 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 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. Class variables are shared by all instance of a class and can be accessed through the class name. b. Compile-time error at line 1. A class defined within another class is called a nested class.methodName(argumentList) or objectReference. The qualified name of an instance variable looks like this: objectReference. You can assign the reference to a variable or use it directly. which must be accessed through an instance reference. such as private or public. Like other members of a class. 119 . a nested class can be declared static or not. The new operator returns a reference to the object that was created. A nonstatic nested class is called an inner class.member. Instances of a class get their own copy of each instance variable. An object is unused if the program holds no more references to it. in the member's declaration. Compile-time error at line 3. A class controls access to its instance variables and methods by using the Java platform’s access mechanism.variableName The qualified name of a method looks like this: objectReference. The garbage collector automatically cleans up unused objects.methodName() Constructors initialize a new instance of a class and have the same name as the class.

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

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

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

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

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

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

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

127 .

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

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

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

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

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

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

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

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

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

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

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

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

0 that will be discussed. r. r. //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. r = b. r.callme().List.5 Annotations Introduced in J2SE 5. For example.callme(). For example: @Override class Cat extends Pet { } or @Override void feedTheDog() { } The following example illustrates all three built-in annotation types.callme().util. using methods: import java. r = c. c = new C().A B C A a = new A(). Annotations use the form @annotation and can be applied to methods or classes. } @Deprecated static void deprecatedMethod() { } } 140 . b = new B().0. r. annotations provide a way for programmers to instruct the compiler on how to handle certain situations. class Food {} class Hay extends Food {} class Animal { Food getPreferredFood() { return null. There are three useful annotations built-in to release 5. } } 6. 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.

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

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

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

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

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

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

taking place at the bytecode level. 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(). n.j++. It does this by checking to make sure that a class is not a subclass of a final class. } Any subsequent attempts to subclass ChessAlgorithm will result in a compiler error such as the following: Chess. conceptually.i = 40. SmallBrain x = new SmallBrain(). use the keyword final before the class keyword in your class declaration. .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. if you wanted to declare your (perfect) ChessAlgorithm class as final. n. int j = 1. To specify that your class is final. . You may think that your class is "perfect" or that. its declaration should look like this: final class ChessAlgorithm { . Design: You may also wish to declare a class as final for object-oriented design reasons.f(). } } 147 . n. your class should have no subclasses. For example.

. } Final methods cannot be abstract methods.with(null). } } 148 . some of its methods are final and some are not. // Illegal -. . . bf.. 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.spin(). For example. BoardLocation newLocation) { .without(null). } public static void main(String[] args) { FinalArguments bf = new FinalArguments(). bf..g not final g. } // void f(final int i) { i++. } // Can't change // You can only read from a final primitive: int g(final int i) { return i + 1. } void without(Gizmo g) { g = new Gizmo(). you might want instead to make the nextMove method final: class ChessAlgorithm { .spin(). // OK -. . } . Final Arguments class Gizmo { public void spin() {} } public class FinalArguments { void with(final Gizmo g) { // g = new Gizmo(). the Object class does this. final void nextMove(ChessPiece pieceMoved. As just shown.6. instead of making your ChessAlgorithm class final.g is final g. All methods of final class are implicitly final.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.

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

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

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

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

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

but it allows finer control over the amount of time to wait for a notification before giving up. has elapsed. 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. See the notify method for a description of the ways in which a thread can become the owner of a monitor. 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. public final void wait(long timeout. has elapsed. int nanos) throws InterruptedException Waits to be notified by another thread of a change in this object. The current thread must own this object's monitor. The timeout period. This method is similar to the wait method of one argument. The timeout period. Summary 154 . specified by timeout milliseconds plus nanos nanoseconds arguments. The current thread must own this object's monitor. This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor. 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. specified by the timeout argument in milliseconds. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.public final native void wait(long timeout) throws InterruptedException Waits to be notified by another thread of a change in this object.

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

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

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

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

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

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

java:248) at java. For instance. to create nested packages. If we want to run at$ To use a public package member from outside its at such as Rectangle. 161 The reason is right now the HelloWorld class belongs to the package world.loadClass( Method) at java.URLClassLoader.URLClassLoader.findClass(URLClassLoader. the examples in this book have referred to types by their simple names. package abc. Within the "vis" package may be several more nested packages to do data management. "database" work. This is useful for creating a hierarchy of packages.AccessController. 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. we have to tell JVM about its fully-qualified class name (world. Circle etc. separated by dots.URLClassLoader.ClassLoader.loadClass( at java.loadClass( at at java.access$1(URLClassLoader.HelloWorld) instead of its plain class name (HelloWorld).defineClass(SecureClassLoader.SecureClassLoader. and so forth. 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.misc.2 Using package members Only public package members are accessible outside the package in which they are defined. class MyClass { } 7.defineClass(URLClassLoader. at java.renderer. there may be a project "abc" package in which are found several nested packages for "vis" work.Launcher$AppClassLoader. C:\world>java 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.

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

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

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

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

m1()". } private String p() { return "Base. } public String m2( String s ) { return "Base. Consider the following interface and class definitions: interface Foo { String m3().m3()". 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. and has therefore eliminated the possibility that developers will use undesirable methods. } public String m3() { return "Derived. } public class Base { public String m1() { return "Base.m1".This simple code change has ensured the proper concealment of information and implementation from other objects.m2(" + s + ")".p()". } } public class Derived extends Base implements Foo { public String m1() { return "Derived. That guarantees that objects instantiated from concrete classes possess implementation code for all the operations of each type specified in the implements clause. } } 166 .

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

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

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

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

5 strictfp The keyword "strictfp" is used to control certain aspects of floating-point arithmetic. they are FP-strict only if their defining class is FP-strict. violates the object-oriented design of the language. constructors. Use a class instead and then statically import the class. 7. 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(). That is." If a class. In practical terms. methods. instance initializers. You can use strictfp as a modifier of class. and static initializers within the declaration. interface. variable initializers. this means that if a class or method is declared with strictfp.This technique. interfaces. interface. you are not really implementing anything. Methods within interfaces cannot be declared using strictfp because this is an implementation rather than an interface property. interface. } public class FpDemo2 { strictfp FpDemo2() {} } The strictfp keyword is used to designate an expression as "FP-strict. 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. any expression that occurs within the class or method is an FP-strict expression. or method is FP-strict. or if it is a compile-time constant expression. Because constructors cannot be declared using strictfp. or method is declared using strictfp. An expression is FP-strict if it occurs anywhere within one of these FP-strict declarations. then the class. 171 . So too are all classes. So constants-only interfaces are ill advised and considered bad programming style . 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. and method declarations. however.

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

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

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

1 What is an Exception? The Java language uses exceptions to provide error-handling capabilities for its programs. such as a hard disk crash. The exception handler chosen is said to catch the exception. Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception. 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. until it finds a method that contains an appropriate exception handler. to simple programming errors. The runtime system searches backwards through the call stack. including its type and the state of the program when the error occurred. 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. your function might look something like this: readFile { 175 . beginning with the method in which the error occurred. In Java terminology. the runtime system (and consequently the Java program) terminates. the runtime system leaps into action to find someone to handle the exception. 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 exception object contains information about the exception. When such an error occurs within a Java method. 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. The term exception is shorthand for the phrase "exceptional event. the method creates an exception object and hands it off to the runtime system.Chapter 8 : Assertions and Exception handling 8." Many kinds of errors can cause exceptions--problems ranging from serious hardware errors. After a method throws an exception. The runtime system is then responsible for finding some code to handle the error. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. By using exceptions to manage errors. If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler.

if (gotTheFileLength) { allocate that much memory. if (theFileIsOpen) { determine the length of the file. and returning that the original 7 lines of code are lost in the clutter. } close the file. And worse yet. } else { errorCode = errorCode and -4. if (readFailed) { errorCode = -1. read the file into memory. } There's so much error detection.} open the file. allocate that much memory. At first glance this function seems simple enough. } } else { errorCode = -5. if (gotEnoughMemory) { read the file into memory. Your function would end up looking something like this: errorCodeType readFile { initialize errorCode = 0. } } else { errorCode = -3. reporting and handling. determine its size. close the file. if (theFileDidntClose && errorCode == 0) { errorCode = -4. 176 . you'd have to add a lot of code to do error detection. } return errorCode. reporting. } } else { errorCode = -2. open the file. the logical flow of the code has also been lost in the clutter. 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. read the file into memory. } method2 { call method3. } catch (memoryAllocationFailed) { doSomething. } } 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. allocate that much memory. which finally calls readFile. well. If your read_file function used exceptions instead of traditional error management techniques. Many programmers "solve" this problem by simply ignoring it--errors are "reported" when their programs crash. which calls method3. } catch (readFailed) { doSomething. it would look something like this: readFile { try { open the file. } method3 { call readFile. Java provides an elegant solution to the problem of error management: exceptions. exceptional cases elsewhere. Exceptions enable you to write the main flow of your code and deal with the. method1 { call method2. Suppose that the readFile method is the fourth method in a series of nested method calls made by your main program: method1 calls method2. } 177 . } catch (fileCloseFailed) { doSomething. determine its size. } catch (sizeDeterminationFailed) { doSomething.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. } catch (fileOpenFailed) { doSomething.

} The Java runtime system searches backwards through the call stack to find any methods that are interested in handling a particular exception. method1 { errorCodeType error. Thus only the methods that care about errors have to worry about detecting errors. else proceed. } errorCodeType method3 { errorCodeType error. } errorCodeType method2 { errorCodeType error. } catch (exception) { doErrorProcessing. else proceed. } } method2 throws exception { call method3. if (error) doErrorProcessing. thereby allowing a method further up the call stack to catch it. 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. error = call readFile. if (error) return error. } 178 .Suppose also that method1 is the only method interested in the errors that occur within readFile. if (error) return error. } method3 throws exception { call readFile. error = call method2. A Java method can "duck" any exceptions thrown within it. else proceed. error = call method3. method1 { try { call method2.

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

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

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

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

. The argument to the catch statement looks like an argument declaration for a method. SomeThrowableObject. } catch (ArrayIndexOutOfBoundsException e) { System. These statements are executed if and when the exception handler is invoked.getMessage()). and only objects that derive from Throwable can be thrown. . . An example of using multiple catch blocks 183 . the catch statement requires a single formal argument. . } 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.lang package. The catch block contains a series of legal Java statements. If the superclass catch block is written first then the catch block of subclass becomes unreachable and gives compile-time error.println("Caught IOException: "+e. . 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. try { .getMessage()). . . . The general form of Java's catch statement is: catch (SomeThrowableObject variableName) { Java statements } As you can see. . The argument type.err. . . . When Java programs throw an exception they are really just throwing an object. . You associate exception handlers with a try statement by providing one or more catch blocks directly after the try block: try { . } catch ( . .The catch Block(s) The try statement defines the scope of its associated exception handlers. ) { ) { There can be no intervening code between the end of the try statement and the beginning of the first catch statement. } catch (IOException e) { System. . 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. } catch ( . } .

class MultiCatch { public static void main (String args[]) { try { int a = args.println ("Array Index oob:" + e). } catch (ArrayIndexOutOfBoundsException e) { System. An exception handler that handles both types of exceptions looks like this: try { . } catch (ArithmeticException e) { System.println("a = " + a). .out. Also.out. int c[] ={ 1 }.out.println("Exception caught:"+e. Your exception handler can be written to handle any class that inherits from Throwable.println ("Divide by 0:" + e). } catch (Exception e) { System.").getMessage()). The closest common ancester of IOException and ArrayIndexOutOfBoundsException is the Exception class.err. 184 . } } Catching Multiple Exception Types with One Handler Each handles only one type of exception. You do this by enclosing the cleanup code within a finally block.out. The Java language allows you to write general exception handlers that handle multiple types of exceptions. } 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. c[42] = 99. 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. . System.length. int b = 42 / a .println ("After try/catch blocks. 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.

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

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

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

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

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. A method can catch an exception by providing an exception handler i. Java requires that a method either catch or specify all checked exceptions that can be thrown within the scope of the method.out.println("Exception caught"). } finally { System. using a try.out.. } } public static void main(String args[]) { try { procA().catch block for that type of exception. 189 .e.out. } procB(). procC(). } } The resulting Output is: inside procA procA's finally Exception caught inside procB procB's finally inside procC procC's finally 8.// Execute a try block normally.println("procC's finally").println("inside procC"). } catch (Exception e) { System. static void procC() { try { System.

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

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

int a[] = null.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.  StringIndexOutOfBoundsException UnsupportedOperationException Checked Exceptions defined in java. For example. j = j / j.length().length and a[0] in the following class declaration throws a NullPointerException at runtime. For example. class Null { public static void main(String args[]) { String o = null. the following code causes an ArithmeticException to be thrown: class Arith { public static void main(String args[]) { int j = 0. IncompatibleClassChangeException 192 . o. the accesses o. } } It is interesting to note that if you throw a null object you actually throw a NullPointerException. } } NullPointerException An attempt to access a variable or method in a null object or a element in a null array throws a NullPointerException. a[0] = 0.

A method that is declared in one class is deleted but other classes that access the method aren't recompiled.length(). // the cast attempt s.In general the IncompatibleClassChangeException is thrown whenever one class's definition changes but other classes that reference the first class aren't recompiled.e. when new is called. 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. a[0] = 0. } } NegativeArraySizeException A NegativeArraySizeException is thrown if an array is created with a negative size. the following code results in an OutOfMemoryException at runtime: class Link { int a[] = new int[1000000].. } } OutOfMemoryException An OutOfMemoryException is thrown when the system can no longer suppy the application with memory. For example. The OutOfMemoryException can only occur during the creation of an object. 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. String s = (String)o. 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. For example. 193 . A field that is declared in one class is deleted but other classes that access the field aren't recompiled. i. the following class definition throws a NegativeArraySizeException at runtime: class NegArray { public static void main(String args[]) { int a[] = new int[-1]. The following class declaration results in a ClassCastException at runtime: class ClassCast { public static void main(String args[]) { Object o = new Object().

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

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

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

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

println("In meth02 catch block").println("Cause is:\n" + e. }//end catch }//end meth02 void meth03(){ try{ int x = 3/0.println(). Write one of your own.9 Creating Your Own Exception Classes Choosing the Exception Type to Throw When faced with choosing the type of exception to throw. Use one written by someone else. You should go to the trouble of writing your own exception classes if you answer "yes" to any of the following questions. } catch(ArithmeticException e){ IndexOutOfBoundsException ex = new IndexOutOfBoundsException("Msg from metho03").e). throw ex.out. Otherwise.out.initCause(e).} catch(RuntimeException e){ System. System.println("Msg is:\n" + e. }//end catch }//end meth03 }//end Class01 8. System.getMessage()).out. The Java development environment provides a lot of exception classes that you could use. you have two choices: 1. 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 .out. ex. System. 2. throw new NewEx02("Msg from meth02". 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()).

parseInt(args[1]). } public DivideByZeroException(String message) { super(message). } catch(DivideByZeroException e) { System. (Errors are reserved for serious hard errors that occur deep in the system.out. } else { System. the java.public DivideByZeroException() { super("Dividing by Zero!").) Runtime exceptions don't have to be specified in the throws clause of a method. int y = Integer.println(x/y).parseInt(args[0]).println(e).println(e).out.out.lang package provides two Throwable subclasses that further divide the type of problems that can occur within a Java program: Errors and Exceptions. } } public class DivisionExample { public static void main(String args[]) { try { int x = Integer. if(y == 0) { throw new DivideByZeroException(). Most of the applets and applications that you write will throw objects that are Exceptions. } } catch(ArrayIndexOutOfBoundsException e) { System. 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. classes that inherit from the Error class should end with the string "Error". 199 . Similarly. } } } Choosing a Superclass However.

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. 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. instead of indicating by a comment that a statement should always be true you can assert that it should always be true. When a program is running normally assertions are disabled and cause no performance overhead.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.8. 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. It would be perfectly possible to write code using the constructs available in Java prior to JDK1.4. Assertions are a key part of JDK 1.10 Assertions Assertions were added to Java with the release of JDK1. but in a form that can be removed from the finally compiled version of the code so they cause no runtime overhead. 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.4 Myprog. Assertions are a feature of other Object Orientated languages and there has been pressure for a while for them to be added to Java. and if they are not an assert error will be If you then run the program normally in the form java Myprog 200 . This takes the form javac -source1. With assertions. As the name implies assertions are used to assert something that should always be true. assert statements are disabled during normal program run. Why Assertions exist? Assertions are a fairly simple concept where you write a statement that should always be true.4 version of assertions.4 and require no additional import statements in the source code. 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.

The introduction of the assert mechanism does not change this. Assert syntax 201 . avi or gif files. The same assumption may be made for code in protected or in package protected methods. mpg. If you subsequently have an issue you want to investigate and confirm that all of the assertions of items that 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. 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. Where should you use assertions? Assertions should not be used to enforce the public interface of a program. If a person has an age less than zero your program or its input has a significant problem. 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. One of the most public interfaces of a program is its command line parameters. 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. therefore you could assert that the date of death is in the future. Imagine if you had an application dealing with media types. For example it should always be true that a person has an age greater than zero. Your application might be expecting to deal with jpg. You set up a case statement that branch according to the type of file. 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.assertions are disabled and no assert exceptions will be thrown. 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. It is not appropriate to use assertions to check the parameters passed to public methods. 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. It is not appropriate to use assert to check the command line parameters of a program because assertions will not always be enabled. 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.

i. foo.m1( 1 ): " ).m1(1) : OK foo.out. } } If the assertions are disabled the output is foo. a method with any return type except void.print( "foo. The more complex version might be of the form assert (iAge > 0) :"age must be greater than zero".m1( 1 ).println( "OK" ).m1( -1) : OK If the assertions are enabled the output is 202 .out. } public static void main( String[] args ) { Foo foo = new Foo().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.m1( -1 ): " ). foo. This example is simple in that the right hand side of the expression is a simple string.print( "foo. System.e. System.out. System. but this could be any method call that returns a value. public class Foo { public void m1( int value ) { assert 0 <= value.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).

d.out.f."). Prints: false. All exception classes are subclasses of Throwable class. Questions instanceof Throwable) + ". b. There are two types of exception types: checked and runtime exceptions. Compile-time error at 1. Exception exception = new Exception(). } } What is the result of attempting to compile and run the program? a.x. Prints: true. x = 1.d.b. None of the above public static void main (String[] args) { Error error = new Error().false b. None of the above 3. 2. There are built-in api exception classes in java.g. Prints: true. System.lang.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. a = b = c = d = f = g = 0. Compile-time error at 2. Run-time error g.c.true e. Prints: false. You can also define your own exception class.true c. 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. Compile-time error f.m1(1) : OK foo. Compile-time error at 3. class A { c.false d. class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Purple { public static void main(String args[]) { int a.out.print(error instanceof Throwable). System. try { 203 .

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

205 .

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

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

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

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

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

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

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

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

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. • Resumed. A thread can enter the waiting state by invoking its sleep() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. Once a thread in the ready state gets access to the CPU. by unsuccessfully attempting to acquire an object’s lock. This thread cannot be executed now. This thread has access to CPU. • Suspended Execution is paused and can be resumed where it left off. when a thread blocks because it is waiting for some resource. The thread on which yield() is invoked would move from running state to ready state. A simple diagram is shown below: A more detailed diagram follows: 214 . To prevent this it can allow other threads to execute by invoking the yield() method. • Ready State A thread in this state is ready for execution. In single-threaded environment. • Terminated or Dead State A thread reaches "dead" state when the run method has finished execution. it gets converted to running state. or by invoking an object’s wait() method. • Blocked A resource cannot be accessed because it is being used by another 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. by blocking on I/O. the entire program stops running. A suspended thread is started. but is not being currently executed. 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. One thread can pause without stopping other parts of your program.

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

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

println("InterruptedException Caught"). On some operating systems the threading algorithm may automatically give different threads a share of the CPU time.currentThread().println(Thread. } } The output of this program. 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. 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.currentThread().8 Using the Thread yield method. For this reason the Java Thread class has a static method called yield. which causes the currently running thread to yield its hold on CPU cycles. Example of using yield() method public class TestRunner implements Runnable { public void run() { System. shown as follows when run under Windows 2000.out. } System.out. } } 217 . Volatile ensures that the value of running is examined each time the following loop iterates: while(running) { click++. The higher priority thread got approx.out. } 9.getName() + " Leaving run"). 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. 90% of the CPU time. Thread.getName() + " In run"). If no other threads are in a "ready to run state" the thread that was executing may restart running again.catch (InterruptedException e) { System. System.println("Low-Priority Thread:" + lo.println("High-Priority Thread:" + hi. on others one thread might simply hog processor resources.println(Thread. indicates that the threads did context switch even though neither voluntarily yielded the CPU nor blocked for I/ System.

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

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

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

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

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

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

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

int number) { cubbyhole = c. public Producer(CubbyHole c. i). the Producer generates an integer between 0 and 9 (inclusive). public int get() { return contents. i < 10. The rest of the code is same. To make the synchronization problem more interesting. } } public class Producer extends Thread { private CubbyHole try { sleep((int)(Math. } public void run() { for (int i = 0. 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.number = number. } 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.random() * 100)). stores it in a CubbyHole object. public class Consumer extends Thread { 225 .put(number. this. The Producer/Consumer Example In this example. i++) { cubbyhole. private int number.} synchronized(target) { target. } Only the run method is changed. } public void put(int value) { contents = value.

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

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

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

these two methods won't work. as is evidenced by the output: here I am. 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 Reentrant object's lock again. Similarly. Once the condition is true. } } //won't work! public synchronized void put(int value) { //won't work! if (available == false) { available = true. and both a and b execute to conclusion. the causing thread notifies the waiting thread to wake up and proceed from where it left off. in a() 9. put doesn't do anything. 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. CubbyHole has another private member variable. return contents. 229 . that is a boolean. available. The CubbyHole stores its value in a private member variable called contents. if the Producer calls put before the Consumer got the value. } } As implemented. contents = value. in b() here I am. Look at the get method. The essential idea is that one thread needs a certain condition that can be brought about by another thread to become true. 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. What happens if the Producer hasn't put anything in the CubbyHole and available isn't true? The get method does nothing. Here's one possible implementation for the put and get methods: public synchronized int get() { if (available == true) { available = false.

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

The put method works in a similar fashion. Both wait and sleep delay for the requested amount of time. } } Here’s the output of ProducerConsumerTest: Producer Consumer Producer Consumer #1 #1 #1 #1 put: got: put: got: 0 0 1 1 231 . but it could be important for threads that sleep for minutes at a time. a Producer. you also can use them in place of sleep. This doesn't matter too much for threads that don't sleep for long. called ProducerConsumerTest. p1. 1). Producer p1 = new Producer(c. The notifyAll method wakes up all threads waiting on the object in question (in this case. You can easily wake up wait with a notify but a sleeping thread cannot be awakened prematurely. Running the Producer-Consumer Example Here’s a small standalone application. timeout is measured in milliseconds. int nanos) Waits for notification or until timeout milliseconds plus nanos nanoseconds have elapsed. wait(long timeout. which arbitrarily wakes up one of the threads waiting on this object.start().start(). The Object class also defines the notify method. 1). Note: Besides using these timed wait methods to synchronize threads. One thread gets it. 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 awakened threads compete for the lock. It waits for the Consumer thread to consume the current value before allowing the Producer to produce a new one. the CubbyHole). and the others go back to waiting. Consumer c1 = new Consumer(c. c1. that creates a CubbyHole object. 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 ultimate form of starvation. Deadlock. If the user doesn’t want a clock. these two threads can run forever in lock-step. effectively managing to achieve nothing at all. as a result. A fair system prevents starvation and deadlock.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. Once suspended. Whatever the case. For example. so what is done by the first thread is undone by another. a separate thread can be used to display the time of the day. This usually happens when the two threads are working at cross-purposes. (A common real world example is when two people approach each other in a narrow corridor. A system is fair when each thread gets enough access to limited resources to make reasonable progress. 232 . Livelocks A livelock. but no work gets done.15 Suspending. This continues for some time. unlike a deadlock. thereby ensuring that neither can pass. Now imagine a situation wherein each thread puts down the object it possesses and picks up the object put down by the other thread. with both of them swaying from side to side and no progress being made. cannot make progress. you must take precautions to ensure fairness.) 9. A simple example is where each thread already holds one object and needs another that is held by the other thread. suspending a thread is a simple matter. Starvation occurs when one or more threads in your program are blocked from gaining access to a resource and. Resuming & Stopping Threads Sometimes suspending execution of a thread is useful. occurs when two or more threads are waiting on a condition that cannot be satisfied. Each person tries to be polite by moving to one side to let the other one pass.14 Starvation and Deadlock If you write a program in which several concurrent threads are competing for resources. Deadlock most often occurs when two (or more) threads are each waiting for the other(s) to do something. Clearly. but both keep moving to the same side at the same time. restarting the thread is also a simpler matter. then its thread can be suspended. happens when threads are actually running.

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

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

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

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

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

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

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

int.length().e. RegionMatchesDemo.out.println (str. foundIt = true.out. } if (foundIt) { System. 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. The program steps through the string referred to by searchMe one character at a time. For each character. if true. 0. boolean foundIt = false. the case is ignored when comparing characters. The boolean argument indicates whether case should be ignored. int len = findMe. i+len)). String findMe = "Eggs". len)) { i++. String. int) boolean regionMatches(boolean. int) This method tests whether the specified region of this string matches the specified region of the String argument. i.substring(i. The charAt method 240 . // a negative number.System. 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. 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". } } } The output from this program is Eggs. while (!searchMe.regionMatches(i. int.compareTo(str2)). findMe. The following program.println(searchMe. String. int. int i = 0. int compareToIgnoreCase(String str) The regionMatches method boolean regionMatches(int.

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

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

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

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

lastIndexOf(pathseparator).substring(sep + 1.substring(dot + 1). then lastIndexOf() returns -1.} } The indexOf() and lastIndexOf() methods are frequently used in conjunction with substring() which returns a substring of the string. return fullpath. pathseparator = sep.'). notice that extension() uses dot + 1 as the argument to substring(). return fullpath. if the filename does not have a period ('. Then substring() uses the return value of lastIndexOf() to extract the filename extension--that is. 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).') character is the last character of the string.'). return fullpath. dot).substring(0. sep).') to the end of the string. int sep = fullpath. and the substring() method throws a "string index out of range exception".lastIndexOf('.') in the filename. char pathseparator.lastIndexOf(pathseparator). The following class illustrates the use of lastIndexOf() and substring() to isolate different parts of a filename. the substring from the period ('. This code assumes that the filename actually has a period ('.'). 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". Also. char sep) { fullpath = str. } String extension() { int dot = fullpath. } } The extension() method uses lastIndexOf() to locate the last occurrence of the period ('. However. If the period ('. class Filename { String fullpath. Filename(String str. } String filename() { int dot = fullpath. While the methods in the example above uses only one version of the lastIndexOf() method. } String path() { int sep = fullpath. 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 .') in it.lastIndexOf('.

This method uses the concept of a regular expression to specify the delimiters. or tokens. int startIndex) boolean endsWith(String str) For example.   returns the index of the first (last) occurrence of the specified character.startsWith(“Foo”).4 added the split() method to the String class to simplify the task of breaking a string into substrings. 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. searching forward (backward) from the specified index returns the index of the first (last) occurrence of the specified String. 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. 246 . both return true “Foobar”. boolean startsWith(String str) boolean startsWith(String str.3) returns true The split method J2SE 1.endsWith(“bar”). returns the index of the first (last) occurrence of the specified String. The endsWith determines whether the String ends up with a specified String. “Foobar”. A regular expression is a remnant from the Unix grep tool ("grep" meaning "general regular expression parser"). “Foobar”.startsWith(“bar”.

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

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

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

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

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

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

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

The same code using String objects would require more than eight objects.out.append("Hello”). The append method can be used to append values together. System.append("Hello"). StringBuffer append(Object obj) Appends the string representation of the Object argument to this string and sends it to the standard output. 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. rb. sb.println(b. StringBuffer rb = new StringBuffer(). This method allows data of any of the simple data types to be added to the end of a StringBuffer.append(" ").append("World!").println(sb. StringBuffer b = new StringBuffer(). StringBuffer append(String str) Appends the string to this string buffer. sb. now holds the value of "Hello World!". The append method is called on a StringBuffer object with the data to be added as an input parameter.append(".append("l"). The StringBuffer variable.toString()).append("r"). Notice that the code takes advantage of the toString method of the StringBuffer class.append("u"). sb.out. StringBuffer sb = new StringBuffer().com"). This code creates the string Builder. but only one object is created. sb.append("World"). sb.append("i"). sb.append("d").append("B"). rb. One more example 254 . System. sb. sb.toString()). This method converts the contents to a String object that can be used for output. This is achieved by the method being overloaded for all of the simple data types and using the valueOf method.StringBuffer append(long longValue) Appends the string representation of the long argument to this string buffer. This allows text to be manipulated accordingly and used for output or data storage.append("e"). is awesome! Builder. } } The following output is produced : After replace : This was a test The replace method public StringBuffer replace(int start.println(sb. String str) Replaces the characters in a substring of this StringBuffer with characters in the specified String. System. The length property is reset so that the text is truncated.delete(4. 255 . int end) Removes the characters in a substring of this StringBuffer. int end.setLength(11).7).out.out.toString()). System.append(" The delete method StringBuffer delete(int is awesome!").println(“After delete :” + sb). System. The output follows: sb.out.deleteCharAt(0). sb. //demonstrate delete and deleteCharAt class deleteDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer(“This is a test”).println(“After deleteCharAt : ” + sb). This code sets the capacity and populates the object with a string. System. The reverse method StringBuffer reverse() The character sequence contained in this string buffer is replaced by the reverse of the sequence.toString()). The deleteCharAt method StringBuffer deleteCharAt(int index) Removes the character at the specified position in this StringBuffer (shortening the StringBuffer by one character).println(sb.out.

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

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

String a = 'a'. b. 1 2. e. d. None of the above 258 . 2 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. 4 } public static void main (String[] args) { // Insert code here. String d = '\uabcd'. class MCZ20 { b. 3 d. String b = 'abc'. c. String c = '\u0041'.

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

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

The InputStream class is an abstract base class that provides a minimal programming interface and a partial implementation of input streams in Java. 261 . 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). ObjectInputStream and ObjectOutputStream. skipping bytes of input. Two of the byte stream classes.To read and write 8-bit bytes. and resetting the current position. both Reader and InputStream provide methods for marking a location in the stream. are used for object serialization. descendants of InputStream and OutputStream. Reader contains these methods for reading characters and arrays of characters: Reader int read() int read(char cbuf[]) int read(char cbuf[]. 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. Character Streams Reader and Writer are the abstract superclasses for character streams in java. int offset. OutputStream defines methods for writing bytes or arrays of bytes to the stream and flushing the stream. or let it be closed implicitly when the object is garbage An output stream is automatically opened when you create it. An input stream is automatically opened when you create it. These streams are typically used to read and write binary data such as images and sounds. You can explicitly close an output stream with the close() method. skipping input. and resetting the current position within the stream. int offset. For example. int length) Also. You can explicitly close a stream with the close() method. programs should use the byte streams. or let it be closed implicitly when the object is garbage collected. finding out the number of bytes that are available for reading. The OutputStream class is an abstract base class that provides a minimal programming interface and a partial implementation of output streams in Java. marking locations in the stream. 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. The InputStream class defines a methods for reading bytes or arrays of 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[].

int offset. writers. int length) All of the streams--readers. Note that many's streams and describes what they do. int offset. 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 . and output streams--are automatically opened when created. Writer defines these methods for writing characters and arrays of characters: int write(int c) int write(char cbuf[]) int write(char cbuf[]. int length) And OutputStream defines the same methods but for bytes: int write(int c) int write(byte cbuf[]) int write(byte cbuf[]. which occurs when the object is no longer referenced. Stream classes The following table lists java. Or the garbage collector can implicitly close it. You can close any stream explicitly by calling its close method. java. input contains character streams and byte streams that perform the same type of I/O but for different data types.Writer and OutputStream are similarly parallel.

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

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

System. To obtain a character-based stream that is attached to the console. Reader is an abstract class. console input is accomplished by reading from System.out and System. that converts bytes to characters.err are objects of type PrintStream. BufferedReader stdin =new BufferedReader( new InputStreamReader(System. To obtain InputStreamReader is an object of the type InputStream. System.out. Its general form is shown here: String readLine() throws IOException An example of reading an entire line of input from console import java. } } } One example that reads from the console and prints the same string and terminates when an empty string is entered. 265 .readLine()).in in a BufferedReader use the following constructor: InputStreamReader (InputStream inputStream) Because System. System. to create a character stream. it can be used for inputStream.println(e). you wrap System. } catch(IOException e) { System. even though they typically are used to read and write characters from and to the console.out.print("Enter a line:"). InputStreamReader is its concrete sub-class. BufferedReader supports buffered input The readLine() method is a member of BufferedReader 11. These are byte streams.*.2 Reading console input In public class ConsoleInputDemo { public static void main(String[] args) { try { BufferedReader stdin =new BufferedReader( new InputStreamReader( refers to an object of type InputStream. 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.*. BufferedReader br = new BufferedReader ( new InputStreamReader(System. In this example we simply wrap the 16-bit encoded OutputStreamWriter class around the usual System.3 Writing console output This example prints a single character on the console. } } } An example of reading characters import java. 266 .out.printStackTrace().out stream. class BRRead { public static void main(String args[]) throws IOException{ char c.length() != 0) { System. System.out. String s = } while( c != ‘q’).io. ‘q’ to quit:”). public class Echo { public static void main(String[] args) { DataInputStream in = new DataInputStream( new BufferedInputStream(System.out. System.*. //read characters do { c = (char) br. try { while((s = in.import } // An empty line terminates the program } catch(IOException e) { We can obtain many print() and println() overloaded methods with the PrintWriter class. import java. } } 11. The OutputStreamWriter class only has a few basic write() methods.println(s).*.println(“Enter characters .

} } } 11. i++) { c = s. try { for( int i = 0.public class SingleCharConsole16bit { public static void main(String f[]) { char c. public class StringOutput { public static void main(String f[]) { PrintWriter pw = new PrintWriter(System.true). } catch (IOException ioe) { System. 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.out.text. // Wrap the System. } catch (IOException ioe) { System.out). OutputStreamWriter osw = new OutputStreamWriter(System.*.flush().out 8-bit stream with the 16-bit // output stream.println( "IO error:" + ioe ). import java. String s = “Hello” } osw.out. String s = “Hello”. osw.println(s).4 System. which provides a wide range of formatting options combined with output operation. i< s.println( "IO error:" + ioe ).length().write(c).charAt(i).printf() The java. try { pw.out.Format subclasses offer limited formatting capabilities and are rather clumsy compared to the C language printf() function. 267 . } } } Another example that prints a String on the console using PrintWriter class.

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

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

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

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*; 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]);


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*; 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*; 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(); } } }


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.


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*; 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*; 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);


FileWriter out = new FileWriter(outputFile); int c; while ((c = != -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 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*; class FileOutputDemo { public static void main(String args[]) { FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object try {


} 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*; 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 = != -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*; 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 ) {


} }

} 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*; 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*; public class TestEOF { public static void main(String[] args) { try { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream(""))); while(in.available() != 0) { System.out.print((char)in.readByte());


} }

} } 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*; 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 = != -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*; 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);


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

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

out. System. System.setIn(in).out").} } System. // close file output stream } catch(IOException e) { e. } } } 281 .8 Redirecting Standard I/O The methods in System class allow you to redirect the standard input. Sample output: Enter int.*. Here’s a simple example that shows the use of these methods: import java.close(). double. output.readLine()) != null) { System. BufferedReader br = new BufferedReader( new InputStreamReader(System. // write it to another file } out.println(a + ":" + x + ":" + word + ":" + line).56:Great: time had by all! 11. Redirecting input is valuable for a command-line program in which you want to test a particular user-input sequence repeatedly. while((s = br. 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.56 Great time had by all! -12:34. word.println(s).setOut(out).true)).io. //reads from the file String")). line: -12 34. class Redirecting { public static void main(String[] args) { try { BufferedInputStream in = new BufferedInputStream( new FileInputStream("Redirecting.printStackTrace(). PrintStream out = new PrintStream(new BufferedOutputStream( new FileOutputStream("test.setErr(out).

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

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

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

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

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

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

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

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

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

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); } }

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 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.


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


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,


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)


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);


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:


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;


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,


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

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

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

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

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

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

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

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

vendor" "java.arch" "os. System.class.url" "java. to get the file separator character of the" Meaning File separator (for example.home" "user.class.println(name).name").Here is a complete list of the system properties you get when the runtime system first starts up and what they mean: Key "" "os.home" "java.out.getProperty("user. You can use a key to look up one property in the properties list. you can use the method System.vendor.getProperty(“file. An example to get the user name : class UserNameTest { public static void main(String[] args) { String name. You can also change the set of system properties completely. } } 307 .separator" "java. For example. "/") 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.path" "java.separator" "user.version" "line. name = 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. or you can get the whole set of properties all at once.version" "java.version" "path.separator" "os.separator”).dir" "user.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

FEBRUARY.00).DATE)+”/”+ (c.out.HOUR.println(c.MINUTE)+”/”+ c.MINUTE)+”/”+ c. int month. int dayOfMonth. System.00). int hours. int dayOfMonth) GregorianCalendar (int year. int dayOfMonth.get(Calendar.Note that the months are called JANUARY.SECOND.get(Calendar. System.out. such as isLeapYear().out. int minutes) GregorianCalendar (int year.MINUTE. System. It adds a number of public constructors. boolean isLeapYear(int year) The getInstance() method of Calendar returns a GregorianCalendar object. initializes the object with the current date and time in the default locale and timezone.HOUR)+”/”+ c. 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.util.getInstance().HOUR)+”/”+ c.get(Calendar. The default.set(Calendar. c.*.. There is also a field UNDECIMBER.get(Calendar. irrespective of location (as opposed to more neutral names such as MONTH_1.get(Calendar.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. Also there are some more like GregorianCalendar (int year. } } 13.SECOND)).print(“Time:”). There are several constructors of GregorianCalendar class. MONTH_2.get(Calendar.MONTH)+1)+”/”+ c.10 GregorianCalendar class The class GregorianCalendar is the only commonly available subclass of Calendar.get(Calendar.out.get(Calendar. System. 325 .print(“Updated Time:”). int month. int month. System.set(Calendar. c. which is required by some (nonGregorian) calendars. as well as some functions specific to Gregorian Calendars.get(Calendar. and so on). etc. System. An example using Calendar class import java.out.SECOND)).print(“Date :”).set(Calendar.10). representing the 13th month of the year.out.println(c. //set the time and print it c.println(c.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

*. import java.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.format(date). public class test { public static void main (String args[]) { Date date = new Date(). System.text. Text information is displayed in an abbreviated form if the pattern letter is repeated less than four times. the number of times a symbol is repeated determines how that data is presented. One example of using SimpleDateFormat import java.println(rptDate+"\n").*. SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd hh:mm"). } } One more example to format and parse it back. the number of times a pattern letter is repeated determines how many digits are presented.format(now). Three or more repetitions of M cause the month to be displayed as a text string.util. String logEntry = formatter. Otherwise unabbreviated form is used. String rptDate = sdf. 349 . For numbers. M or MM causes the month to be displayed as one or two digits. // Create a formatter with the following pattern: //Hour(0-23):Minute:Second SimpleDateFormat formatter = new SimpleDateFormat( "HH:mm:ss" ).out. Date now = new Date().

The first element in the array argument of setShortWeekdays is a null String. and time zones.getShortWeekdays(). 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.// To read the string back in try { Date sometime = formatter. } System. The SimpleDateFormat constructor accepts the modified DateFormatSymbols object as an argument. Here is the source code: DateFormatSymbols symbols = new DateFormatSymbols( new Locale("en". i++) { System. for (int i = 0.print(defaultDays[i] + " "). 1998.3 DateFormatSymbols class The format method of the SimpleDateFormat class returns a String composed of digits and symbols."US")). For example. April 10.parse( logEntry ). in the String "Friday. String [] defaultDays = symbols. among others. i < defaultDays. } catch ( ParseException exc ) { exc. you can change them with the DateFormatSymbols. You can change symbols that represent names for months.out.out.length. } Note the ParseException that needs to be caught. Therefore the array is one-based rather than zero-based. 15. The full source code for this example is in DateFormatSymbolsDemo." If the symbols encapsulated in SimpleDateFormat don't meet your needs. 350 ." the symbols are "Friday" and "April. days of the week.printStackTrace(). It is thrown when the beginning of the input string cannot be parsed.println().

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

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

##0.out. If you want to change formatting symbols. If one is not specified. grouping (thousands) separators. These classes offer a great deal of flexibility in the formatting of numbers.format(value). The example that follows creates a formatter by passing a pattern String to the DecimalFormat constructor.Double percent = new Double(0. 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. The pattern determines what the formatted number looks like. you can use the DecimalFormatSymbols in conjunction with the DecimalFormat class. NumberFormat percentFormatter = NumberFormat. The format method accepts a double value as an argument and returns the formatted number in a String: DecimalFormat myFormatter = new DecimalFormat(pattern).75). . System. String output = myFormatter.format(percent). String percentOut = percentFormatter. The applyPattern() method can be used to change this pattern. 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. such as the decimal separator.00. ' 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. 15.($#. and the decimal separator.##0. 353 . prefixes and suffixes.getPercentInstance(currentLocale). a DecimalFormatSymbols object suitable for the default locale is used. This class allows you to control the display of leading and trailing zeros. but they can make your code more complex.5 DecimalFormat class You can use the DecimalFormat class to format decimal numbers into locale-specific strings.println(value + " " + pattern + " " + output).00)" Char 0 # . For example: "$#. % .

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

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

0.333e+000".0/3. import java.0/3.*.For example.0 = " + qValStr). System.3e").out. qValStr = new Format ("%0. class FormatDemo { public static void main(String args[]) { double q = 1. An instance of the format must first be created with the desired formatting description. double q =10. // Can change the format pattern: qValStr = new Format ("%0.out.5f"). // The # symbol indicates trailing blanks q = 1.format (q). System.4f".out.println ("1000.print("0. // Create an instance of the format pattern // and then create the string with the method format String qValStr = new Format ("%0. 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.println ("1.3f"). will result in an output of 3. // q = 1000.0/4567.0. System.0/3.0.0. String str = new Format("0.text.0 = " + qValStr).0.0. q). the class provides several overloaded format(arg) methods.println ("1.0/3.println ("1.0 = " + qValStr). Format.format (q).0 = " + qValStr).2e").format(q) which results in the string variable str referencing "3.out. where arg is a number type.0/3.0/3. The following program shows the use of Format class.3333 To send formatted outputs directly to a string.0/2. qValStr = new Format ("%0.format (q).format (q). System.0/2. // q = 3. 356 .5g").0/3.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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. if=1. be=1. is=2. delegate=1} This flexibility provides a potent illustration of the power of an interface-based framework. is=2} Suppose you'd prefer to see the frequency table in alphabetical order. By convention. 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. 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. In addition to its obvious use of dumping one Map into another. 385 . The putAll operation is the Map analogue of the Collection interface's addAll operation. if=1. me=1. delegate=1. it=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. All you have to do is change the implementation type of the Map from HashMap to TreeMap. The following one-liner creates a new HashMap initially containing all of the same key-value mappings as m: Map<K. Like the Set and List interfaces. it=2. to=3. regardless of the other Map's implementation type. Making this fourcharacter change causes the program to generate the following output from the same command line: 8 distinct words: {be=1. it=2. Map Interface Bulk Operations The clear operation does exactly what you think it does: it removes all the mappings from the Map. up=1. suppose you have a Map. Two Map instances are equal if they represent the same key-value mappings. named m. 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.word has never been seen before or one more than its current value if the word has already been seen. it has a second. me=1. be=1. more subtle use. is=2. Doing so results in the following output: 8 distinct words: {if=1. me=1. V> copy = new HashMap<K. delegate=1. up=1} Similarly. up=1. For example. to=3. V>(m).

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

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

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

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

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

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

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

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

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

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

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

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

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

On the other hand. //error If you try this you will notice that the last statement produces a compilation error.println(o). 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.println(o).. } } 399 . List<Object> 16. //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.. .out. printall(list). written as Collection<?>: public void printAll(Collection<?> c) { for (Object o : c) { System.. 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.out. } } You might choose to create a list of strings and use this method to print all the strings: List<String> list = new ArrayList<String>(). printall(list).println(o). .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.. namely Object.out.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. } } List<Object> list = new ArrayList<Object>(). regardless of the type of objects contained in the collection: public void printAll(Collection<Object> c) { for (Object o : c) { System. Suppose you would like to write a method that prints out a collection of objects.

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

i++) { list. } 401 . } String filler = args[0].fill(list. The type parameters of generic methods generally are independent of any class or interface-level type parameters.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). for (int i = 0. One difference between generic types and generic methods is that generic methods are invoked like regular methods. The type parameters are inferred from the invocation context. .. as in this invocation of the fill method: public static void main(String[] args) { List<String> list = new ArrayList<String>(10). Collections.add(""). filler).. i < 10.

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

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

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

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

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

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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer: Get 4 months of Scribd and The New York Times for just $1.87 per week!

Master Your Semester with a Special Offer from Scribd & The New York Times