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.


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

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

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

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

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

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

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

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

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

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

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

or a memory address in other languages.1 Data Types The Java programming language has two categories of data types: primitive and reference. positive value: (2-2-23)*2127. Arrays. You use the variable's name instead. 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. positive value: 2-149 20 .Chapter 2 : Data types. int anInt = 4. variables and Arrays 2. A variable of primitive type contains a single value of the appropriate size and format for its type: a number. Min. The value of a reference type variable. or a boolean value. in contrast to that of a primitive type. classes. Range of primitive data types Primitive Type Size Range of Values byte 8 bit -27 to 27-1 short 16 bit -215 to 215-1 int 32 bit -231 to 231-1 long 64 bit -263 to 263-1 char 16 bit '\u0000' to '\uffff'(0 to 216-1 ) float 32 bit Max. a character. and interfaces are reference types. The Java programming language does not support the explicit use of addresses like other languages do. A reference is called a pointer. is a reference to (an address of) the value or set of values represented by the variable.

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

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

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

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

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

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

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

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

Questions 1. 1 2 3 4 5 None of the above 29 . you use the length attribute.The length of the array must be specified when it is created. Once created. the size of the array cannot change. 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. b. e. To copy an array. or you can use an array initializer. d. // 5 A compile-time error is generated at which line? a. // 3 = '\b'. c. // 2 = '\"'. // 4 = '\''. // 1 = '\r'. use the arraycopy method in the System class.You can use the new operator to create an array. Indices begin at 0 and end at the length of the array minus 1. f. To get the length of the array.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5556 80 26. All other operators (see precedence table above) are evaluated left to right. } } } Here's the output: 0 -17. fahr = fahr + step.889 Everything inside the parentheses will be calculated before anything outside of the parentheses is calculated.8889 140 60 160 71. Operator Associativity The following operators have Right to Left associativity.3333 220 104. 48 .7778 120 48.778 300 148.0 / 9. double fahr = lower.2222 200 93.1111 180 82.667 280 137.out.66667 40 4.0) * (fahr-32. while (fahr <= upper) { double celsius = (5.0.556 260 126.6667 100 37.7778 20 -6.0).double step = 20.444 240 115.println(fahr + " " + celsius).44444 60 15. System.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

} }

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

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

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

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


} }


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


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

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

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

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

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

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

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

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.


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

127 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

the logical flow of the code has also been lost in the clutter. } else { errorCode = errorCode and -4. if (gotTheFileLength) { allocate that much memory. allocate that much memory. determine its size. } close the file. if (gotEnoughMemory) { read the file into memory. and returning that the original 7 lines of code are lost in the clutter. Your function would end up looking something like this: errorCodeType readFile { initialize errorCode = 0. open the file. if (readFailed) { errorCode = -1.} open the file. 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. reporting and handling. } There's so much error detection. } } else { errorCode = -3. reporting. close the file. you'd have to add a lot of code to do error detection. At first glance this function seems simple enough. } } else { errorCode = -2. if (theFileDidntClose && errorCode == 0) { errorCode = -4. read the file into memory. if (theFileIsOpen) { determine the length of the file. } return errorCode. 176 . } } else { errorCode = -5. And worse yet.

exceptional cases elsewhere. If your read_file function used exceptions instead of traditional error management techniques. } catch (readFailed) { 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. Suppose that the readFile method is the fourth method in a series of nested method calls made by your main program: method1 calls method2. } catch (memoryAllocationFailed) { doSomething. } 177 . } method2 { call method3. determine its size. } catch (sizeDeterminationFailed) { doSomething. close the file.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. which finally calls readFile. Exceptions enable you to write the main flow of your code and deal with the. } method3 { call readFile. Many programmers "solve" this problem by simply ignoring it--errors are "reported" when their programs crash. } catch (fileCloseFailed) { doSomething. Java provides an elegant solution to the problem of error management: exceptions. read the file into memory. which calls method3. method1 { call method2. } catch (fileOpenFailed) { doSomething. well. allocate that much memory. it would look something like this: readFile { try { open the file.

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

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

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

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

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

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

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

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

then a divide-by-zero exception will be generated by the following code*/ if (a == 1) a = a / (a – a).length. Nesting of try statements can occur in less obvious ways when method calls are involved. //An Example of nested try statements. class NestTry { public static void main (String args[]) { try { int a = args. You can enclose a call to a method within a try block. /* if no command-line args are present the following statement will generate a divide-by-zero exception*/ int b = 42 / a. which calls the method. If an inner try statement does not have a catch handler for a particular exception. System. // division by zero /* if two command line arg is used . or until the entire nested try statements are exhausted. If no catch statement matches. In this case. try //nested try block { /* if one command line arg is used . Inside that method is another try statement. //generate an out of bound exception } } catch (ArrayIndexOutOfBoundsException e) { System.*/ if( a = 2 ) { int c [] = { 1 }. This continues until one of the catch statements succeeds. the context of that exception is pushed on the stack. c[ 42 ] = 99.out. then generate an out of bounds exception .println(e).Each time a try statement is entered.out. the stack is unwound and the next try statement’s catch handlers are inspected for a match. the try statement within the method is still nested inside the outer try block. then the Java runtime system will handle the exception. } } catch (ArithmeticException e) { 186 .println(“a = “ + a). Cannot throw class java. If you attempt to throw an object that is not throwable.lang. the compiler refuses to compile your program and displays an error message similar to the following: testing.1.4 The throw Statement All Java methods use the throw statement to throw an exception. setObjectAt(size . 187 . throwable objects are instances of any subclass of the Throwable class. it must be a subclass of class java. return obj. throw new Integer(4). Sample outputs: 1) C:\> java NestTry Divide by zero. The throw statement requires a single argument: a throwable object. 2) C:\> java NestTry One a = 1 divide by zero 3) C:\> java NestTry One Two a = 2 Array index out of bounds. if (size == 0) throw new EmptyStackException().1). public Object pop() throws EmptyStackException { Object obj. Here's an example of a throw statement: throw someThrowableObject.Throwable.Integer. } The EmptyStackException class is defined in the java. obj = objectAt(size .lang. In the Java system.println(“Divide by zero”). 8. null). size--.} } } System.util package.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

205 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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,


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful