Java Quick Reference

Java Quick Reference

Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

Welcome fellow Java enthusiasts!
This site grew out of a desire to store all the information I discovered in my study of the Java Language in one easily accessible location and format. If you're brand new to Java you may want to begin by working your way through a number of the on-line tutorials. Click on Favourite Links and then choose Tutorials for a list of what's available on the Web. If you're studying for the Sun Certfied Java Programmer Exam (SCJP) click on SCJP2 Study Notes. You'll find a collection of notes I made while studying for my own SCJP certification which I'm happy to say I passed on December 14th, 2000. All the best in your studies! Jane

The Java Certification Web Ring
[Previous] [Next] [Random] [List Sites] [Join Ring]

http://www.janeg.ca/ [15/03/2004 8:46:18 AM]

Java Quick Reference

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package

SCJP2 Study Notes
This section contains study notes for the Sun Certified Java 2 Programmer Exam (SCJP2). The objectives are based on the Testing Objectives for the New Sun Certified Programmer for Java 2 Platform posted on Sun's site as of October 1st, 2000. The exam consists of 59 questions. A passing mark of 61% is required. The time limit, originally 90 minutes, has now been increased to 120 minutes.

NEW 1.4 EXAM as of August, 2002
Sun introduced a new exam version in August, 2002. I've marked up my pages to indicate which objectives have been dropped or added; and, where possible, provided a link to study materials related to the new objectives. !!! ALWAYS CHECK SUN'S SITE FOR THE LATEST OBJECTIVES !!!

Usage
q q

q

References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

q q

use the menu on the left to navigate the various Certification Objective pages use the menu on the bottom of the Objective and note pages to navigate notes related to the selected Objective save and compile the Code Examples to see Java concepts in action Tips are things to be keep in mind when taking the exam Traps are things to watch out for when taking the exam Testing concepts

If you're having a problem with a concept, WRITE SOME CODE to test it! DO NOT use an IDE! Compile all your test code from the command line; this ensures you'll see all the errors the compiler may create.

Why get certfied?
Read an on-line article by David L. Hecksel and Marcus Green in The Certification Magazine

!!! Study Tip !!!
Visit JavaRanch on a regular basis! It's the best site on the Web if you want to learn everything and anything about Java! Pick up a good certification study guide. There are a number of excellent ones on the market, The Complete Java 2 Certification Study Guide: Programmer's and Developers Exams (With CD-ROM) a.ka. RHE is a favourite of many JavaRanchers. Of course, I like the one I co-authored with my fellow JavaRanch moderators the best<g>

http://www.janeg.ca/java2.html (1 of 2) [15/03/2004 8:46:20 AM]

Java Quick Reference

Mike Meyer's Java 2 Certification Passport by Cindy Glass, Jane Griscti, Margarita Isayeva, Ajith Kallambella, and Kathy Sierra A concise, affordable and portable guide to Sun's Java 2 Exam 310-025 Errata Page Best of luck in your studies!

http://www.janeg.ca/java2.html (2 of 2) [15/03/2004 8:46:20 AM]

Java Quick Reference - Language Fundamentals

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes

Language Fundamentals Certification Objectives
q

Identify correctly constructed source files, package declarations, import statements, class declarations (of all forms including inner classes), interface declarations and implementations (for java.lang.Runnable or other interfaces described in the test), method declarations (including the main method that is used to start execution of a class), variable declarations and identifiers. State the correspondence between index values in the argument array passed to a main method and command line arguments. Identify all Java programming language keywords and correctly constructed identifiers. State the effect of using a variable or array element of any kind when no explicit assignment has been made to it. State the range of all primitive data types and declare literal values for String and all primitive types using all permitted formats, bases, and representations.

q

q

q

1.4 Exam Objectives
The objectives are basically the same; the first objective in 1.2 has been restated as: q Identify correctly constructed package declarations, import statments, class declarations (of all forms including inner classes) interface declarations, method declarations (including the main method that is used to start execution of a class), variable declarations and identifiers.
q

Identify classes that correctly implement an interface where that interface is either java.lang.Runnable or a fully specifiec interface in the question.

The second 1.2 objective has been split with an additional note on 'keywords' q State the correspondence between index values in the argument array passed to a main method and command line arguments.
q

SCJD Notes Projects Favourite Links About Feedback

Identify all Java programming language keywords. Note: There will not be any questions regarding esoteric distinction between keywords and manifest constants.

Source Methods Primitives

Package main() # Literals

Import Identifiers char Literal

Class Keywords

Interface Defaults

Constructors Arrays

String Literals Class Literals

http://www.janeg.ca/scjp/language.html [15/03/2004 8:46:20 AM]

Java Quick Reference

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

Operators and Assignments Certification Objectives
( 1.4 Objectives are identical ) q Determine the result of applying any operator, including assignment operators and instanceof, to operands of any type, class, scope, or accessibility, or any combination of these.
q

Determine the result of applying the boolean equals(Object) method to objects of any combination of the classes java.lang.String, java.lang.Boolean, and java.lang.Object. In an expression involving the operators &, |, &&, ||, and variables of known values state which operands are evaluated and the value of the expression. Determine the effect upon objects and primitive values of passing variables into methods and performing assignments or other modifying operations in that method.

q

q

Conversions Bin/Hex/Octal Cast Method Invocation

Promotion Bitwise Ternary

Overflow Shift String

Unary Comparison equals()

Prefix Logical Precedence

Arithmetic Assignment Bit vs Logic

http://www.janeg.ca/scjp/operatorsAndAssignments.html (1 of 2) [15/03/2004 8:46:20 AM]

Java Quick Reference

http://www.janeg.ca/scjp/operatorsAndAssignments.html (2 of 2) [15/03/2004 8:46:20 AM]

Java Quick Reference

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

Flow Control and Exception Handling Certification Objectives
q

Write code using if and switch statements and identify legal argument types for these statements. Write code using all forms of loops including labeled and unlabeled use of break and continue, and state the values taken by loop control variables during and after loop execution. Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding methods that throw exceptions.

q

q

1.4 Exam: Additional objectives
q

Recognize the effect of an exception arising at a sepcified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination). Write code that makes proper use of assertions, and distinguish appropriate from inapporopriate uses of assertions. Identify correct statements about the assertion mechanism.

q

q

For additional study materials try: Sun: Programming with Assertions Developerworks: Working with Assertions JavaWorld: Understand the mechanics of ... new assertion facility

Statements Labels

if Exceptions

switch Handling Exceptions

for try-catch-finally

while

do

http://www.janeg.ca/scjp/flow.html [15/03/2004 8:46:21 AM]

Java Quick Reference

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package

Declarations and Access Control Certification Objectives
( 1.4 objectives are identical ) q Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and initialization. (Covered under Language Fundamentals - Array Initialization)
q

Declare classes, inner classes, methods, instance variables, static variables, and automatic (method local) variables making appropriate use of all permitted modifiers (such as public, final, static, abstract, and so forth). State the significance of each of these modifiers both singly and in combination, and state the effect of package relationships on declared items qualified by these modifiers. For a given class, determine if a default constructor will be created, and if so, state the prototype of that constructor. (Covered under Language Fundamentals - Constructors) State the legal return types for any method given the declarations of all related methods in this or parent class. (Covered under Language Fundamentals - Method Declarations)

q

q

The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback
q q

Additional References
q

Chapter 6 Objects and Classes from The Complete Java 2 Certification Stuyd Guide by Simon Roberts, Philip Heller, Michael Ernest Sun Tech Tip: Using Class Methods and Variables Sun Tech Tip: Global Variables

Access Modifiers

Special Modifiers

this and super

Scope

Inheritance

Access Control

http://www.janeg.ca/scjp/declarations.html [15/03/2004 8:46:21 AM]

awt Package The java.lang Package The java.4 Exam The above objective has been expanded as: q State the behavior that is guaranteed by the garbage collection system. Recognize the point in a piece of source code at which an object becomes eligible for garbage collection.util Package The java.html [15/03/2004 8:46:21 AM] .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Garbage Collection Certification Objectives q State the behaviour that is guaranteed by the garbage collection system. and write code that explicitly makes objects eligible for collection.ca/scjp/gc.janeg. q Behaviour Eligibility finalize() http://www. q Write code that explicitly makes objects eligible for garbage collection. 1.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.

q Encapsulation Polymorphism Initialization Top-level Classes isA/hasA Overloading Overriding Anonymous Classes Field Variables Inner Classes Local Classes http://www. Runtime Types and Object Orientation Certification Objectives ( 1. inner classes.janeg.ca/scjp/overloading. q Write code to invoke overridden or overloaded methods and parental or overloaded constructors.lang Package The java.util Package The java. Overriding.html [15/03/2004 8:46:22 AM] . static inner classes. Write code to construct instances of any concrete class including normal top level classes. and anonymous inner classes.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.4 Objectives are identical ) q State the benefit of encapsulation in object oriented design and write code that implements tightly encapsulated classes and the relationships "is a" and "has a".awt Package The java. and describe the effect of invoking these methods.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading.

and start new threads using both java.html (1 of 2) [15/03/2004 8:46:22 AM] .4 Exam The third 1.lang Package The java. notify.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.util Package The java.Runnable. notify or notifyAll Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify(). or notifyAll q q 1. wait. Write code using synchronized.ca/scjp/threads. notify. notifyAll() http://www. notify and notifyAll to protect against concurrent access problems and to communicate between threads.lang.awt Package The java.Thread and java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads Certification Objectives q Write code to define. or notifyAll. Recognize conditions that might prevent a thread from executing.janeg. instantiate. wait.2 objective has been re-worded as: q Write code using synchronized wait.lang. q Define the interaction among threads and object locks when executing synchronized wait. Define the interaction between threads and between threads and object locks when executing synchronized. to protect against concurrent access problems and to communicate between threads.

Java Quick Reference http://www.ca/scjp/threads.janeg.html (2 of 2) [15/03/2004 8:46:22 AM] .

including making appropriate selections in the wrapper classes to suit specified behavior requirements. q 1. sqrt.janeg. floor. max. stating the result of excecuting a fragment of code that includes an instance of one of the wrapper classes.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java.Math class: abs.lang Package The java.awt Package The java.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.util Package The java. cos.lang Package Certification Objectives q Write code using the following methods of the java. etc): r doubleValue r floatValue r intValue r longValue r parseXxx r getXxx r toString r toHexString Main Classes Wrapper Classes Math Class String Immutability String Class StringBuffer Class http://www.ca/scjp/langPkg. Describe the significance of the immutability of String objects. Integer. sin.lang.4 Exam : Additional objectives q Describe the significance of wrapper classes. min. ceil.g.html [15/03/2004 8:46:22 AM] . Double. round. random. and writing code using the following methods of the wrappers classees 9e. tan.

html [15/03/2004 8:46:23 AM] . 1.lang Package The java.util Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java.awt Package The java.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.a tutorial by Joshua Bloch The Collection Framework The Java Collections Framework Collections Framework Collection Abstract Classes Iterator List http://www.util Package Certification Objectives q Make appropriate selection of collection classes/interfaces to suit specified behavior requirements.4 Exam This objective has been renamed The Collection Framework and the following has been added: q Distinguish between correct and incorrect implementations of hashcode methods.ca/scjp/utilPkg. Also see q q q Collections .janeg.

html [15/03/2004 8:46:23 AM] .event package.awt. container. extract information from the event to determine the affected component. and OverlayLayout implement the LayoutManager2 interface. they maintain their own list.rogers. GridBagLayout.html http://www. and distinguish the responsibilities of layout managers from those of containers.4 EXAM Write code using component.awt package to present a GUI with a specified appearance and resize behaviour. Pay Attention to which Layout Managers implement LayoutManager2 one thing I discovered (after I wrote the exam!) that is of prime importance in the way containers handle components when they are resized is knowing which Layout Interface the active LayoutManager implements. BoxLayout.lang Package The java.awt Package Certification Objectives q Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. Any Layout Manager that extends the LayoutManager2 Interface keeps track of their own components.awt Package The java. FlowLayout and GridLayout.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q q q q q NOT REQUIRED FOR 1. and in listener methods. LayoutManager2 type managers do not query the container for a list of components.com/jgriscti/awt. Note I haven't gotten around to re-writing my original notes. mouse position. If the container is resized they rely on their own.util Package The java. BorderLayout. State the classname for any specified event listener interface in the java. When the container is resized they will query the container for a list of the components and then layout them out according to their contract. no components will be visible. and LayoutManager classes of the java. They are located at http://members. Components added to a container before the LayoutManager was added will not be known and hence not included in the layout when the container is resized.ca/scjp/awt.janeg.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes The java. Write code to implement listener classes and methods. internal list of components. CardLayout. nature and time of the event. What this means in practice is that if the layout manager is set after components have been added to the container and the layout manager implements the LayoutManager2 interface. both implement LayoutManager.

janeg. and update files using FileInputStream.util Package The java.ca/scjp/io. FileOutputStream and RandomAccessFile objects. Write appropriate code to read. Write code that uses objects of the classes InputStreamReader and OutputStreamWriter to translate between Unicode and either platform default or ISO 8859-1 character encoding and distinguish between conditions under which platform default encoding conversion should be used and conditions under which a specific conversion should be used. q q q Tip q focus on the classes mentioned in the objectives and their constructors Also see q Introduction to Java I/O Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www. FileOutputStream.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes The java. Describe the permanent effects of the file system of constructing and using FileInputStream.io Package Certification Objectives q Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.awt Package The java. write.4 EXAM Write code that uses objects of the file class to navigate a file system. Select valid constructor arguments for FilterInputStream and FilterOutputStream subclasses from a list of classes in the java.io package.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q NOT REQUIRED FOR 1.lang Package The java. and RandomAccessFile objects.html [15/03/2004 8:46:23 AM] .

(JSK) Java 2 Platform Standard Edition v 1. Rosanna Lee. Addison Wesley. The Java Series.janeg. 1999 (GJ) Graphic Java: Mastering the AWT by David M.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.html [15/03/2004 8:46:24 AM] . The Java Series. McClellan. Volume 2 by Patrick Chan and Rosanna Lee.lang Package The java.io Package References Miscellaneous Notes Sun Sites q q q Sun Certified Programmer for the Java 2 Platform certification objectives. Addison Wesley. 2000 (JCL1) The Java Class Libraries Second Edition. 1998 (JCL2) The Java Class Libraries Second Edition. The Java Series. Volume 1: Supplemental for the Java 2 Platform. 1997 (VA) Programming with VisualAge for Java by Marc Carrel-Billiard and John Akerley. Addison Wesley. Standard Edition.ca/scjp/ref. v1. Addison Wesley. Part 2 Writing Advanced Applications for the Java Platform Hardcover q q q q Tips & Traps Mock Exams Case Studies q q SCJA Notes q SCJD Notes Projects Favourite Links About Feedback q q (JPL) The Java Programming Language Second Edition by Ken Arnold and James Gosling. New Riders. Part 1 Essentials of the Java Programming Language: A Hands on Guide. SunSoft Press.awt Package The java.util Package The java. Prentice-Hall. Geary and Alan L. The Java Series. 1999 (BB) Java Certification Exam Guide for Programmers and Developers by Barry Boone. 1998 http://www. Addison Wesley. and Douglas Kramer. The Java Series.3 (JLS) Java Language Specification Books On-line q q q q Thinking In Java by Bruce Eckel Essentials of the Java Programming Language: A Hands on Guide. McGraw Hill. 1997 (JJ) Java 2 Certification by Jamie Jaworski. 1998 (JCLS) The Java Class Libraries Second Edition. 1998 (CPJ) Concurrent Programming in Java Second Edition: Design Principles and Patterns by Doug Lea. Volume 1 by Patrick Chan and Rosanna Lee.2 by Patrick Chan.

java Compiling with JDK 1.lang Package The java.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.jar file.jar files to that ..ca/scjp/misc.3 under Win98 If you're having problems compiling check the following: 1. as instructed.jar file.jar > srcList. In the same directory. if you are using the javac switch -classpath DO NOT include an ending '\' JRE can't locate .html [15/03/2004 8:46:24 AM] . If one exists.3 does not require the DOS environment variable).jar src/java/io/Reader. View the text file to locate the path name of the class you're interested in and then type: jar xf src. The Runtime should now be able to find the .\' to ensure the current directory is always included. you are issuing the compile command from within the directory containing the .java files in the src. to the jdk1.janeg. make sure it begins with a '. 2.java file jar xf src.jar files properly. enter jar tf src.\jre\lib\ext directory and re-boot.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Extracting Source code for the Java API classes To extract source code for the Java Class files. to extract the Reader.java source file 3. you do NOT have CLASSPATH set in your AUTOEXEC.txt This will create a text file listing all the .util Package The java. copy the .BAT file (JDK 1. check your system for a Java JRE Plug-in.3\jre\lib\ext directory but you're still getting ClassDefNotFound errors when you try to run an application that references the jars.jar file pathname For example. If the variable is set because of other programs.. check your JDK directory for a src.awt Package The java. http://www.jar files and installed them.jar files under Win98 If you've downloaded some .

the variable name does not have to be args. the original String value can never be changed all the primitive type wrapper classes override the Object.java file does not contain a public class or interface it can have any name a single-type import will take precedence over an import-on-demand import-on-demand types do not increase the size of the compiled code ie only the types actually used are added to the code while import-on-demand adds no overhead to the compiled code.lang Package The java. even if they are local variables array index operator [] has highest level of precedence integer variables can be used as array dimension values postfix/prefix operators have the highest level of precedence remember that when the postfix operator is used in an expression. the current value of the variable is used a class may be assigned to an Interface type if the class implements the interface or one of it's sub-interfaces you cannot cast a primitive type to an object reference.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. not declared.ca/scjp/tips.. or static public void .janeg.html (1 of 4) [15/03/2004 8:46:24 AM] .equals() method to compare the q q q q q q q q q q q q q q SCJA Notes SCJD Notes Projects q q q Favourite Links About q q Feedback q q q q q http://www.awt Package The java. they can slow down the speed of the compile a constructor body can include a return statement providing no value is returned any method can throw a Runtime or Error exception without declaring it in the throws clause methods having the same name and parameter types do not have the same signature unless the parameter types are listed in the same order main() can be declared final main() is inherited and can be overridden if not declared as final args[0] references first command line argument after the application name ( arrays in Java are zero-based) main() can be declared public static void ..util Package The java. otherwise they return a reference to a new String Strings are immutable. can be anything as long as the type is String[] variables can have the same name as a method or a class only field variables are automatically initialized to their types default value.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies Tips q q an empty source file will compile without error if a . or vice versa you cannot cast a boolean type to another primitive type String operations whose result does not alter the original string (ie calling toUpperCase() on a String that is already in uppercase) return the original string reference... local variables must be explicitly initialized arrays are initialized to the default value of their type when they are created.

synchronized.equals() method checks if the variables reference the same object q q you do not have to have a default statement in a switch() block the default statement in a switch() blcok can appear anywhere in the construct. Boolean.Java Quick Reference value of the objects.janeg.* class attempting to extend more than one other class class declared both final and abstract an interface method declared as native or synchronized an interface method declared as static subclass with default constructor when the superclass does not have a no-args constructor or it's no-arg constructor has a throws clause constructor declared with a return type an abstract method also declared private. particularly wrapper classes Integer. does not have to be last all sections of the for() loop are optional finalize() can only be executed once on any object q q Traps q q q q code with package or import declarations given in wrong order more than one package declaration file with more than one public class or interface declaration filename. native. etc C/C++ keywords listed as possible Java keywords an empty string vs null as the default value for a String object incorrect array declaration statements.java does not match name of public class declared in the file single-type imports for two classes in different packages but with the same simple name single-type import with the same simple name as a class defined in the source file attempting to import a package vs a type ie import java. final. or strictfp an abstract method declared in a non-abstract class a native or abstract method with a method body method returning a type which is not convertible to the declared return type a void method returning a value a static method referencing this or super main() declared other than according to the standard convention local (automatic) variables declared with a modifier other than final identifiers names beginning with a number or # sign main listed as a possible keyword capitalized words listed as possible keywords. particularly: q q q q q q q q q q q q q q q q q q q q q q q http://www.util vs import java.util.ca/scjp/tips. the default Object.html (2 of 4) [15/03/2004 8:46:24 AM] .

Java Quick Reference q q q q arrayType [#] varName.html (3 of 4) [15/03/2004 8:46:24 AM] . incorrect array initialization statements. varName = { value.ca/scjp/tips. particularly: arrayType[] varName = new arrayType[2]. value. value }.janeg. negative values for array index long value for array index array declaration used as an array creation statement variables of primitive type handled as Objects using the char literals \u000A or \u000D in comments or Strings String literal "c" assigned to char type using == operator to compare values of two different string reference variables variables requiring narrowing conversion being passed to methods without using a cast assigning a typed byte or short variable to a char variable floating point operation throwing an ArithmeticException Bitwise operator precdence is: & ^ | assigning subclasses with the same parent to each other assigning a parent class to a subclass without a cast result of an integer operation on byte or short types being assigned to a byte or short without an explicit cast a non-boolean value used for operand1 in a ternary expression using == to compare the contents of two different String objects using a new value based on a short-circuit operation that was never evaluated code that results in a primitive value being changed in a method (can't happen) code that results in an unchanged object value when it was changed in a method failing to cast a value to match a method parameter type ie assuming narrowing conversion on a method call a non-boolean value used in a loop or if( ) statement using the assignment operator '=' vs '==' in an loop or if() statement using an expression vs a value promotable to int in a switch() block switch() blocks with duplicate case values switch() blocks with incorrectly 'typed' case statements switch() blocks with missing break statements (unintentionally causing code to fall through to next case) attempting to access a variable declared in the initialization outside of the for-loop for()loop with incorrect initialization expression for()loop with a non-boolean expression a question that targets a specific object for garbage collection (can't be done) a question that presumes to force the gc to run (can only suggest it run) q q q q q q q q q q q q q q q q q q q q q q q q q q q q http://www.

ca/scjp/tips.janeg.Java Quick Reference http://www.html (4 of 4) [15/03/2004 8:46:24 AM] .

as one of the more difficult mock exams.awt Package The java.lang Package The java.util Package The java. by Levteck. http://www.janeg.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Mock Exams A complete list of Mock Exams can be found on Maha Anna's JavaRanch site Another list of Mock Exams by Levteck Getting Certified in Java A Java SCJP Mock Exam by Ashok Gupta rated. The site also contains study notes.html [15/03/2004 8:46:25 AM] .Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.ca/scjp/mocks.

janeg. MailMerge An example of a classic batch processing application implemented in Java.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies Tech Articles SCJA Notes SCJD Notes Projects Favourite Links About Feedback Case Studies Learning how to put an OOP application together is not an easy task. http://www. The code must be 1. While there is lots of information available on the Java language and numerous books and articles on using various OO methods and notations there are very few resources that marry the two in a format that's helpful to beginners. Posted here are the results of my own look at code written and designed by others. The design incorporates a Command pattern. preferably on the web 2. it must utilize multiple user defined types The pages in this section will also be laid out slightly different than the rest of the site.ca/caseStudy. available. One tried and true method of learning how to program is to study the code created by other programmers. What's the basis for my choosing a case study? Right now it's pretty simple.html [15/03/2004 8:46:25 AM] . The design incorporates a Singleton pattern. JCalculator An example of a calculator component that can be used in any application.

html (1 of 7) [15/03/2004 8:46:26 AM] .ca/case/techIndex.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies Tech Articles SCJA Notes SCJD Notes Projects Favourite Links About Feedback Case Studies .janeg. Basics q q q q q q q q q q q q q q Accessing the environment from Java applications Constructor and Initialization Ordering Class and Object initialization Default Constructors Destroying Objects How arguments are passed to Java methods Interfaces and Constants Narrowing and Widening Conversions Overload Resolution Shadowing Understanding Expression Evaluation Order Using Assertions Using Import Declarations Using Variable length argument lists Class Design q q q q q q q q q q q q q q Abstract Classes Abstract Classes vs Interfaces Anonymous Classes Cloning Objects Java Design Patterns 101 (Developerworks tutorial) Joshua Bloch: A conversation about design Local Classes Making defensive copies of objects Making deep copies of objects Returning multiple values from a method Using Adapters Using Class methods and variables Use stack variables whenever possible When not to Overload Methods Collections q q Using Java Collections Collection Utilities http://www.Technical Articles Index An index to various technical articles on the web.

janeg.html (2 of 7) [15/03/2004 8:46:26 AM] . LinkedHashSet and TreeSet Using Hashtable Using List Collections efficiently Using the LinkedHashMap Class Using Sets Using Vector in the Collections Framework Using Zero-Length Arrays Exceptions q q q q q q q q q q Using Exceptions Finally clauses Guidelines and tips on when and how to use exceptions Handling InterruptedExceptions Handling Uncaught Exceptions Reusing Exceptions Stack Trace Elements Use the finally keyword to avoid resource leaks Using finally vs finalize for resource cleanup Why finalizers should (and can) be avoided Graphics q q q q Blending Images Drawing and rendering simple graphic images without suffering a serious performance hit Providing a Scalable Image Icon Using the BitSet Class I/O q q q q Capturing standard output in a log file Converting Pathnames to URLs File Channles Filter Streams http://www.ca/case/techIndex.Java Quick Reference q q q q q q q q q q q q q q q q q q q Choosing a Collections Framework Implementation Using Iterators Maintaining Insertion order in Collections Maintaining a Priority Queue Manipulating Arrays Sorting Arrays Sorting Lists Sorting with Comparators(Using Method Pointers) The Enumeration interface The RandomAccess Interface Using ArrayList and LinkedList Using Enumerations in Java Programming Using HashSet.

ca/case/techIndex.Java Quick Reference q q q q q q q q q q q q q q q q q q I/O Redirection Improving Java I/O Performance Improving I/O Performance with buffering Improving Serialization performance with Externalizable Piped Streams Programming with Buffers Programming with File Attributes Random Access for Files Reading and writing Unicode using I/O Stream Encodings Reading from Output Streams Serialization in the real world Serialization and Transient values Temporary Files Using Charsets and Encodings Using Checksums Using ReadResolve Using the PushbackReader Class Using the Serialiazable Fields API HTML q Extracting links from an HTML document Java Tools/Extras q q q q q q q q q A custom utility class for JavaHelp software Adding Help to your applications with JavaHelp software Capturing Audio with the Sound API Creating a HelpSet with JavaHelp software Fundamentals of JavaMail API Generating custom taglets (JavaDoc) Getting started with Java Management Extensions (JMX) Reading files from Java Archives (Jars) (An addendum to this article) Sending mail with the JavaMail API Math q q q q q q q q q BigDecimal Character (using the Character class) Formatting BigDecimal Numbers Format currencies Format Dates Formatting Decimal Numbers Generating integer random numbers Performing exact calculations with floating-point numbers Representing currencies http://www.html (3 of 7) [15/03/2004 8:46:26 AM] .janeg.

janeg. decimal. hex) Miscellaneous q q q q q q q q q Compiling source directly from a program Converting C programs to Java Discovering the calling methods name Goto statements and Java programming Invoking programs from Java applications Unpacking Zip files Producing MIDI Sound Using Method Pointers Using runtime.Java Quick Reference q q q Some things you should know about Floating Point Arithmetic Using Random Numbers for Testing and Simulation Working with Number Bases (binary.lang. octal.exec to invoke child processes Optimization q A Memory Testbed Application / Controlling your Memory Manager Patterns q q q Employ Factory Methods to best advantage Singleton: Limit class instances with a modified singleton Singleton: Creating thread-safe singletons Reflection q q q q Reflection Using java.ca/case/techIndex.html (4 of 7) [15/03/2004 8:46:26 AM] .Class Using Reflection to Create Class Instances Using Reflection to test methods and classes RMI q q q q Dynamic Class Loading in RMI The LifeCycle of an RMI Server Using RMI to access legacy databases A Java RMI server framework Strings q q q q q String vs StringBuffer Collators Interning Strings Optimizing String Performance String Concatenation and Performance http://www.

Part 1. Part 1 .janeg.Java Quick Reference q q q q q q q q Optimizing StringBuffer Usage StringBuffer editing String tokenization using StreamTokenizer String tokenization using StringTokenizer Using BreakIterator to parse text Using the CharSequence Interface Using the java. scrollable desktop) JSpinner(selecting from an ordered list) JTabbedPane JTable (cell rendering) JTable (displaying multi-column lists) Set your table options JTextField (validating numerical input) JTextPane JToolTips (customizing) http://www. Custom Carets (cursors) Cut. Part 2.awt. Part 2 Dragging Text and Images with Swing Effective Layout Management Fonts (working with) Handling Keyboard Focus JColorChooser JFileChooser JFileChooser(Implementing type-ahead feature) JFormattedTextField (and regular expresssions) JList (advanced programming) JList (Making sure your JList index is visible) JMenu (displaying large menus) JScrollableDesktopPane (create a virtual.ca/case/techIndex.html (5 of 7) [15/03/2004 8:46:26 AM] . Copy and Paste Displaying element level tool tips for Swing components Drag and Drop Fundamentals Drag and Drop.Robot Borders Build a better GUI Creating a File Chooser Create a Splash Screen Creating Image Thumbnails Creating Modal Internal Frames (with a JOptionPane) Creating Round buttons Creating Tree Tables.Character class Writing toString Methods Swing q q q q q q q q q q q q q q q q q q q q q q q q q q q q q q q q q q Automating GUI programs with java.lang.

janeg.ca/case/techIndex. global order Do not reassign the object reference of a locked object Ease your multithreaded application programming (Producer-Consumer) Exploiting ThreadLocal to enhance scalability Can ThreadLocal solve the double-checked locking problem? Minimizing the overhead of synchronized blocks Multi-threading in Java programs Piped Streams (to communicate between threads) Programmatically choose threads for notification http://www.Java Quick Reference q q q q q q q q q q q q q q q q q q JTree (manipulating hierarchical data) JTree (understanding TreeModel) Keymaps Loading text files in Swing efficiently Look and Feel Make a Splash Screen in Swing Performance secrets in Swing Press Esc to close Dialog windows Printing in Swing Saving and reconstituting Swing components Tracking locations in a Document Undoing Text edits Using Swing Timers Using the GraphicsEnvironment class Swing model filtering (Using filter objects to reinterpret data and state models) The Java Foundation Classes(The new standard for Java GUI development) Using Progress bars and Monitors in Java GUI Applications Using Timers in Swing Applications Text in Swing q q q q q q q q q q q q Converting Numeric Entities Displaying Multiline text Displaying text in multiple styles Text Overview Text attributes Modeling Text in Documents Pattern Matching (java.regex) The Element Interface Tabbing Sizing text with FontMetrics Customizing a Text Editor Concurrency in Swing Text Threads q q q q q q q q q Acquire multiple locks in a fixed.util.html (6 of 7) [15/03/2004 8:46:26 AM] .

Java Quick Reference q q q q q q Protecting shared resources with synchronized blocks Understand that for methods. synchronized locks objects.ca/case/techIndex.janeg. not methods or code Using synchronized or volatile when accessing shared variables Using Synchronized Statements Using Timers to run tasks on a background thread Writing efficient thread safe classes http://www.html (7 of 7) [15/03/2004 8:46:26 AM] .

ArgoUML a free CASE Tool. Extreme Programming. q SCJD Notes Projects Favourite Links About Feedback http://www.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes This spot will eventually host study notes for the Sun Certified Java Architect Certification Exam.janeg. Patterns and other design topics. Useful SCJA sites you may want to check out: q SCJA 2 Study Notes by Aaron Robinson q Martin Fowler's where you'll find a wealth of information on UML.html [15/03/2004 8:46:26 AM] .ca/scja.

q the application must be able to run in either stand-alone or network mode q the GUI interface must be flexible enough to allow the easy implementation of future enhancements http://www. Quote from Sun Basically.SCJD Study Notes Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback SCJD Study Notes Preliminary Notes q I haven't completed the assignment or passed the SCJD . The download will include a jar file containing: q an Introduction and Index document q source code that serves as a starting point q a binary database file Assignment features The assignment requires the following features: q a GUI for viewing information. you can get the assignment and determine the studying you need to do. Because it is a programming assignment. !!! ALWAYS CHECK SUN'S SITE FOR THE LATEST OBJECTIVES !!! Overview The exam consists of two parts: 1. the SCJD is testing your ability to apply the Java core API set to code the solution to a problem. these notes are being built as I go. you do not have a set time frame in which to complete the assignment. They will send you information on downloading the assignment within 2 business days. An examination to be taken at a test center. register for the exam immeadiately upon uploading your assignment. while your assignment is still fresh in your mind. The specific design requirements will be provided in the assignment instructions.Java Quick Reference .janeg. The majority consensus (from what I've seen in the forums) is that the assignment takes roughly 120 hours of work to complete. So. This exam contains multiple-choice and essay questions relating to the programming assignment. Questions and Answers about Java Platform Certification It is recommended that you track your design decisions as the exam portion will ask you to explain why you opted for one design feature over another.ca/scjd. Must demonstrate good principles of design. A programming assignment 2. Downloading the assignment Order the assignment from Sun. There is no time limit on completing the assignment.html (1 of 3) [15/03/2004 8:46:26 AM] . q database extensions to support a flexible search and record locking q network server functionality for the database systems.. Also. q communications functionality to connect the user interface with the database.. The server must be multi-threaded and thread safe.

User Guide. please let me know! http://www. Install instructions Other SCJD Resources q q The Dallas SCJD Study Group Brian Thorn received full marks for his Documentation (Note: These links have not been working lately. RMI. you need 124 points to pass Marks are based on the following criteria: q General Considerations (58) r ease of use (23) r coding standards and readability (23) r clarity and maintainablity of the design and implementation (12) q Documentation (20) r user documentation (10) r javadoc source documentation (5) r comments (5) q User Interface (24) r layout uses accepted GUI principles q Server Design (53) r locking (30) r error handling (8) r search algorithm: clarity and efficiency (15) Knowledge of the following Technologies is apt to be required q q q q q q q q Application Design: Use cases. If you come across a good resource site. TCP/IP.Java Quick Reference .SCJD Study Notes The finished assignment must include: q q q q q source and object code Javadoc documentation Database server documentation User interface (client) documentation a README file Marking The programming assignment is worth 155 points. UML. Sockets.janeg.html (2 of 3) [15/03/2004 8:46:26 AM] .) r Programming Notes example r User Documentation example There doesn't appear to be all that much out there. Patterns GUI Design using Swing components and event handling Database processing Networking: Client-Server design. Object Serialization Threads: implementing multi-threading Error and Exception handling Security profiles Documentation: JavaDoc. CRC. It's possible Mr. Thorn has removed his pages. I/O Streams.ca/scjd.

html (3 of 3) [15/03/2004 8:46:26 AM] .ca/scjd.janeg.SCJD Study Notes http://www.Java Quick Reference .

Application Design The first thing you'll probably do when you download your assignment is read the guidelines and take a look at the included code. You might want to poke around the Object Orientation Tips site to find some pointers. etc. Your first impulse may be to jump in and start coding right away! DON'T! The point of the assignment isn't just to produce working code.Application Design Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback SCJD Study Notes . OOD OOP Resources http://www. mean is not the same as knowing how to apply them in a design. polymorphism. it's to produce well designed object-oriented code! Stop and ask yourself: q What constitutes a well-designed Object-Oriented application? q What features does it have? q What separates a good design from a poor one? Do you have a clear idea of the answers? Knowing what the various OOD terms: encapsulation. That doesn't help much if you don't have alot of experience in designing OOP applications. You write your class files based on the objects you've modeled. Design is often described as "more art than science". A design is actually a model of the abstracted objects you will create to build your application. Patterns. UML Diagrams.Java Quick Reference . that help you describe an application.janeg.ca/scjd/design. etc. Where do you start? How do you begin? There are a number of modeling tools: CRC.SCJD Study Notes .html [15/03/2004 8:46:27 AM] . Modeling tools help you to identify the objects you'll need and how they will interact with each other to produce the required results. inheritance. Use Cases.

The most complete demo is SwingSet2.ca/scjd/gui.GUI Design Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback SCJD Study Notes .janeg. Check your JDK installed directory.changing the Look and Feel Resources http://www. amongst other things. q SimpleExample .Java Quick Reference . They include a JTable example. in the demo/jfc directory.html [15/03/2004 8:46:27 AM] . The following links are some notes I've made on what's available.SCJD Study Notes .GUI Design The JDK comes with a number of Swing demo applications.

SCJD Study Notes .ca/scjd/db.html [15/03/2004 8:46:27 AM] .Java Quick Reference .Database Processing Database q Use a RandomAccessFile to build a low-level database.Database Processing Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback SCJD Study Notes . Article on JavaWorld Searching q Plant your data in a ternary search tree Article on JavaWorld http://www.janeg.

Java Quick Reference .Networking Networking q q Custom Networking tutorial on Sun's site. and Michael Ernest Remote Method Invocation (RMI) q q Sun's RMI White Paper Sun's Guide to RMI Fundamentals of RMI: Short Course By jGuru on Sun's site. Tutorial may be downloaded Building a Java Chat Server tutorial by Greg Travis on the IBM Developerworks site. Chapter 17 Writing the Network Protocol from Java 2 The Complete Certification Study Guide by Simon Robers. The tutorial covers the problems inherent in building a server and techniques for over-coming them.html [15/03/2004 8:46:28 AM] .ca/scjd/network. Philip Heller.SCJD Study Notes . LifeCycle of an RMI Server (Sun Tech Tip) Dynamic Class loading in RMI (Sun Tech Tip) JavaWorld RMI Article Index An index of all the RMI articles published at JavaWorld. q q Networking Threads q Errors and Exceptions Security Documentation Projects Favourite Links About Feedback q q q RMI Tools q q q rmic . The tutorial is free and can be downloaded but you need to register first.The Java RMI Stub Compiler rmiregistry .Networking Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing SCJD Study Notes .The Java RMI Activation System Daemon Sockets q All about Sockets Sun tutorial http://www. Distributed Computation with Java Remote Method Invocation a basic RMI tutorial by Kevin Henry.janeg.The Java Remote Object Registry rmid .

(JavaWorld) q q q q q q q q Errors and Exceptions q Security q Documentation Projects Favourite Links About Feedback q q q q q q q q http://www. critical sections and read/write locks Acquire multiple locks in a fixed. not methods or code Using synchronized or volatile when accessing shared variables Using Synchronized Statements Using Timers to run tasks on a background thread Writing efficient thread safe classes Double-checked locking: Clever.janeg.Threads Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads SCJD Study Notes . synchronized locks objects.ca/scjd/threads.Threads q Learn how to implement a read/write lock Singletons. Do you know what synchronized really means? (JavaWorld) Warning! Threading in a multiprocessor world Find out why many tricks to avoid synchronization overhead just don't work.SCJD Study Notes . global order Do not reassign the object reference of a locked object Exploiting ThreadLocal to enhance scalability Ease your multithreaded application programming (Producer-Consumer) Can ThreadLocal solve the double-checked locking problem? Minimizing the overhead of synchronized blocks Multi-threading in Java programs Piped Streams (to communicate between threads) Programmatically choose threads for notification Protecting shared resources with synchronized blocks Understand that for methods.Java Quick Reference .html [15/03/2004 8:46:28 AM] . but broken.

janeg.Error and Exception Handling q Sun Tutorial on Exceptions Using Exceptions Exception Handling: The good.html [15/03/2004 8:46:28 AM] .Error and Exception Handling Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing SCJD Study Notes . the bad and the ugly (Article by Michael C.SCJD Study Notes . Daconta) The Proper Way to do Exception Handling (Article by Brian Maso) Exceptions in Java: Nothing Exceptional about them (Article by Gaurav Pal and Sonal Bansal) Using your own exception classes in Java (Article by Keld H.ca/scjd/error.Java Quick Reference . Hansen) q q q q q Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback http://www.

Security Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes SCJD Study Notes .Security q Security in Java 2 SDK 1.Example q q q Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback http://www.2 (Sun tutorial) Java's Security Architecture (Article by Bill Venners) Java security: How to install the security manager and customize your security policy (Article by Bill Venners) Java Security API .html [15/03/2004 8:46:28 AM] .ca/scjd/security.Java Quick Reference .janeg.SCJD Study Notes .

Java Quick Reference .Documentation Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback SCJD Study Notes .html [15/03/2004 8:46:29 AM] .Documentation q JavaDoc Tool Home Page How to put comments in your code with JavaDoc Java theory and practice: I have to document THAT? Integrated documentation a la Javadoc is both a benefit and a burden q q http://www.ca/scjd/doc.janeg.SCJD Study Notes .

The example uses InputVerifier's to validate user input.a simple calculator that uses method reflection to invoke commands. q PropertiesViewer .a custom 'date' input component that mimics a combo-box.html [15/03/2004 8:46:29 AM] . FieldValidation .ca/projects.display the system properties returned by System. Right now it's just small examples. q ClassBrowser . CalendarComboBox . Calculator .A simple Java class browser. displaying a perpetual calendar as it's drop-down.janeg. q q q http://www.getProperties() in a JTree.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Projects is a rather glorified name for this section.

Contains a large Certification FAQ. tutorials. Discussions. EJB.html [15/03/2004 8:46:29 AM] . SCJA and SCJD Certification.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback JavaRanch JavaRanch hosts numerous discussion groups related to all areas of Java Development: SCJP. much more including CattleDrive (Java College) where you can write practice assignments and have someone nitpick your code for free! JCHQ Java Programmer Certification Exam and Training.janeg. JavaChina A SCJP Certification site created by Roseanne Zhang. code examples and much more! Sun Sites Tutorials On-line Books Resource Sites http://www.ca/links. Popular site created by Marcus Green. XML. JSP and much. FAQ's and more.

Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Site Design The site is built and maintained by myself using HomeSite from Allaire I swiped the folder and page icons from Jeff Rouyer. http://www. author of Dynamic HTML: Web Magic.ca/about.html [15/03/2004 8:46:30 AM] .janeg.

html [15/03/2004 8:46:30 AM] . and links to other resources. how to get started learning and using Java. Forte for Java. Technical Articles. Bugs Database containing reported Bugs. Techniques and sample code. Certification Objectives and exam details. JavaBeans. Code Samples Code snippets (examplets) showing how to handle various common tasks. You need to register with the site before you can access the database.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback New 2 Java Certification SDK JLS JVM Sun site geared to Java newbies.ca/lnk_sun. Newsgroups. Graphics. Sun Sites Tutorials On-line Books Resource Sites http://www. Tech Tips Tips. View or download the Java Virtual Machine Specification. Includes links to the FAQ. etc. JDBC. Code Conventions On-line document outlining coding conventions for the Java Programming Language Technical Articles Numerous articles on various aspects of the Java platform: Collections. Documentation and Downloads. Download site for latest Java 2 Software Development Kit View or download the Java Language Specification. Forte Resources Developer resource for Sun's Java Development IDE. Applets Sample applets contributed by Java enthusiasts or created at Sun.janeg. Programming. Contains an overview of the language. Glossary Glossary of Java Technology related terms.

Java Tutorials Java 2 Certification Java Jems JSP Tutorial JDBC Tutorial A collection of introductory Java Tutorials from Free Java Help.ca/lnk_tutorials. Tutorial on Java Servlets Tutorial on Java Database Connectivity from the Web Developers Virtual Library. techniques and source code. Pure Java Education Center Collection of Java "how-to" articles. May be taken on-line or downloaded.html [15/03/2004 8:46:31 AM] .Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Sun Java Tutorial The Java Tutorial viewable on-line or may be downloaded. an student online magazine. tips.janeg. Introduction to Computer Science using Java Interactive tutorial created by Bradley Kjell of Cental Connecticut State University. Brewing Java A basic Java tutorial by Elliot Rusty Harold. Assumes no prior programming experience. Introduction to Programming Using Java Tutorial written by David Eck of Hobart and William Smith Colleges. A popular tutorial created by Marcus Green geared to the Java 2 Certification Objectives Tutorials for beginners and SCJP certification. Java Tutorials A series of Java tutorials available in the Objective Viewpoint column written by George Crawford III for ACM Crossroads. Download the html version. On-line Books Resource Sites Sun Sites Tutorials http://www. Thinking in Java Popular tutorial by Bruce Eckel.

This is a free. online textbook on introductory Java™ programming. Lots of excercises and example code.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes Data Structures and Algorithms with Object-Oriented Design Patterns in Java This book is about the fundamentals of data structures and algorithms--the basic elements from which large and complex software artifacts are built.janeg. etc.ca/lnk_books. Covers a wide variety of topics: RMI. Complete tutorial on the Java Language. A list of Java online books made available by InformIt.html [15/03/2004 8:46:31 AM] . Java Free Library Java by Example SCJD Notes Java Expert Solutions Projects Favourite Links About Feedback Focus on Java Programming Sun Sites Tutorials On-line Books Resource Sites http://www. JDBC. Applets.

ca/lnk_resources. Updated weekly. Contains articles. JavaWorld Java How-To's and Tutorials from JavaWorld magazine.Java Quick Reference Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Java FAQ JavaFile DigitalCats Java FAQ from the computer-lang/java/programmers/faq newsgroup. Sun Sites Tutorials On-line Books Resource Sites The Java Certification Web Ring [Previous] [Next] [Random] [List Sites] [Join Ring] http://www. Collection of free Java applets. Gamelan One of the oldest and most popular Java resource sites. Java resource site. Other resources A number of people have written study notes and built Java related sites.html [15/03/2004 8:46:31 AM] . links to other resources.janeg. Browse the Java Certification web-ring (see bottom of page) to find others.

janeg.html [15/03/2004 8:46:32 AM] .Java Quick Reference .java Home | Projects http://www.ca/projects/properties/properties.Project .PropertiesViewer Java Project .PropertiesViewer PropertiesViewer.

javax.tree. which automatically * sorts them. Iterator iter = keySet.util.util.util. javax.event. 300 ) ).setMinimumSize( getPreferredSize() ).StringTokenizer. Nodes are categorized * according to the first element of the property name.swing.TreeMap.java.JScrollPane.swing.swing.0 Dec-21-2001 */ public class PropertiesViewer extends JPanel{ private Properties props = System.Set.swing.ca * @version 1. For example. http://www.html (1 of 3) [15/03/2004 8:46:33 AM] . /** Creates a JPanel containing a JTree. * A StringTokenizer is used to extract the first portion of the property name * to build category nodes. import import import import import import import import import import import import import import import java. java.Dimension. java.Iterator. * all properties beginning with 'java' are categorized under * the node 'java'.event.util.JFrame.swing.PropertiesViewer. javax.JOptionPane.swing.ca/projects/properties/PropertiesViewer.awt. Set keySet = new TreeMap(props). * * @author Jane Griscti jane@janeg.TreeSelectionModel.java package ca. /** Displays system properties in a sorted.DefaultMutableTreeNode. javax. java. createSortedTree().swing.swing.swing.keySet().getProperties().janeg. private JTree tree. javax. */ private void createSortedTree(){ DefaultMutableTreeNode top = new DefaultMutableTreeNode("System Properties"). private JPanel owner. javax.properties.janeg. add( jsp ). java. * Select a property node to display its corresponding value. javax.TreeSelectionEvent. javax. */ public PropertiesViewer(){ super(). } /** Builds the JTree. import javax.setPreferredSize( new Dimension( 400. The properties are given to a TreeMap.JTree. jsp.TreeSelectionListener. owner = this.tree. categorized tree heirarchy. jsp.SwingUtilities.swing.util. The keys from the TreeMap are used to create the JTree nodes. JScrollPane jsp = new JScrollPane( tree ). java.Properties. javax.JPanel.iterator().

if( !currentCategory. tree. } /** The JTree listener.add( category ).lineStyle".INFORMATION_MESSAGE).janeg.getSelectionModel(). ".next() ).getLastSelectedPathComponent(). while( iter.getProperty( property ). if (node == null) return.java.showMessageDialog( owner.add( key ).hasNext() ){ key = new DefaultMutableTreeNode( iter.SINGLE_TREE_SELECTION).html (2 of 3) [15/03/2004 8:46:33 AM] . */ private class TreeListener implements TreeSelectionListener{ public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree. StringTokenizer stok = new StringTokenizer( (String)key.isLeaf()) { String property = (String)nodeInfo. */ http://www.setSelectionMode(TreeSelectionModel. if( value. value. "Angled" ). Object nodeInfo = node.java DefaultMutableTreeNode key = null.".getUserObject().ca/projects/properties/PropertiesViewer. if (node.nextToken(). String currentCategory = "". } tree = new JTree( top ). property.putClientProperty("JTree. JOptionPane.getUserObject(). newCategory = stok.PropertiesViewer. DefaultMutableTreeNode category = null." ). When a property node is selected a JOptionPane * is created to display the value associated with the property. } } } /** Demos the PropertiesViewer. top.equals(newCategory) ){ currentCategory = newCategory. category = new DefaultMutableTreeNode( newCategory ). tree.addTreeSelectionListener( new TreeListener() ). } category. String newCategory = "". } JOptionPane. tree. String value = props.equals("") ){ value = "No associated value.

janeg. PropertiesViewer pv = new PropertiesViewer(). frame.getContentPane(). frame. } } http://www.setVisible( true ).EXIT_ON_CLOSE ).html (3 of 3) [15/03/2004 8:46:33 AM] .add( pv ).setDefaultCloseOperation( JFrame.PropertiesViewer. frame.pack().ca/projects/properties/PropertiesViewer. frame.java.java public static void main(String[] args){ JFrame frame = new JFrame("Properties Viewer Demo").

ClassBrowser Java Project . Home | Projects http://www. The MethodGroup class diagram.Project . The ConstructorGroup class diagram. The Source Code ClassBrowser AccessSeparator CBClassGroup CBClassInfo CBDocument CBTextPane CBTreePanel ConstructorGroup FieldGroup MethodGroup NameComparator ParsedClassName Refactoring Notes Probably could be refactored to use a Group interface or abstract class as the ConstructorGroup.html (1 of 2) [15/03/2004 8:46:33 AM] . The FieldGroup class diagram. It would be nice to display the access groups using different colours: red for 'private'. FieldGroup and MethodGroup have identical functionality.ClassBrowser The GUI A screen shot of the application. The ClassBrowser class diagram. The CBClassInfo class diagram. The CBClassGroup class diagram. The CBDocument class diagram.ca/projects/cb/cb. The NameComparator class diagram. The text display could also using some cleaning up. The CBTextPane class diagram. The UML The UML diagram. The CBTreePanel class diagram.janeg. the only difference being the type of their attributes.Java Quick Reference . etc. The AccessSeparator class diagram. The ParsedClassName class diagram. 'green' for public.

Project .ca/projects/cb/cb.ClassBrowser http://www.Java Quick Reference .janeg.html (2 of 2) [15/03/2004 8:46:33 AM] .

http://www.ca/projects/cb/images/cbScreenShot.janeg.janeg.jpg [15/03/2004 8:46:34 AM] .jpg http://www.ca/projects/cb/images/cbScreenShot.

gif [15/03/2004 8:46:34 AM] .janeg.janeg.http://www.gif http://www.ca/projects/cb/images/cb_uml_1.ca/projects/cb/images/cb_uml_1.

ca/projects/cb/images/classBrowser_uml.http://www.ca/projects/cb/images/classBrowser_uml.gif http://www.gif [15/03/2004 8:46:34 AM] .janeg.janeg.

http://www.gif [15/03/2004 8:46:34 AM] .janeg.ca/projects/cb/images/cbClassGroup_uml.gif http://www.ca/projects/cb/images/cbClassGroup_uml.janeg.

ca/projects/cb/images/cbClassInfo_uml.ca/projects/cb/images/cbClassInfo_uml.gif http://www.http://www.janeg.gif [15/03/2004 8:46:35 AM] .janeg.

ca/projects/cb/images/cbDoc_uml.ca/projects/cb/images/cbDoc_uml.janeg.janeg.gif http://www.http://www.gif [15/03/2004 8:46:35 AM] .

ca/projects/cb/images/cbTreePanel_uml.gif [15/03/2004 8:46:35 AM] .ca/projects/cb/images/cbTreePanel_uml.janeg.janeg.http://www.gif http://www.

gif [15/03/2004 8:46:35 AM] .ca/projects/cb/images/cbTextPane_uml.gif http://www.http://www.ca/projects/cb/images/cbTextPane_uml.janeg.janeg.

http://www.gif http://www.janeg.gif [15/03/2004 8:46:36 AM] .ca/projects/cb/images/fldGroup_uml.janeg.ca/projects/cb/images/fldGroup_uml.

janeg.gif http://www.ca/projects/cb/images/ctorGroup_uml.gif [15/03/2004 8:46:36 AM] .janeg.ca/projects/cb/images/ctorGroup_uml.http://www.

ca/projects/cb/images/methodGroup_uml.gif [15/03/2004 8:46:36 AM] .http://www.janeg.janeg.ca/projects/cb/images/methodGroup_uml.gif http://www.

ca/projects/cb/images/parsedClassName_uml.gif http://www.janeg.http://www.gif [15/03/2004 8:46:36 AM] .ca/projects/cb/images/parsedClassName_uml.janeg.

janeg.ca/projects/cb/images/nameComparator_uml.janeg.ca/projects/cb/images/nameComparator_uml.gif http://www.http://www.gif [15/03/2004 8:46:37 AM] .

gif http://www.gif [15/03/2004 8:46:37 AM] .http://www.janeg.ca/projects/cb/images/accessSep_uml.janeg.ca/projects/cb/images/accessSep_uml.

io. treePanel = new CBTreePanel( this.event.ZipFile.Dimension.ZipException.ActionEvent.add( mainPanel ).<p> * Takes a . java.EXIT_ON_CLOSE ). javax. tsp ). private CBTextPane textPane = new CBTextPane().cb.swing. java. java. java.jar or .awt. extracts the class names and * displays them in a JTree by package or alphabetically.zip.File.swing. http://www.zip. java. * *@author Jane Griscti jane@janeg. import import import import import import import import import import import import import java.util.janeg.event.ClassBrowser. javax.awt.JMenuBar. treePanel. /** * Constructs a new ClassBrowser object * * @param cbcg a CBClassGroup object */ public ClassBrowser( final CBClassGroup cbcg ) { super( "ClassBrowser" ).ca *@created January 26. tsp.setPreferredSize( new Dimension( 500.JSplitPane.java package ca. javax.<p> * Selecting a class displays it's superclasses.IOException. private CBTreePanel treePanel. createMenuBar().awt.HORIZONTAL_SPLIT. 2002 */ public class ClassBrowser extends JFrame { private JSplitPane mainPanel.ca/projects/cb/ClassBrowser.zip archive.JMenuItem. fields. pack().io.swing. javax.getPreferredSize() ).JScrollPane.JMenu. javax.swing.swing. javax.util.janeg.setMinimumSize( tsp. mainPanel = new JSplitPane( JSplitPane.swing. java. cbcg ). JScrollPane tsp = new JScrollPane( textPane ). * constructors and methods in an adjacent JTextPane. getContentPane().ActionListener. /** * A simple Java class browser. tsp. 300 ) ).JFrame.html (1 of 3) [15/03/2004 8:46:37 AM] . setDefaultCloseOperation( JFrame.

JMenuItem exitItem = new JMenuItem( "Exit" ).ClassBrowser. menu.setMnemonic( 'p' ). menuBar.setMnemonic( 'v' ). pkgItem. menu. menu.java setVisible( true ). } /** Builds the menu bar.add( exitItem ).addActionListener ( new ActionListener() { public void actionPerformed( ActionEvent evt ) { dispose(). JMenuBar menuBar = new JMenuBar(). classItem. JMenuItem pkgItem JMenuItem classItem = new JMenuItem( "by Packages" ).html (2 of 3) [15/03/2004 8:46:37 AM] . setJMenuBar( menuBar ).janeg. pkgItem. = new JMenuItem( "by Class" ). } } ). */ private void createMenuBar() { JMenu menu = new JMenu( "View" ).addActionListener( new ActionListener() { public void actionPerformed( ActionEvent evt ) { treePanel.exit(0). System.add( pkgItem ).addActionListener( new ActionListener() { public void actionPerformed( ActionEvent evt ) { treePanel. } } ). } http://www. menuBar.add( menu ). } } ).add( classItem ).ca/projects/cb/ClassBrowser.switchToClassTree().setMnemonic( 'x' ).setMnemonic( 'c' ). exitItem.switchToPkgTree(). exitItem. classItem.

length == 0 ) { System. } private static void exit(){ System.html (3 of 3) [15/03/2004 8:46:37 AM] . exit().janeg.g." ).out.out. try { cbcg = new CBClassGroup( new ZipFile( new File( args[0] ) ) ). } ClassBrowser cb } } = new ClassBrowser( cbcg ). } catch( IOException e ) { System.println( args[0] + " is not a valid file path. } catch( ZipException e ) { System.println( " where. c:/j2sdk1.out. System. } CBClassGroup cbcg = null.zip file. http://www. exit().jar or .ClassBrowser.println( "Usage: java ClassBrowser filepath" ). System.java void displayClassInfo( final String className ) { textPane.exit(1).4.displayClassInfo( className )." ). exit(). System.out.zip" ).println( " e.out. } /** * The main program for the ClassBrowser class * *@param args The command line arguments */ public static void main( String[] args ) { if( args.out. filepath is the full path to the archive file" )." ).println( args[0] + " is not a valid .0_01/src.println( " containing the class or source files.ca/projects/cb/ClassBrowser.

2002 */ class AccessSeparator { /* * Checks the name of an object for one of the four access levels: * public. ArrayList pro = new ArrayList().html [15/03/2004 8:46:38 AM] .add( obj[i] ).ArrayList.add( obj[i] ).janeg.indexOf( "protected" ) >= 0 ) { pro. * * @author Jane Griscti jane@janeg. protected.cb. } else if( name. private or default and returns four ArrayLists * with the objects separated accordingly. } else { pkg. import java. i++ ) { name = obj[i]. */ static Object[] separate( final Object[] obj ) { ArrayList pub = new ArrayList().java package ca. for( int i = 0. /* * Takes an array of objects and uses their string names to separate * the elements by their access levels.length. pro. ArrayList pri = new ArrayList(). i < obj.AccessSeparator.indexOf( "public" ) >= 0 ) { pub.ca/projects/cb/AccessSeparator. String name = null.indexOf( "private" ) >= 0 ) { pri.add( obj[i] ).util.toString(). int index = 0. ArrayList pkg = new ArrayList(). } } http://www. pkg}. } else if( name. if( name. } } return new Object[]{pub.ca * @created January 13. pri.janeg.add( obj[i] ).

} } Collections.class" ) ) { // drop the .nextElement().java" ) || name.zip. // only want full paths.cb.util.entries(). * Extracted class names are stored for retreival by package or * alphabetically by name.Collection.zip archive file. java. private String[] sortedByPkg. CBClassGroup( final ZipFile zip ) throws IOException { groupName = zip. not partials if( name.File.html (1 of 2) [15/03/2004 8:46:38 AM] .janeg.util.getName().util. java.ArrayList.CBClassGroup.ca/projects/cb/CBClassGroup. name = zipEntry. = null. import import import import import import import import import import java. java. java.Enumeration.jar or . java.ZipFile. http://www.util.endsWith( ".StringTokenizer. * *@author Jane Griscti jane@janeg.io.ZipEntry.util.endsWith( ".Comparator.hasMoreElements() ) { zipEntry = (ZipEntry)allEntries.util.ca *@created January 5. while( allEntries.io.janeg. String token = stok.class ending StringTokenizer stok = new StringTokenizer( name. java.add( token ).java package ca.zip.java or . "." ).IOException. /** * Constructs a new CBClassGroup object by extracting * class names from a .util. private String groupName. = zip. java.getName(). entries. java.Collections. java.nextToken(). private String[] sortedByClass.sort( (ArrayList)entries ).util. 2002 */ class CBClassGroup { private ArrayList entries = new ArrayList(). Enumeration allEntries ZipEntry zipEntry String name.

getInstance() ).html (2 of 2) [15/03/2004 8:46:38 AM] . CBNameComparator. } /** * Gets the class name entries sorted by package. */ String[] getByClassName() { return sortedByClass.toArray( new String[0] ). * *@return An array of class names sorted by the class simple name.sort( (ArrayList)entries. */ String getGroupName() { return groupName. sortedByClass = (String[])entries. } } http://www.java sortedByPkg = (String[])entries. */ String[] getByPackageName() { return sortedByPkg. entries = null. * *@return An array of class names sorted by package.toArray( new String[0] ). Collections.ca/projects/cb/CBClassGroup. } /** * Gets the name of the group of entries. * *@return The fullpath name of the file containing this group of entries.CBClassGroup. } /** * Gets the class name entries sorted by class.janeg.

private private private private private private private Class thisClass.". private final String fullyQualifiedName. java. ConstructorGroup ctors.Constructor.cb.ca * @created January 8.Array. } http://www. if it is * available to the JVM via the bootstrap loader or the system classpath.java package ca. java.ArrayList.janeg.lang.lang.reflect. For example.reflect. * * @author Jane Griscti jane@janeg. MethodGroup methods. private final ParsedClassName pcn. /** * A CBClassInfo object used to load a class and store pertinent class * information: superclasses. Checks for a fully qualified class * name. however.Method. java. fields. and its information retreived. java.CBClassInfo.reflect.util.util. Class[] memberInterfaces. FieldGroup flds. methods. 2002 */ public class CBClassInfo { private final static String NAME_DELIMITER = ". java. constructor names.html (1 of 9) [15/03/2004 8:46:38 AM] .ca/projects/cb/CBClassInfo. Class[] memberClasses. java." ). this does not guarantee that the class is available to be * loaded.Field. String[] superClasses.Collections.reflect. java.lang.Object<p> * * A class may only be loaded. private boolean memberPermission /** * Constructs a new CBClassInfo object.janeg. * * @param name a fully qualified class name * @exception ClassNotFoundException if name is not a fully qualified class * name */ public CBClassInfo( final String name ) throws ClassNotFoundException { if( !isFullyQualifiedName( name ) ) { throw new ClassNotFoundException( " '" + name + "' is not a fully qualified class name.util. <p> * * A 'fully qualified name' consists of the classes package name and simple * name given in dot-notation format.Arrays. import import import import import import import java. = true.lang.lang.

} if( !mInter.add( className ).getName(). tmp = null.toArray( new Class[0] ).add( members[i] ). pcn = new ParsedClassName( name.janeg. } Collections.toArray( new String[0] ). i++ ) { if( members[i].indexOf( NAME_DELIMITER ) > 0. for( int i = 0. i < members. NAME_DELIMITER ).add( members[i] ).CBClassInfo.isInterface() ) { mInter. if( members.getSuperclass(). = subclass.length. subclass = superclass. } private boolean isFullyQualifiedName( final String name ) { return name. } private void loadSuperClasses() { Class subclass Class superclass ArrayList tmp = thisClass.getSuperclass(). ArrayList mClass = new ArrayList(). = new ArrayList(). } } if( !mClass.html (2 of 9) [15/03/2004 8:46:38 AM] .java fullyQualifiedName = name.getDeclaredClasses().isEmpty() ) { http://www. tmp.isEmpty() ) { memberClasses = (Class[])mClass. loadClassData().sort( tmp ).ca/projects/cb/CBClassInfo. while( superclass != null ) { String className = superclass. superClasses = (String[])tmp.length > 0 ) { ArrayList mInter = new ArrayList(). } else { mClass. } private void loadMemberClasses() throws SecurityException { Class[] members = thisClass. superclass = subclass.

} } /** * Returns the simpleName attribute of the CBClassInfo object * *@return The simpleName value */ public String getSimpleName() { return pcn. flds = new FieldGroup( thisClass ). } /** * Returns the package names associated with the class represented by http://www. } /** * Returns the fullyQualifiedName attribute of the CBClassInfo object * *@return The fullyQualifiedName value */ public String getFullyQualifiedName() { return fullyQualifiedName. methods = new MethodGroup( thisClass ).ca/projects/cb/CBClassInfo. } catch( SecurityException e ) { memberPermission = false. try { loadMemberClasses(). ctors = new ConstructorGroup( thisClass ).getSimpleName().toArray( new Class[0] ).html (3 of 9) [15/03/2004 8:46:38 AM] .getPackageName(). } } } private void loadClassData() throws ClassNotFoundException { thisClass = Class.forName( fullyQualifiedName ). loadSuperClasses().CBClassInfo. } /** * Returns the packageName attribute of the CBClassInfo object * *@return The packageName value */ public String getPackageName() { return pcn.java memberInterfaces = (Class[])mInter.janeg.

getPrivateFields().janeg. } /** * Returns all the fields declared in the class represented by this object.getPackages(). * *@return an object array containing Field objects */ public Field[] getPublicFields() { return flds.getAllFields().ca/projects/cb/CBClassInfo. } /** * Returns all the package fields declared in the class represented by this * object.html (4 of 9) [15/03/2004 8:46:38 AM] . * * *@return an object array containing Field objects */ public Field[] getPackageFields() { return flds. } http://www.CBClassInfo.getPublicFields(). * *@return an object array containing Field objects */ public Field[] getAllFields() { return flds. * *@return an object array containing Field objects */ public Field[] getPrivateFields() { return flds. } /** * Returns all the public fields declared in the class represented by this * object.getPackageFields().java * this object. * *@return The packages value */ public String[] getPackages() { return pcn. } /** * Returns all the private fields declared in the class represented by this * object.

java /** * Returns all the protected fields declared in the class represented by * this object.janeg. } /** * Returns all the methods declared in the class represented by this * object. * *@return an object array containing Field objects */ public Field[] getProtectedFields() { return flds.getProtectedFields(). } /** * Returns all the super classes the class represented by this object * inherits from.CBClassInfo. * *@return an object array containing Method objects */ public Method[] getPublicMethods() { return methods. } /** * Returns all the private methods declared in the class represented by * this object.html (5 of 9) [15/03/2004 8:46:38 AM] . * *@return an object array containing Class objects */ public String[] getSuperClasses() { return superClasses.getPublicMethods(). * *@return an object array containing Method objects */ public Method[] getAllMethods() { return methods. * *@return an object array containing Method objects */ public Method[] getPrivateMethods() { return methods.getAllMethods().ca/projects/cb/CBClassInfo. } /** * Returns all the public methods declared in the class represented by this * object.getPrivateMethods(). http://www.

* *@return an object array containing Constructor objects */ public Constructor[] getPublicConstructors() { return ctors.getPackageMethods().java } /** * Returns all the package methods declared in the class represented by * this object. } /** * Returns all the private constructors declared in the class represented * by this object.html (6 of 9) [15/03/2004 8:46:38 AM] .getAllConstructors().ca/projects/cb/CBClassInfo. * *@return an object array containing Constructor objects http://www. * * *@return an object array containing Method objects */ public Method[] getPackageMethods() { return methods. } /** * Returns all the constructors declared in the class represented by this * object.janeg. } /** * Returns all the protected methods declared in the class represented by * this object. * *@return an object array containing Method objects */ public Method[] getProtectedMethods() { return methods.CBClassInfo.getProtectedMethods(). * *@return an object array containing Constructor objects */ public Constructor[] getAllConstructors() { return ctors. } /** * Returns all the public constructors declared in the class represented by * this object.getPublicConstructors().

getPrivateConstructors().html (7 of 9) [15/03/2004 8:46:38 AM] . * *@return an object array containing Constructor objects */ public Constructor[] getProtectedConstructors() { return ctors. * *@return an object array of Class objects *@see isMemberAccessAllowed() */ public Class[] getMemberClasses() { return memberClasses. * * @return an object array of Class objects * @see isMemberAccessAllowed() */ public Class[] getMemberInterfaces() { return memberInterfaces.ca/projects/cb/CBClassInfo. } /** http://www.CBClassInfo. } /** * Returns all the interfaces declared as members of the class represented * by this object if the package security allows access to the information.janeg. } /** * Returns all the classes declared as members of the class represented by * this object if the package security allows access to the information.java */ public Constructor[] getPrivateConstructors() { return ctors. * * *@return an object array containing Constructor objects */ public Constructor[] getPackageConstructors() { return ctors. } /** * Returns all the package constructors declared in the class represented * by this object.getPackageConstructors().getProtectedConstructors(). } /** * Returns all the protected constructors declared in the class represented * by this object.

*/ public boolean hasSuperClasses() { return Array.html (8 of 9) [15/03/2004 8:46:38 AM] .janeg.java * Returns true if the class has declared fields.CBClassInfo. } /** * Returns true if the class has declared constructors. */ public boolean hasCtors() { return ctors. } /** * Returns a textual description of the object.getLength( superClasses ) > 0. */ public boolean hasMethods() { return methods. } /** * Gets the interface attribute of the CBClassInfo object * *@return The interface value */ public boolean isInterface() { return thisClass. */ public boolean hasFields(){ return flds. * *@return the name of the class represented by this object */ public String toString() { http://www.hasMethods ? true : false. } /** * Returns true if the class has super classes. } /** * Returns true if the class has declared methods.hasFields ? true : false.hasCtors ? true : false. } /** * Gets the memberAccessAllowed attribute of the CBClassInfo object * *@return The memberAccessAllowed value */ public boolean isMemberAccessAllowed() { return memberPermission.isInterface().ca/projects/cb/CBClassInfo.

java return "A ClassInfo object for the '" + fullyQualifiedName + "' class.janeg.html (9 of 9) [15/03/2004 8:46:38 AM] .ca/projects/cb/CBClassInfo.CBClassInfo.". } } http://www.

http://www. StyleConstants.text.cb.setFontSize( s. StyleConstants. larger font Style s = addStyle( HEADING. true ).janeg.awt. javax.CBDocument. import import import import import java.ca/projects/cb/CBDocument. StyleConstants. StyleConstants.text. StyleConstants. javax.0f ).swing. } /** Adds three styles to the document: Heading.DefaultStyledDocument.setBold( s.text. javax.swing. StyleConstants.java package ca.Style. 0 ). 2002 */ class CBDocument extends DefaultStyledDocument { private static Style basicStyle.text. = "Bold".setForeground( basicStyle. with the required font basicStyle = addStyle( BASIC. 6 ). Basic and Bold */ private void createStyles() { // Create the top-level style. 16 ).setFontSize( basicStyle.swing. /** * A customized DefaultStyledDocument used by the CBTextPane * component to display class details as formatted text. basicStyle ).swing. Color.BadLocationException. javax. 50.Color. "Courier New" ). StyleConstants. bold. final static String BASIC final static String HEADING final static String BOLD = "Basic".StyleConstants.setFontFamily( basicStyle. 14 ).black ).setFirstLineIndent( basicStyle. * *@author Jane Griscti jane@janeg.janeg.setSpaceAbove( basicStyle. // Heading: centered. null ).html (1 of 2) [15/03/2004 8:46:39 AM] . StyleConstants.setSpaceBelow( basicStyle. /** Constructs a new CBDocument object */ CBDocument() { createStyles(). = "Heading".ca *@created January 5.

StyleConstants.ca/projects/cb/CBDocument. // BoldText s = addStyle( BOLD. basicStyle ).setAlignment( s.setBold( s.setSpaceBelow( s. } } http://www. StyleConstants.html (2 of 2) [15/03/2004 8:46:39 AM] . StyleConstants.ALIGN_CENTER ).java StyleConstants.janeg.setForeground( s.CBDocument. true ). new Color( 0x006699 ) ). StyleConstants. 12 ).

janeg.lang.HEADING ). JOptionPane. javax. /n" + e. /** Construct a new CBTextPane object */ CBTextPane() { super(). 2002 */ class CBTextPane extends JTextPane { CBClassInfo currentClass. javax. * interfaces. doc. java. doc.setLogicalStyle( doc.insertString( doc. /** * A component to display formatted text detailing the superclasses. fields.text.ERROR_MESSAGE ).ca * @created January 5.reflect. if( currentClass.AttributeSet.text. javax.getFullyQualifiedName().CBTextPane.swing. javax. } catch( BadLocationException e ) { JOptionPane.java package ca. } try { AttributeSet s = doc.Constructor.showMessageDialog( this. constructor.lang. java.lang. s ).swing.Field.StringTokenizer.swing.reflect.swing.JOptionPane. "Error displaying details.getFullyQualifiedName(). } else { head = "Details for Class " + currentClass.isInterface() ) { head = "Details for Interface " + currentClass. } /** * Formats the class name and assigns it to the first line of the display * document.getLength() .1.ca/projects/cb/CBTextPane. javax.getLength().text. */ private void showHeading() { String head = null. "Display Error".reflect. java. import import import import import import import import import java. and methods of a selected class.html (1 of 5) [15/03/2004 8:46:39 AM] .getStyle( doc.cb.util.JTextPane.janeg. head + "\n".Style.swing. http://www.BadLocationException. CBDocument doc. * * @author Jane Griscti jane@janeg. (Style)s ).Method.

"Error displaying details. * *@param data An array of Interface.showMessageDialog( this. "Error displaying details.ERROR_MESSAGE ). i++ ) { try { doc. if( supers == null ) { return. } } /** * Retreives the class superclasses. (Style)s ).insertString( doc.length. return. } } } /** * Formats the class details and adds them to the display document. /n" + e. "Display Error".getSuperClasses(). formats their names and adds them to * the display document */ private void showSuperClasses() { String[] supers = currentClass.java return. doc.insertString( doc. Constructor. /n" + e. try { doc.1.CBTextPane.getLength() . JOptionPane. supers[i] + "\n".getLength(). } doc.getStyle( doc. JOptionPane.setLogicalStyle( doc.ERROR_MESSAGE ). } catch( BadLocationException e ) { JOptionPane.HEADING ). "Display Error". } AttributeSet s = doc.ca/projects/cb/CBTextPane. or Method objects *@param type Description of Parameter */ http://www. Field.showMessageDialog( this. } catch( BadLocationException e ) { JOptionPane. "SuperClasses \n".getLength().html (2 of 5) [15/03/2004 8:46:39 AM] . for( int i = 0.getStyle( doc. s ). return.BASIC ) ). i < supers.janeg.

"\n".BASIC ) ).lastIndexOf( '.substring( pos + 1 ). s ). /n" + e.getLength(). StringTokenizer stok = new StringTokenizer( line. token = token.getStyle( doc. "Error displaying details.getLength() .getStyle( doc. type + "\n". (Style)s ). return.lastIndexOf( '. try { if( token.getLength().html (3 of 5) [15/03/2004 8:46:39 AM] .hasMoreTokens() ) { token = stok.setLogicalStyle( doc. doc. "Display Error".length. doc.getStyle( doc.insertString( doc. i < data.' ).insertString( doc.indexOf( className ) == -1 ) { if( token. } } /** * Write a new line in the document * * @param line the text to be displayed */ private void displayLine( final String line ) { String className = currentClass. } try { if( type != "" ) { AttributeSet s = doc.showMessageDialog( this. final String type ) { if( data == null ) { return.endsWith( ")" ) ) { int pos = token. while( stok.ca/projects/cb/CBTextPane.ERROR_MESSAGE ). }else{ doc. } for( int i = 0. i++ ) { displayLine( data[i].1.HEADING ). true ). JOptionPane.getLength(). doc. http://www. } } catch( BadLocationException e ) { JOptionPane.BASIC ) ).' ) > 0 && !token.CBTextPane. String token = new String( "" ).java private void showData( final Object[] data. doc.toString() ).janeg.nextToken(). doc. " (".insertString( doc. "\n".getSimpleName().

if( currentClass. } doc = new CBDocument(). JOptionPane.getStyle( doc. * *@param str the name of the class for which details will be displayed */ void displayClassInfo( final String str ) { try { currentClass = new CBClassInfo( str ). token. token. setStyledDocument( doc ). doc.BOLD ) ). doc.getMemberInterfaces().ca/projects/cb/CBTextPane.showMessageDialog( this. All * content is displayed using a StyledDocument. JOptionPane. } catch( ClassNotFoundException e ) { JOptionPane.showMessageDialog( this. ctor name in bold int pos = token.janeg.html (4 of 5) [15/03/2004 8:46:39 AM] .ERROR_MESSAGE ). showHeading(). doc. "Interfaces" ). "Error displaying details. showData( inter.ERROR_MESSAGE ).' ).insertString( doc.hasSuperClasses() ) { showSuperClasses().insertString( doc.CBTextPane. return. } http://www.java } doc. "Unable to load class " + str + "\nPlease check your classpath. "Display Error". return. /n" + e.getStyle( doc.lastIndexOf( '. } else { // show field.getLength().". } } } /** * Replaces the current content with the details of the supplied class. } } catch( BadLocationException e ) { JOptionPane. "Error Loading Class".BASIC ) ). method.substring( pos + 1 ). Class[] inter = currentClass.getLength().

} if( currentClass. showData( flds.getPackageFields().getProtectedFields(). showData( flds. flds = currentClass.getPublicFields(). "" ). ctors = currentClass. showData( flds. ctors = currentClass.ca/projects/cb/CBTextPane.CBTextPane.getPublicMethods(). "" ). } } http://www.hasCtors() ) { Constructor[] ctors = currentClass. showData( ctors. showData( methods.janeg. showData( flds. showData( ctors. flds = currentClass.getPrivateConstructors(). "" ). showData( methods. "" ). showData( ctors. "" ).getPrivateMethods().getPackageConstructors().getPackageMethods().getProtectedMethods(). "" ).java Class[] members = currentClass. "Methods" ). flds = currentClass. "" ). methods = currentClass.html (5 of 5) [15/03/2004 8:46:39 AM] .getProtectedConstructors().getPrivateFields(). } if( currentClass. showData( methods.hasFields() ) { Field[] flds = currentClass. } setCaretPosition( 0 ). "Member Classes"). "" ). showData( members. "" ). methods = currentClass. showData( methods. showData( ctors.getMemberClasses(). ctors = currentClass.hasMethods() ) { Method[] methods = currentClass. if( currentClass. "Constructors" ).getPublicConstructors(). "Fields" ). methods = currentClass.

buildClassTree().util.TreePath.JTree. javax.TreeSelectionEvent.StringTokenizer.swing.ArrayList. parent = frame. java. java.janeg. CBClassGroup classGroup.Dimension. java.swing. javax. javax.TreeSelectionModel.java package ca.ca * @created January 26. DefaultMutableTreeNode pkgTree. javax.tree. javax.tree. /** * Builds and contains the JTree used to display the class heirarchy. java. javax.util.util.cb.event. final CBClassGroup cbcg ) { super(). classGroup = cbcg. javax.tree.util.swing.tree. 2002 */ class CBTreePanel extends JPanel { private private private private private private ClassBrowser parent. * * @author Jane Griscti jane@janeg.CBTreePanel.swing.util.swing. /** * Constructs a CBTreePanel object. java.awt.Collection.JScrollPane.DefaultMutableTreeNode.ListIterator. http://www. buildPkgTree().swing. javax.DefaultTreeModel.TreeSelectionListener.tree.janeg. javax.TreeNode.Collections.TreeMap. DefaultMutableTreeNode classTree.html (1 of 5) [15/03/2004 8:46:39 AM] .swing. javax. Collection sortedClasses = new ArrayList().swing. import import import import import import import import import import import import import import import import import java.JPanel.event.util.swing. * * @param frame the ClassBrowser object to contain the panel * @param cbcg the CBClassGroup to be displayed */ CBTreePanel( final ClassBrowser frame.swing. JTree tree = new JTree(). java.ca/projects/cb/CBTreePanel.

addTreeSelectionListener( new CBTreeListener() ).lineStyle".hasMoreTokens() ) { key = stok.append( key + '. keyBufStr = "".getGroupName() ). tree. keyBufStr = keyBuf. add( jsp ).toString(). DefaultMutableTreeNode prevNode.containsKey( keyBufStr ) ) { prevNode = (DefaultMutableTreeNode)map. = new TreeMap(). tokenCount++.get( keyBufStr ). */ private void buildPkgTree() { DefaultMutableTreeNode top = new DefaultMutableTreeNode( classGroup.CBTreePanel. String element.setPreferredSize( new Dimension( 300.putClientProperty( "JTree. TreeMap map prevNode = top.setSelectionMode( TreeSelectionModel. DefaultMutableTreeNode node. 500 ) ).' ).getSelectionModel().setMinimumSize( jsp. if( map. = classGroup. String key StringBuffer keyBuf String keyBufStr. i < pkgs. i++ ) { element = pkgs[i]. jsp.getPreferredSize() ). tree. tree. while( stok.html (2 of 5) [15/03/2004 8:46:39 AM] . = null. = 0.nextToken(). = new StringBuffer( "" ). jsp.java switchToPkgTree().ca/projects/cb/CBTreePanel.length() ). JScrollPane jsp = new JScrollPane( tree ). } /** Builds a tree model based on the class package names. "/" ). keyBuf = new StringBuffer( element. keyBuf.getByPackageName().length.janeg. // build tree nodes for( int i = 0. StringTokenizer stok ClassInfo data int tokenCount = new StringTokenizer( element. String[] pkgs = "". "Angled" ).SINGLE_TREE_SELECTION ). } else { http://www.

sortedClasses. while( liter.<p> * * Note: This is not built by using the CBClassGroup sorted classes.getInstance() ). } /* * Builds a tree model based on the class names. node = new DefaultMutableTreeNode( element ).add( node ). classTree = classTop.add( node ).add( data ). } prevNode = node.hasNext() ) { element = (ClassInfo)liter. } // finished with sorted classes http://www.ca/projects/cb/CBTreePanel. DefaultMutableTreeNode node.getGroupName() ). map. DefaultMutableTreeNode classTop = new DefaultMutableTreeNode( classGroup. ClassInfo element.janeg.put( keyBufStr. */ private void buildClassTree() { Collections.add( node ). It * uses the same ClassInfo objects created for the package tree. } else { prevNode.CBTreePanel. CBNameComparator.java data = new ClassInfo( keyBufStr.html (3 of 5) [15/03/2004 8:46:39 AM] .listIterator(). // check for top level package names if( tokenCount == 1 ) { top. ListIterator liter = ( (ArrayList)sortedClasses ).next(). } } } pkgTree = top.sort( (ArrayList)sortedClasses. } sortedClasses = null. classTop. key ). node = new DefaultMutableTreeNode( data ). node ).

getUserObject(). } /** * Switches the JTree model to the package name tree model. if( node == null ) { return. parent.CBTreePanel. model.ca/projects/cb/CBTreePanel.getLastSelectedPathComponent(). model. */ void switchToClassTree() { DefaultTreeModel model = (DefaultTreeModel)tree.getModel(). } if( node.ca * @created January 26.reload().setRoot( pkgTree ). model.isLeaf() ) { ClassInfo classInfo = (ClassInfo)node.reload().getModel(). http://www.html (4 of 5) [15/03/2004 8:46:39 AM] .setRoot( classTree ). * The display is automatically updated. model. 2002 */ private class CBTreeListener implements TreeSelectionListener { public void valueChanged( TreeSelectionEvent e ) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.janeg. } } } /** * Separates the class name from the package name and stores them * separately. A ClassInfo object acts as a leaf node in the JTree.qualifiedName ). * The display is automatically updated.displayClassInfo( classInfo.java /** * Switches the JTree model to the sorted class tree model. */ void switchToPkgTree() { DefaultTreeModel model = (DefaultTreeModel)tree. } /** * The listener for the JTree contained in CBTreePanel. * * @author Jane Griscti jane@janeg.

String name ) { fullpath = fullpath.ca/projects/cb/CBTreePanel. * *@return Description of the Returned Value */ public String toString() { return className. fullpath.length() . qualifiedName = fullpath. } /** * Overrides Object. that of the class it represents.substring( 0.java * * @author Jane Griscti jane@janeg. String className.ca * @created January 5. /** * Constructs a new ClassInfo object * * @param fullpath the fully qualifed class name * @param name the simple class name */ ClassInfo( String fullpath. 2002 */ class ClassInfo { String qualifiedName.toString() to provide each node with a display * name.html (5 of 5) [15/03/2004 8:46:39 AM] .1 ). } } } http://www. } public String getQualifiedName() { return qualifiedName. className = name.janeg.CBTreePanel.

Arrays.Comparator. ArrayList al = (ArrayList)obj[0].ArrayList. NameComparator.reflect.toArray( new Constructor[0] ). * *@param owner the class object the methods are derived from */ ConstructorGroup( final Class owner ) { this.Array. hasCtors = Array. /** * A constructor group object contains class constructor information separated * into groups based on their access privileges. Constructor[] publicConstructors. boolean hasCtors. protectedConstructors = (Constructor[])al. http://www.html (1 of 2) [15/03/2004 8:46:40 AM] .cb.owner = owner.lang. java. java.ConstructorGroup.java package ca. /** * Creates a ConstructorGroup object.lang.getLength( ctors ) > 0. java. al = (ArrayList)obj[1]. ctors = owner. Each grouping is sorted on the * constructors simple name.util. 2002 */ class ConstructorGroup { private private private private private private final Class owner. Constructor[] ctors.getDeclaredConstructors().toArray( new Constructor[0] ).util.janeg. } private void separateByAccess() { Object[] obj = AccessSeparator. if( hasCtors ) separateByAccess(). Constructor[] protectedConstructors. java. * *@author Jane Griscti jane@janeg.janeg.util.ca/projects/cb/ConstructorGroup. Constructor[] privateConstructors.reflect. import import import import import java.getInstance() ).separate( ctors ). Constructor[] packageConstructors.ca *@created January 13. Arrays.sort( ctors.Constructor. publicConstructors = (Constructor[])al.

janeg.toArray( new Constructor[0] ).toArray( new Constructor[0] ).html (2 of 2) [15/03/2004 8:46:40 AM] . } Constructor[] getAllConstructors() { return ctors. al = (ArrayList)obj[3]. privateConstructors = (Constructor[])al.java al = (ArrayList)obj[2].ca/projects/cb/ConstructorGroup. } } http://www. } Constructor[] getPrivateConstructors() { return privateConstructors. packageConstructors = (Constructor[])al.ConstructorGroup. } Constructor[] getPublicConstructors() { return publicConstructors. } Constructor[] getPackageConstructors() { return packageConstructors. } Constructor[] getProtectedConstructors() { return protectedConstructors.

Field[] packageFields.owner = owner. boolean hasFields. /** * Creates a new FieldGroup object. java. Field[] privateFields. import import import import import java.util.getLength( flds ) > 0.html (1 of 2) [15/03/2004 8:46:40 AM] . java.util. Each grouping is sorted on the fields * simple name.separate( flds ).janeg. /** * A field group object contains class field information separated into groups * based on their access privileges. if( hasFields ) } // separate fields based on their access level private void separateByAccess() { Object[] obj = AccessSeparator. Field[] publicFields. Field[] protectedFields.reflect. * *@author Jane Griscti jane@janeg.janeg. separateByAccess().lang.lang.getDeclaredFields(). ArrayList al = (ArrayList)obj[0]. java.cb. NameComparator.ca *@created January 13. publicFields = (Field[])al.getInstance() ).java package ca. http://www. * *@param owner the class object the fields are derived from */ FieldGroup( final Class owner ) { this.Array. hasFields = Array.sort( flds.FieldGroup.util. Field[] flds.ArrayList.Comparator.reflect. 2002 */ class FieldGroup { private private private private private private final Class owner. java. Arrays.Arrays.toArray( new Field[0] ).Field. flds = owner.ca/projects/cb/FieldGroup.

toArray( new Field[0] ). packageFields = (Field[])al.toArray( new Field[0] ). al = (ArrayList)obj[3].janeg. } Field[] getPublicFields() { return publicFields. } Field[] getPackageFields() { return packageFields.toArray( new Field[0] ). privateFields = (Field[])al. } Field[] getPrivateFields() { return privateFields. protectedFields = (Field[])al.FieldGroup. } Field[] getAllFields() { return flds.java al = (ArrayList)obj[1]. al = (ArrayList)obj[2]. } Field[] getProtectedFields() { return protectedFields. } } http://www.ca/projects/cb/FieldGroup.html (2 of 2) [15/03/2004 8:46:40 AM] .

Method[] privateMethods. } // separate methods based on their access level private void separateByAccess() { Object[] obj = AccessSeparator. java.Comparator.ca * @created January 13.util.Method.reflect.sort( methods. import import import import import import java. java. hasMethods = Array. boolean hasMethods.getLength( methods ) > 0.owner = owner.lang. java. * * @author Jane Griscti jane@janeg.Array. Method[] methods.ca/projects/cb/MethodGroup. Each grouping is sorted on the * methods simple name. methods = owner. /** * Creates a MethodGroup object. java.util.html (1 of 2) [15/03/2004 8:46:40 AM] .getDeclaredMethods().Arrays. Method[] packageMethods.StringTokenizer.util.lang. Method[] protectedMethods.util. Arrays. Method[] publicMethods. if( hasMethods ) separateByAccess(). /** * A method group object contains class method information separated into * groups based on their access privileges. http://www.java package ca.MethodGroup. NameComparator. * *@param owner the class object the methods are derived from */ MethodGroup( final Class owner ) { this. java.ArrayList.reflect.getInstance() ).janeg.janeg.separate( methods ). 2002 */ class MethodGroup { private private private private private private final Class owner.cb.

packageMethods = (Method[])al.ca/projects/cb/MethodGroup. } Method[] getProtectedMethods() { return protectedMethods. } Method[] getAllMethods() { return methods. } Method[] getPublicMethods() { return publicMethods. al = (ArrayList)obj[3]. al = (ArrayList)obj[1].toArray( new Method[0] ). } Method[] getPackageMethods() { return packageMethods.java ArrayList al = (ArrayList)obj[0].toArray( new Method[0] ). privateMethods = (Method[])al. protectedMethods = (Method[])al. } Method[] getPrivateMethods() { return privateMethods. } } http://www.toArray( new Method[0] ).toArray( new Method[0] ). publicMethods = (Method[])al. al = (ArrayList)obj[2].janeg.html (2 of 2) [15/03/2004 8:46:40 AM] .MethodGroup.

indexOf( "/" ) > 0 ) { delimiter = "/". ignores character case. /** * * * * * */ Compares fully qualified class.indexOf( ". import java. } return result. @author @created Jane Griscti jane@janeg. /* * Ensure only one NameComparator is created (Singleton) */ private NameComparator() { } private String getDelimiter( final String str ) { String delimiter = "".cb.html (1 of 2) [15/03/2004 8:46:41 AM] . // drop any parameters if it's a method or constructor name if( str.janeg.janeg.java package ca. } else if( str.ca January 13. field and method names based on their simple name. 2002 class NameComparator implements Comparator { private final static NameComparator INSTANCE = new NameComparator().substring( index + 1 ). final String delimiter ) { String result = str.util. str.Comparator." ) > 0 ) { delimiter = ". constructor. if( str. } if( delimiter != "" ) { int index = result.".ca/projects/cb/NameComparator.lastIndexOf( delimiter ). } return delimiter.indexOf( "(" ) > 0 ) { result = str.NameComparator. } private String extract( final String str.indexOf( "(" ) ).substring( 0. } http://www. result = result.

s2Delimiter ). equal to. s1 = extract( o1.ca/projects/cb/NameComparator.NameComparator.java /** * Returns a singleton instance of NameComparator * *@return a NameComparator object */ public static NameComparator getInstance() { return INSTANCE. return s1. zero.toString(). or greater than the second.toString(). s2 = extract( o2.toString(). } /** * Compares two objects * *@param o1 the first object being compared *@param o2 the second object being compared *@return a negative integer.janeg. = getDelimiter( s2 ). String s2 = o2. } } http://www. final Object o2 ) { String s1 = o1.html (2 of 2) [15/03/2004 8:46:41 AM] .compareToIgnoreCase( s2 ). String s1Delimiter String s2Delimiter = getDelimiter( s1 ).toString(). or a positive integer as the first * argument is less than. */ public int compare( final Object o1. s1Delimiter ).

java package ca.cb. delimiter ).nextToken(). } simple = stok. /** * A ParsedClassName takes a fully qualified class name and breaks into it's * component parts using the given delimiter. i++ ) { tok = stok. buf.length() ). } pkgName = buf. } String getSimpleName() { return simple. final String delimiter ) { StringTokenizer stok int tokens = new StringTokenizer( name.janeg. } String getPackageName() { http://www. } String[] getPackages() { return pkgs. if( tokens > 1 ) { StringBuffer buf = new StringBuffer( name. for( int i = 0. buf. pkgs[i] = tok. pkgs = new String[tokens .janeg.1].1. ParsedClassName( final String name. i < tokens .append( tok + '.countTokens(). 2002 */ class ParsedClassName { private String simple. String tok = "".ParsedClassName.length() .substring( 0.ca *@created January 26. = stok. * *@author Jane Grisct jane@janeg. import java.ca/projects/cb/ParsedClassName.html (1 of 2) [15/03/2004 8:46:41 AM] . private String[] pkgs.nextToken().' ).util. private String pkgName.1 ).StringTokenizer.

println().. ". i < pcn.out.out. i++ ) { System.println( pcn. i < pcn.pkgs[i] ).DateFormatZoneData_en".getSimpleName() ).java return pkgName.out." ). * *@param args The command line arguments */ public static void main( String[] args ) { // good example ParsedClassName pcn = new ParsedClassName( "java.out.pkgs. System. for( int i = 0. for( int i = 0. } // works ok with ending delimiter System.pkgs. // works ok with empty tokens pcn = new ParsedClassName( "java. } } } http://www.getPackageName() )..Frame.println().text. } /** * The main program for the ParsedClassName class. i < pcn.janeg.getPackageName() ).length.out.pkgs[i] ). used for testing. System. i++ ) { System.println( pcn. ".getSimpleName() ).println( pcn.println( pcn." ). } System.pkgs.getSimpleName() ). pcn = new ParsedClassName( "java. System. i++ ) { System.println( pcn.out.awt. System." ).out.out.Button".awt.ca/projects/cb/ParsedClassName.html (2 of 2) [15/03/2004 8:46:41 AM] . System.pkgs[i] ).getPackageName() ). ".out.length.println( pcn.println( pcn.resources.println( pcn.awt.out.println( pcn.ParsedClassName. for( int i = 0.length.out. System.".

A corresponding message is displayed in the 'status' area. The static method center() from the Utils class is used to center the window on the desktop. If the input does not fall within the verifiers parameters. Home | Projects http://www.Project .html [15/03/2004 8:46:42 AM] .java Utils.ca/projects/validate/validate.Java Quick Reference . focus is automatically returned to the field.FieldValidation Java Project .java Each field is assigned an InputVerifier which checks the contents of a field when it is exited.janeg.FieldValidation FieldValidation.

awt.Border. 49 12 ).awt. 18 import javax. 21 import javax. 32 * 33 * References: 34 * <ul> 35 * <li><a href="http://www. 12 13 import javax.SimpleDateFormat.swing.swing.com/javaworld/jw-06-2001/jw-0622-traps.html (1 of 6) [15/03/2004 8:46:42 AM] .awt.FieldValidation (Java2HTML) FieldValidation 1 package ca. 30 * 31 * The verifiers are defined as inner classes.Font.VALIDATING NUMERICAL INPUT IN A JTEXTFIELD</a></li> 39 * 40 * </ul> 41 * @author Jane Griscti.janeg.border. 26 27 /** 28 * An example of validating user input fields using 29 * <code>javax. 20 import javax.swing.swing. 5 import java.swing.janeg. 9 import java. 19 import javax.awt.ca 42 */ 43 public class FieldValidation { 44 45 private final static DateFormat dateFormat = 46 new SimpleDateFormat( "MM/dd/yyyy" ).com/developer/JDCTechTips/2001/tt1120. 17 import javax. 48 Font.JPanel. 50 http://www.awt.html"> 38 * JDC Tech Tip .text.ParseException.Utils.WindowAdapter.swing.border.html?"> 36 * JavaWorld article by Michael Daconta</a></li> 37 * <li><a href="http://developer. 23 import javax.swing.JLabel.text.Color. 2 3 import java. 22 import javax.janeg.Box. 7 import java.swing. 14 import javax.java.event. jane@janeg.swing.JTextField. 15 import javax.DateFormat.JComponent.event.ITALIC.project.BorderLayout.BOLD | Font.InputVerifier.WindowEvent.ca/projects/validate/FieldValidation. 10 import java.javaworld.Dimension.InputVerifier</code>.janeg. 47 private final Font font = new Font( null.JFrame. 6 import java.swing. 11 import java.swing.java.sun. 16 import javax.ca. 8 import java. 4 import java.TitledBorder.swing.text.BoxLayout.awt.swing. 24 25 import ca.BorderFactory.project.

setInputVerifier( new BirthdayVerifier() ).FieldValidation (Java2HTML) 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 private private private private private final final final final final JFrame frame JTextField name JTextField age JTextField birthday JTextField status = = = = = new new new new new JFrame(). } /* * Build the example GUI.setInputVerifier( new AgeVerifier() ). } }).5. http://www. Border border = BorderFactory.getContentPane(). mainPanel.5 ). } /* * Build the GUI input panel. mainPanel. mainPanel.CENTER ). // assign a verifier to each input field age.janeg.5. Utils. JTextField( JTextField( JTextField( JTextField( 25 ).getBorder() ) ).setLayout( new BoxLayout( mainPanel.createCompoundBorder( BorderFactory.setTitle( "Field Validation Example" ). public FieldValidation(){ frame.createEmptyBorder( 5.Y_AXIS ) ).janeg. frame. BorderLayout.pack(). "Input". frame. name. mainPanel. BoxLayout. 3 ).setBorder( BorderFactory.LEADING. frame.add( buildStatusPanel() ).ca.html (2 of 6) [15/03/2004 8:46:42 AM] . 30 ). 10 ).setInputVerifier( new BlankFieldVerifier() ).exit(0). buildGUI().add( buildInputPanel() ). birthday.center( frame ). TitledBorder.setResizable( false ). frame. frame.setVisible( true ).project. */ private JPanel buildInputPanel(){ JPanel panel = new JPanel().createEtchedBorder().java.add( mainPanel.ca/projects/validate/FieldValidation.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent wevt) { System. mainPanel. */ private void buildGUI(){ JPanel mainPanel = new JPanel().createTitledBorder( BorderFactory.

getPreferredSize() ). Box rightBox = new Box( BoxLayout.createEtchedBorder(). font.setBorder( BorderFactory. panel.GRAY ). panel. panel. return panel.FieldValidation (Java2HTML) 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 TitledBorder. TitledBorder. */ private JPanel buildField( JComponent comp. panel.add( buildField( age.2.add( Box. Border border = BorderFactory.add( leftBox ). */ private JPanel buildStatusPanel(){ JPanel panel = new JPanel(). font. panel. } /* * Build the GUI status panel. "Birthday:" ) ).Y_AXIS ) ). JPanel panel = new JPanel().setLayout( new BoxLayout( panel.X_AXIS ). leftBox. } /* * Build an input field to be displayed in the input panel.X_AXIS ).setBorder( border ). TitledBorder. panel. BoxLayout.setLayout( new BoxLayout( panel.2. Box leftBox = new Box( BoxLayout.TOP. panel.TOP.getPreferredSize() ).project. "Name:" ) ).add( buildField( name. 20 ) ).ca.createEmptyBorder( 2. return panel.html (3 of 6) [15/03/2004 8:46:42 AM] . rightBox.createHorizontalGlue() ).setPreferredSize( new Dimension( 60.LEADING.add( comp ). http://www. panel.janeg.add( new JLabel( label ) ).add( rightBox ).setMaximumSize( comp. String label ){ comp.X_AXIS ) ). "Status". comp. BoxLayout. panel. leftBox.ca/projects/validate/FieldValidation.java.2 ) ).janeg.setMinimumSize( comp. Color. "Age:" ) ).add( buildField( birthday. panel.createTitledBorder( BorderFactory.

* * The 'shouldYieldFocus()' method produces * a 'beep' if the validation fails. http://www.BLUE ). status. boolean isValid = true.length() == 0) { status.").FieldValidation (Java2HTML) 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 Color.getToolkit(). */ private class AgeVerifier extends BlankFieldVerifier { public boolean verify(JComponent comp) { JTextField fld = (JTextField) comp. if (content.setText("Field cannot be blank. } } /* * Checks the age field to ensure it is not * empty and that it contains an integer value.setEditable( false ).html (4 of 6) [15/03/2004 8:46:42 AM] . panel.add( status ).getText(). } return isValid. } return valid. */ private class BlankFieldVerifier extends InputVerifier { public boolean verify(JComponent comp) { JTextField fld = (JTextField) comp. } /* * Checks to ensure a field is not blank. } public boolean shouldYieldFocus(JComponent input) { boolean valid = super. return panel. if (!valid) { frame. boolean isValid = true.shouldYieldFocus(input). isValid = false. String content = fld.janeg.setText( "Ready" ). panel. status.project.GRAY ). status. String content = fld.getText().janeg.setBorder( border ).ca/projects/validate/FieldValidation.beep().setForeground( Color. It is inherited * by the other field verifiers.java.ca.

} catch (NumberFormatException nfe) { fld.setText("Age must be a number.setText("Birthday is valid.parseInt(content). isValid = false. boolean isValid = true.setText("").janeg."). } if (isValid) { status.setText("").setText("Birthday must be mm/dd/yyyy."). */ private class BirthdayVerifier extends BlankFieldVerifier { public boolean verify(JComponent comp) { JTextField fld = (JTextField) comp. } if (isValid) { status.").").parse(content).html (5 of 6) [15/03/2004 8:46:42 AM] .ca.getText(). isValid = false. */ public static void main(String[] args){ new FieldValidation().setText("Age is valid.janeg.FieldValidation (Java2HTML) 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 try { Integer. } catch (ParseException e) { fld. } } /* * Checks the birthday field to ensure it is not blank * and it contains a valid date string.project. status. try { dateFormat. There is no * range checking on the date.java.ca/projects/validate/FieldValidation. } return isValid. } return isValid. String content = fld. } } http://www. } } /** * Main entry point for the class. status.

ca.project.html (6 of 6) [15/03/2004 8:46:42 AM] .janeg.java.ca/projects/validate/FieldValidation.janeg.FieldValidation (Java2HTML) FieldValidation http://www.

getDefaultToolkit().swing.html"> * The Java Almanac</a> * @param window the component to be centered.janeg.ca.awt/screen_CenterScreen.com/egs/java.width . int x = (dim. * * Source: * <a href="http://javaalmanac. int h = window.java.awt.setLocation(x.Toolkit.Window. int y = (dim. y). // Determine the new location of the window int w = window. } } Utils http://www.Utils (Java2HTML) Utils 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 package ca.html [15/03/2004 8:46:43 AM] .awt. * * * @author Jane Griscti.getSize().height . import java.getSize().w) / 2.awt. */ public static void center( Window window ) { // Get the size of the screen Dimension dim = Toolkit. import java.ca/projects/validate/Utils.janeg.ca */ public class Utils { /** * Center a component on the screen.height.Dimension.getScreenSize().h) / 2. import java.janeg. // Move the window window.swing. /** * Utility methods for Swing components. jane@janeg.width.

it was not shown until a number between 1 and 9 was selected.K.C. All in all the whole thing came out fairly clean<g>. the button action listener could invoke engine. exponential numbers were being returned. each JButton's action command is set to the value of the button label.html (1 of 2) [15/03/2004 8:46:45 AM] . To accomplish this I created an inner class CalcButton which implements ActionListener and then created a number of subclasses to handle the different colour settings for each function.##0. This got me thinking about how nice it would be if. Haven't figured out how to get http://www. The reflection mechanism in Java allows for just such a scenario.0.0#". I also wanted the buttons appearance to vary according to their functions: digit. binary. There is one small flaw that I'm aware of. the display shows nothing when really it should show a '0'. In the end I gave up and decided to modify CalculatorEngine. control. q Calculator The key to the GUI is displaying the various buttons in a pleasing manner and finding an easy way to invoke their actions. By default. unary.###.Calculator Java Project .#" and invoked setDecimalSeperatorAlwaysShown( false ) but then the decimal did not show up until the user selected another digit key and if that happened to be a zero.Project . I only wanted to show decimal digits if the user had selected the decimal key. This also presented difficulties. if the result of a unary operation such as mod is zero. Kiong which implemented the four binary operations: + . a NumberFormatter and modifying the code to keep the value and display attributes in sync. I then tried using a JFormattedTextField in the GUI with a DecimalFormat.ca/projects/calc/calc.java CalculatorEngine. This worked fine from the command line but gave me problems when I was designing the GUI.cos(). I added the unary functions and built a Swing GUI. The default pattern for DecimalFormat is "#. Design Decisions q CalculatorEngine The original code returned Double. I changed the pattern to #. The display always showed 0.toString( value )./ * and = in the class CalculatorEngine.janeg. adding the display field.Java Quick Reference .java This is a simple implementation of a Calculator. I started with some code I found in Object-Oriented Programming and Java by Danny C. Poo and Derek B. in any decimal position. when a user selected the cos button.Calculator Calculator.

Project .html (2 of 2) [15/03/2004 8:46:45 AM] . If you have a solution.Java Quick Reference . please let me know <g> Home | Projects http://www.janeg.ca/projects/calc/calc.Calculator around this yet.

calc.awt.ActionEvent. 1998. java.awt.Container.javaalmanac.Insets.event.InvocationTargetException.com/egs/javax.awt.ca.Calculator (Java2HTML) Calculator /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *************************************************************************** File: Package: Contains: Calculator. layouts and action listener changed CalcButton to use a white foreground as the default button color and removed redundant calls from the subclasses re-arranged the code in the class body to place inner classes after all methods except main() *************************************************************************** */ Author ------------Jane Griscti Jane Griscti Jane Griscti References: package ca.awt.awt.Toolkit.html Date -----------Oct 17.awt.awt.swing/LookFeelNative.java ca.Dimension.event.lang.com (Layout) The Java Programming Language: 2nd Edition by Ken Arnold and James Gosling Addison-Wesley. 2002 Changes ---------------------------------------------Created Cleaned up comments. import import import import import import import import import import import import import java.GridLayout.ca/projects/calc/Calculator.awt. Article at http://archive. java.calc.awt.janeg.Method.awt/screen_CenterScreen. java.reflect. http://www. 7th Printing 2000 (p311) The Java Developers Almanac 1. 2002 Oct 23.Color. java. java.html (1 of 7) [15/03/2004 8:46:45 AM] .lang.janeg. java.janeg. java.janeg. java.reflect.calc Inner classes CalcButton DigitButton FunctionButton UnaryButton ControlButton Visual Components: Sum It Up with JCalculator by Claude Duguay. java.ActionListener.Component. java.java.devx.html http://www.Font.4 (online) http://javaalmanac.awt.awt.com/egs/java. java. java.Window. 2002 Oct 22.

calc.0 Oct 17. 2002 */ public class Calculator extends JFrame { private final Class ENGINE.setEditable( false ).swing. javax.ca.UnsupportedLookAndFeelException.Y_AXIS ) ). // set up a Class object used in actionPerformed() // to invoke methods on the CalculatorEngine ENGINE = engine. setVisible( true ).swing.setBackground( Color. } private JPanel buildControlPanel(){ JPanel panel = new JPanel().DISPOSE_ON_CLOSE ).add( buildControlPanel() ).html (2 of 7) [15/03/2004 8:46:45 AM] .WHITE ). */ public Calculator(){ setDefaultCloseOperation( JFrame. javax. javax. http://www.swing.ca * @version 1.swing.janeg.java. /** * A GUI interface for <code>CalculatorEngine</code>.swing. display. setLAF(). /** * Create a new calculator instance.Box.swing.JButton. * * @author Jane Griscti jane@janeg.UIManager. setTitle( "Calculator" ). buildGUI(). cp.JTextField.Calculator (Java2HTML) import import import import import import import import javax. BoxLayout. private final JTextField display = new JTextField().add( buildButtonPanels() ).swing. private final CalculatorEngine engine = new CalculatorEngine(). cp.swing. cp. center( this ).ca/projects/calc/Calculator. cp. javax. javax. javax.BoxLayout.setLayout( new BoxLayout( cp.JPanel.janeg. setResizable( false ).JFrame. } private void buildGUI(){ Container cp = getContentPane(). display.add( display ). javax.getClass(). pack().

setLayout( new GridLayout( 4.add( new ControlButton( "C".java.ca. "sign" ) ). panel. panel. 2 ) ). panel. panel.add( new DigitButton( "2" ) ).janeg. 2.add( new DigitButton( "0" ) ). panel. return panel.add( new DigitButton( "6" ) ).add( Box.add( new DigitButton( "9" ) ).calc.setLayout(new BoxLayout(buttons.add( new DigitButton( "3" ) ). http://www.add( new DigitButton( "4" ) ).Calculator (Java2HTML) panel. return panel. panel.add( new DigitButton( "1" ) ). JPanel panel2 = new JPanel( new GridLayout( 1. 0 ) ) ). 2 ) ). 1.add( new ControlButton( "Backspace". panel. buttons.setFont(new Font("Courier".X_AXIS)). 2 ) ). buttons.createRigidArea( new Dimension( 2.add( new UnaryButton( " +/.add( panel2 ).BOLD)). panel.". 2.createHorizontalGlue() ). panel.add( new DigitButton( "5" ) ). 3.add( buildFunctionPanel() ). panel.ca/projects/calc/Calculator.setLayout(new BoxLayout(panel.add( new DigitButton( ".add( buildDigitPanel() ). // not a digit but added here to balance out the panel panel. "clear" ) ). panel. 10. panel.html (3 of 7) [15/03/2004 8:46:45 AM] .add( new ControlButton( "CE". 3. BoxLayout. "backspace" ) ). panel.add( new DigitButton( "8" ) ). panel2. BoxLayout. } private JPanel buildFunctionPanel(){ JPanel buttons = new JPanel( new GridLayout( 4. buttons. Font. panel2. panel." ) ).add( Box. buttons. return buttons. } private JPanel buildDigitPanel(){ JPanel panel = new JPanel().X_AXIS)). 2. panel. "clearEntry" ) ). } private JPanel buildButtonPanels() { JPanel buttons = new JPanel().add( new DigitButton( "7" ) ).add( buildUnaryPanel() ).janeg. buttons. panel.

buttons.add( buttons. 3. "cos" ) ). buttons.ca/projects/calc/Calculator. 2. buttons.add( new FunctionButton( "-". "tan" ) ). buttons.getScreenSize(). "subtract" ) ). "equals" ) ). 2 ) ). "atan" ) ). "xor" ) ). "divide" ) ). "log" ) ).add( new FunctionButton( ">>".add( new FunctionButton( "<<". } /* * Center a component on the screen.add( new new new new new new new new UnaryButton( UnaryButton( UnaryButton( UnaryButton( UnaryButton( UnaryButton( UnaryButton( UnaryButton( "sin" ) ). buttons. "percent" ) ).add( buttons. buttons. "rightShift" ) ). "leftShift" ) ).ca. } private JPanel buildUnaryPanel(){ JPanel buttons = new JPanel( new GridLayout( 4.html (4 of 7) [15/03/2004 8:46:45 AM] .add( new UnaryButton( "rad".add( new FunctionButton( "/".add( new FunctionButton( "|".add( new UnaryButton( "%". "multiply" ) ).add( new FunctionButton( "mod" ) ). buttons. return buttons.add( new FunctionButton( "=".add( buttons. // Determine the new location of the window int w = window.janeg.add( buttons.add( new FunctionButton( "+". "add" ) ).janeg.add( new FunctionButton( "pow" ) ).getDefaultToolkit(). * * @param window the component to be centered.add( new FunctionButton( "&".width. buttons.calc. buttons. buttons. "acos" ) ). */ private void center( Window window ) { // Get the size of the screen Dimension dim = Toolkit.getSize().add( new UnaryButton( "1/x". "radians" ) ).add( buttons.add( new FunctionButton( "*". "reciprocal" ) ). buttons. "degrees" ) ).add( new UnaryButton( "sqrt" ) ). "and" ) ). "deg". buttons.add( buttons. buttons.add( new FunctionButton( "^" . http://www. "asin" ) ).add( buttons. buttons.java. return buttons.Calculator (Java2HTML) buttons. "divide" ) ). buttons. buttons.

html (5 of 7) [15/03/2004 8:46:45 AM] .w) / 2. * Each button acts as its own listener. // Move the window window. have to use new Integer( '.width . */ private class CalcButton extends JButton implements ActionListener{ CalcButton( String s.setLocation(x. } catch (IllegalAccessException e) { System. setMargin( new Insets( 2. } catch (ClassNotFoundException e) { System.' ) which converts the ASCII http://www.println( e. int y = (dim. // Install the look and feel try { UIManager.getSize(). } /* * Set the Look and Feel to the system look and feel.janeg. } /* * * * * * * * * * * Captures the button events and then uses 'reflection' to invoke the right method in the calculator engine Digit buttons are handled slightly different as they all use the digit( int ) method and their values must be passed as arguments.getSystemLookAndFeelClassName()." ) throws a NumberFormatException. The digit button for the decimal has special handling.java. String action ){ super( s ).println( e.out. 2. 2 ) ).getMessage() ). */ private void setLAF() { // Get the native look and feel class name String nativeLF = UIManager.getMessage() ).out.getMessage() ).h) / 2.setLookAndFeel(nativeLF). } catch (UnsupportedLookAndFeelException e) { System. setActionCommand( action ).Calculator (Java2HTML) int h = window.println( e.println( e.janeg. addActionListener( this ).getMessage() ).calc.ca/projects/calc/Calculator. } catch (InstantiationException e) { System. } } /* * Helper class to handle button formatting.out.out.WHITE ).ca. setForeground( Color. new Integer( ". int x = (dim. 2.height. y).height .

} } private class DigitButton extends CalcButton { DigitButton( String s ){ super( s.equals(". } catch (IllegalAccessException ea) { System.println("No such method: " + methodName). if (methodName.getActionCommand(). } display.calc.invoke(engine.janeg.out.getMethod(methodName. action ).invoke(engine.setText(engine.display()). Method method = null. } else { method. null).janeg. new Object[] { new Integer( '.GRAY ). } catch (InvocationTargetException et) { System.out.invoke(engine.ca/projects/calc/Calculator. method. try { if ( e.getSource() instanceof DigitButton ) { method = ENGINE.Calculator (Java2HTML) * value of '. new Class[] { int.' to an integer.class }). } FunctionButton( String s.html (6 of 7) [15/03/2004 8:46:45 AM] . setBackground( Color.println("Target exception: " + methodName). setForeground( Color. } } else { method = ENGINE. new Object[] { new Integer( methodName )}). String action ){ super( s. } } catch (NoSuchMethodException ex) { System.ca.")) { method.out.java.println("Illegal access" + methodName). } } private class FunctionButton extends CalcButton { FunctionButton( String s ){ this( s. } } http://www.' )}). null).BLUE ). s ). * */ public void actionPerformed(ActionEvent e) { String methodName = e.getMethod("digit". s ).

BLUE ).html (7 of 7) [15/03/2004 8:46:45 AM] . } ControlButton( String s.java. action ).calc. } } private class UnaryButton extends CalcButton { UnaryButton( String s ){ this( s. s ). } UnaryButton( String s. String action ){ super( s.janeg. s ). setBackground( Color.ca. String action ){ super( s. } } Calculator http://www. setBackground( Color.RED ).Calculator (Java2HTML) private class ControlButton extends CalcButton{ ControlButton( String s ){ this( s. } } /** * Main entry point for the program */ public static void main(String[] args) { new Calculator(). action ).janeg.ca/projects/calc/Calculator.

import java.getInstance().java ca. false.digit( 2 ).digit( 3 ).digit( 1 ). Kiong.ca.println( c. 2002 Oct 18.janeg. etc Added var display. false. * </pre> * * Accuracy is limited to fifteen decimal places. or. sqrt. * * <pre> * CalculatorEngine c = new CalculatorEngine().janeg. http://www. Poo and Derek B. * c.janeg. * System. 1999 (p48-49) Date -----------Oct 17. Springer.digit( 1 ). number formatter and related methods Added integer binary operations: xor.calc.text. 2002 Jane Griscti Added trig and log unary functions *************************************************************************** */ Author ------------Jane Griscti Jane Griscti Jane Griscti package ca. by Danny C.CalculatorEngine (Java2HTML) CalculatorEngine /* * * * * * * * * * * * * * * * * * * * *************************************************************************** File: Package: References: CalculatorEngine. and leftShift. 2002 Jane Griscti Cleaned up comments Oct 22.NumberFormat. * c. /** * A class to perform standard calculator operations. * c. * For example. * c.out. 2002 Changes ---------------------------------------------Created Added unary functions %. reciprocal.ca/projects/calc/CalculatorEngine.equals().html (1 of 8) [15/03/2004 8:46:47 AM] .text. 2002 */ public class CalculatorEngine { private private private private StringBuffer display DecimalFormat df boolean newOp boolean inDecimals = = = = new StringBuffer( 64 ).C.2 Oct 20. (DecimalFormat)NumberFormat. * c.calc. import java.DecimalFormat.janeg. * c.ca * @version 1.calc Object Oriented Programming and Java. 2002 Oct 20.K.display() ).java.add(). * * @author Jane Griscti jane@janeg. rightShift Oct 21.

' ). toDo.' ){ display. */ public CalculatorEngine(){ super(). }else if( !inDecimals ){ display. newOp = false.length() ).parseDouble( display.java. inDecimals = true. } /* -. */ if( newOp ){ display. } char c = (char)n.janeg. */ public void digit(final int n ){ /* * Strategy: * 1. setting the decimal flag if it's * a decimal point or increasing the decimal count if we're * already into decimals.*/ /** * Accept a digit or decimal as input. }else{ if( decimalCount < 16 ){ display.append( n ).janeg. Append the input character.delete( 0. keep. http://www.ca/projects/calc/CalculatorEngine. } } try{ value = Double.ca.html (2 of 8) [15/03/2004 8:46:47 AM] . df. Start a new value if at the beginning of a new operation. * * 2. decimalCount++.append( '. if( c == '. * * 3.toString() ).setMaximumFractionDigits( 15 ). // // // // // current digits previous value or operation result binary operation waiting for 2nd value number of decimal positions in current value /** * Creates a new <code>CalculatorEngine</code> object.append( n ).Digits and the decimal point handler -.0 value. Convert the revised input string to a double for use in * calculations. decimalCount. forcing input errors to return a 0.CalculatorEngine (Java2HTML) private private private private double double int int value.calc. display.

} /** * Bitwise Or ( | ) */ public void or(){ binaryOperation( "|" ). } /** * Multiply the next input value by the previous value */ public void multiply(){ binaryOperation( "*" ).CalculatorEngine (Java2HTML) }catch( NumberFormatException e ){ value = Double.ca/projects/calc/CalculatorEngine. } /** * Subtract the next input value from the previous value */ public void subtract(){ binaryOperation( "-" ).0" ).html (3 of 8) [15/03/2004 8:46:47 AM] . store the current value * 2. set the 'toDo' flag with the requested operation * 3. } /** * Bitwise And ( & ) */ public void and(){ binaryOperation( "&" ).calc. accept input for a second value * 4. } } /* -. perform the 'toDo' op when '=' or another binary operation * is requested */ /** * Add the next input value to the previous value */ public void add(){ binaryOperation( "+" ). http://www.janeg.janeg. } /** * Divide the previous value by the next input value */ public void divide(){ binaryOperation( "/" ).Binary operations -* * A binary operation signals the engine to: * 1.ca.parseDouble( "0.java.

} /** * Bitwise left shift ( < ) */ public void leftShift(){ binaryOperation( "<" ). } /** * Perform any waiting binary operation and clear previous value */ public void equals(){ compute().CalculatorEngine (Java2HTML) } /** * Bitwise ( ^ ) */ public void xor(){ binaryOperation( "^" ).janeg.ca. } /** * Modulous ( % ) */ public void mod(){ binaryOperation( "m" ).html (4 of 8) [15/03/2004 8:46:47 AM] . newOp = true.janeg.ca/projects/calc/CalculatorEngine. } /** * Raise the previous value to the 'power.calc.java. } /** * Bitwise right shift ( > ) */ public void rightShift(){ binaryOperation( ">" ). http://www. } /* * Setup registers for next input value */ private void binaryOperation( final String op ){ if( toDo == 0 ){ keep = value. toDo = 0. of the next input value */ public void pow(){ binaryOperation( "p" ). }else{ compute().

janeg. break.value. break. unaryOperation(). case '/': if( value != 0 ){ // ignore divide by zero value = keep / value. case '>': value = (int)keep >> (int)value.html (5 of 8) [15/03/2004 8:46:47 AM] .janeg. break. case '^': value = (int)keep ^ (int)value. break.*/ /** * Compute the square of the current value */ public void sqrt(){ value = Math. break.pow( keep.java.CalculatorEngine (Java2HTML) } value = 0. } case '&': value = (int)keep & (int)value. case 'p': value = Math. } /** * Convert the current value to a percent */ http://www. value ). break. } keep = value.ca. break. break. case 'm': value = keep % value.Unary Operations -. } /* * Perform a binary operation */ private void compute(){ switch( toDo ){ case '+': value = keep + value. break. break.calc. unaryOperation(). setDisplay(). case '*': value = keep * value. toDo = op. resetDecimals(). } /* -. } /** * Reverse the sign on the current value */ public void sign(){ value = value * -1. setDisplay().hashCode(). case '|': value = (int)keep | (int)value. case '<': value = (int)keep << (int)value.ca/projects/calc/CalculatorEngine. case '-': value = keep .sqrt( value ).

http://www.ca. } /** * Compute the asine of the current value */ public void asin(){ value = Math. unaryOperation(). } /** * Compute the tan of the current value */ public void tan(){ value = Math.tan( value ). } /** * Compute the acosine of the current value */ public void acos(){ value = Math. } /** * Compute the sine of the current value. unaryOperation(). */ public void sin(){ value = Math. unaryOperation().sin( value ).calc. }else{ value = 0.asin( value ).java. } /** * Convert the current value to it's reciprocal value */ public void reciprocal(){ if( value > 0 ){ value = 1 / value.CalculatorEngine (Java2HTML) public void percent(){ value = value / 100. unaryOperation().acos( value ).ca/projects/calc/CalculatorEngine.cos( value ). unaryOperation(). } unaryOperation().html (6 of 8) [15/03/2004 8:46:47 AM] . unaryOperation(). } /** * Compute the cosine of the current value */ public void cos(){ value = Math.janeg.janeg.

deleteCharAt( display.atan( value ).ca/projects/calc/CalculatorEngine. } http://www. } /* -. unaryOperation(). } /* * Setup flag to signal start of a new operation and * set the display to match the value generated by a * unary operation */ private void unaryOperation(){ newOp = true. unaryOperation().toString() ). } /** * Convert the current value to degrees */ public void degrees(){ value = Math.Control operations -.janeg. } /** * Convert the current value to radians */ public void radians(){ value = Math.janeg.toDegrees( value ). unaryOperation().log( value ). value = Double.java.html (7 of 8) [15/03/2004 8:46:47 AM] .1 ).parseDouble( display. unaryOperation().ca.toRadians( value ).*/ /** * Delete the last entered digit */ public void backspace(){ display.calc.length() . setDisplay(). setDisplay(). } /** * Compute the log of the current value */ public void log(){ value = Math.CalculatorEngine (Java2HTML) } /** * Compute the atan of the current value */ public void atan(){ value = Math.

display. value = 0. display.delete( 0. resetDecimals(). decimalCount = 0. display. resetDecimals(). df.length() ).calc. value = 0.length() ). }else{ display.ca.delete( 0.janeg.format( value ) ).length() ). } /* * Reset the decimal flag and counter */ private void resetDecimals(){ inDecimals = false.toString(). } /** * Clear the current value */ public void clearEntry(){ display.ca/projects/calc/CalculatorEngine.delete( 0. } } /** * Returns the current value as a decimal formatted string */ public String display(){ return display.CalculatorEngine (Java2HTML) /** * Clear all values */ public void clear(){ display.length(). } } CalculatorEngine http://www. } /** * Convert the current value to a formatted string for * display */ private void setDisplay(){ if( value == 0 ){ display. display.replace( 0. keep = 0.janeg.html (8 of 8) [15/03/2004 8:46:47 AM] . toDo = 0.java.

I thought it would be nice to have one for my Java projects.NORTH and the table in BorderLayout. a gettor method. It turned out to be less difficult to create than I'd originally imagined. Design Decisions q Class fields The values represented by these fields are common to the system the class is running on. and Popup. q http://www. And last. This is good coding practice.Java Quick Reference . Below are my reasons for designing the class as I did. not during the active life of a running application.CalendarComboBox Java Project . it was very distracting. The data is based on the system Locale which is not likely to change.ca/projects/calendar/cal. I also needed to figure out how to build an array to hold the days in a month and leverage the various date related classes: Calendar. The private keyword helps to enforce encapsulation and forces you to think about your classes public interface.Project .CalendarComboBox CalendarComboBox.java As a Notes developer. Field access modifiers All fields (except popup ) are declared private and final. Once I changed the label to a JTextField and the calendar panel layout to BorderLayout.CENTER the display started to behave itself. DateFormat. they are hightlighted in the code comments. were the layout experiments. JTable. Finally realized that part of the problem was the JLabel component I was using to display the month and year name and the fact that I was using a BoxLayout. I was able to create the CalendarComboBox by simply arranging a number of existing components: JFormattedTextField. It took some poking around in the API and Java source code related to JComboBox before I tracked them down. I got stuck for a few hours on the calendar display. the buttons in the navigation panel kept changing size. Of course. current needed to be publicly exposed.html (1 of 2) [15/03/2004 8:46:47 AM] . I ran across a few other snags. code always looks simple once it's finished. Dunn's book. but not least. BasicArrowButton. public Calendar getDate() was provided to return current as it's reasonable to assume an external class would need access to the currently selected date. and DateFormatSymbols. I've gotten used to having a date input box with a perpetual calendar. The one truly nice thing about Java is the richness of it's API. Mr. Java Rules was particularly useful in helping me understand how these classes worked.janeg. with the navigation portion placed in BorderLayout. at least. GregorianCalendar. Originally I didn't know the BasicArrowButton and Popup classes even existed. In this case. only one field.

Java Quick Reference . Add to that the difficulty of maintaining code that is peppered with anonymous classes and the choice of using inner classes became even more attractive. this is simply a personal preference. here's the proof that it just ain't so! They can be alot easier to create than you realize. not one. q q Summary If you've avoided creating custom components.CalendarComboBox q The keyword final emphasizes that the fields are required and that references cannot be accidently modifed during the life of an object. Having a separate method to handle them just makes life easier for me. if you fail to initialize a final variable during object creation the compiler complains. ButtonListener. So again. It also notifies the compiler that the code relating to these values can be safely optimized.janeg. as inner classes or as anonymous classes. As the programmer's at Sun have been kind enough to supply me with a class that can manage popup's it seemed sensible to use it rather than create a final popup reference and attempt to manage it myself. When I started writing the class I had no idea how long a particular listeners code would be and I did know that one listener. thinking they're to much trouble or that you need to be an expert programmer to create them. managing their reuse and disposal. Listeners as inner classes There are three basic ways to implement listeners: as external classes. Another advantage is that it helps ensure that everything the object requires to work correctly will be available once it is created.ca/projects/calendar/cal.Project . The registerListeners() method For the most part. The only reason to implement one as an external class is if it could possibly be used by another class. there was little to be gained by implementing the listeners as anonymous classes. Why popup isn't final The API recommends using PopupFactory to create Popup objects. PopupFactory caches popup objects. would be required by three elements. I find it easier to keep track of listeners when they are all located in one spot. yet listeners are generally very specific in nature and certainly are specific in this case so there was nothing to be gained by implementing them as external classes.html (2 of 2) [15/03/2004 8:46:47 AM] . If you end up using the class in one of your applications please let me know how it fares<g> Home | Projects http://www. Anonymous listener classes are generally used if they are required by only one element in the class and if they can be written in nine or ten lines of code.

awt.awt.text.Toolkit.html (1 of 9) [15/03/2004 8:46:49 AM] .janeg.event.awt. David S.awt. 2002 jg Cleaned up InputListener code to only accept * valid dates * Nov 2.ca.KeyAdapter. java.Calendar.awt. 2002 jg modified getPopup() to handle display when * component is positioned at the bottom of the screen * Nov 3.util.ParseException.swing.janeg.JFormattedTextField.DateFormatSymbols.CalendarComboBox (Java2HTML) CalendarComboBox /* *************************************************************************** * * File: CalendarWidget.event. java.awt. java. java.java.ca/projects/calendar/CalendarComboBox.awt.janeg.Color. Krutsch.calendar.util.GregorianCalendar. java.---------------------------------------------------------* Oct 24.swing.BorderLayout. import import import import import import import import import import import import import import import import java.event.util. java.BoxLayout.awt.event.calendar.swing. java. Cargo.DateFormat.java * Package: ca. 2001 (Chapter 1-3) * * Date Author Changes * -----------. java. 2002 Jane Griscti Created * Oct 27. java. java.Point. http://www.calendar * * Contains: ButtonActionListener * CalendarModel * CalendarSelectionListener * InputListener * * References: 'Java Rules' by Douglas Dunn * Addison-Wesley. 2002 (Chapter 5. 2002 jg changed some instance variables to class variables * Mar 29.Font.19) * * 'Professional Java Custom UI Components' * by Kenneth F. 2003 jg added setDate() contributed by James Waldrop * *************************************************************************** */ package ca.ActionListener.KeyEvent. 2002 jg added ctor CalendarComboBox( Calendar ) * Oct 31. import javax. section 13 .janeg. java.Date. java. java. java.awt.awt. import javax. Virginia Howlett * WROX Press. 2002 jg Cleaned up calendar display * Oct 30.text.Box.text.ActionEvent. java. import javax.Dimension. 2002 jg Added listeners and Popup * Nov 1.

instance fields used with 'combo-box' panel private final JPanel inputPanel = new JPanel().swing.BasicArrowButton. javax.swing.SwingConstants.swing. private static final Dimension private static final PopupFactory dfs months dayNames toolkit = new DateFormatSymbols().plaf.janeg. javax.JTableHeader.swing.EAST ). private final JFormattedTextField input = new JFormattedTextField( new Date() ). = dfs. javax. /** * A custom component that mimics a combo box.swing.TableColumn.ca * @version 1.janeg. 6 ).swing. JTable( display ).getDefaultToolkit(). javax. private final BasicArrowButton comboBtn = new BasicArrowButton( SwingConstants. javax.table.CalendarComboBox (Java2HTML) import import import import import import import import import import import import import import javax. javax.ca/projects/calendar/CalendarComboBox.PopupFactory.swing. private final BasicArrowButton closeCalendarBtn = new BasicArrowButton( SwingConstants. // -.SOUTH ).swing.ca.swing. // -.html (2 of 9) [15/03/2004 8:46:49 AM] .instance fields used with calendar panel private final JPanel calPanel private final JTextField calLabel private final Calendar current private final CalendarModel display private final JTable table = = = = = new new new new new JPanel().border.swing.getSharedInstance(). javax.0 Oct 24.ListSelectionEvent. javax.JPanel. javax.swing.calendar. javax. = new String[ 7 ]. CalendarModel( 6.DefaultTableModel.Popup.ListSelectionListener. GregorianCalendar().LineBorder. = screenSize = toolkit. 2002 */ public class CalendarComboBox extends JPanel { // -.ListSelectionModel.basic.event. JTextField( 11 ).getMonths(). factory = PopupFactory.swing. * * @author Jane Griscti jane@janeg.NORTH ). http://www.getScreenSize(). javax. private final BasicArrowButton prevBtn = new BasicArrowButton( SwingConstants.swing.table.java.table. javax.JTextField.class fields private static final DateFormatSymbols private static final String[] private static final String[] private static final Toolkit Toolkit.event. javax.WEST ).swing. private final BasicArrowButton nextBtn = new BasicArrowButton( SwingConstants. displaying * a perpetual calendar rather than a 'list'.JTable.

add( input ). BoxLayout. // create the GUI elements and assign listeners buildInputPanel().janeg. table. // set the calendar and input box date Date date = cal.util. */ private void buildInputPanel(){ inputPanel. } /** * Create a new calendar combo-box object set with the given date. inputPanel. buildCalendarDisplay().setValue( date ). */ public CalendarComboBox(){ this( new GregorianCalendar() ). registerListeners().setSelectionMode(ListSelectionModel. input.setLayout( new BoxLayout( inputPanel.setActionCommand( "combo" ).setTime( date ). table.add( comboBtn ). comboBtn.setColumns( 12 ).CalendarComboBox (Java2HTML) private Popup popup.setCellSelectionEnabled(true).ca. // intially.GregorianCalendar */ public CalendarComboBox( final Calendar cal ){ super(). * * @param cal a calendar object * @see java. } /* * Creates a field and 'combo box' button above the calendar * to allow user input.java. inputPanel. input. http://www.SINGLE_SELECTION).getTime(). /** * Create a new calendar combo-box object set with today's date.X_AXIS ) ). } /* * Builds the calendar panel to be displayed in the popup */ private void buildCalendarDisplay(){ // Allow for individual cell selection and turn off // grid lines.html (3 of 9) [15/03/2004 8:46:49 AM] .janeg.calendar.ca/projects/calendar/CalendarComboBox. only display the input panel add( inputPanel ). current.

// // Need to re-map the retreived names. BoxLayout. */ private JPanel buildCalendarNavigationPanel(){ JPanel panel = new JPanel(). table. calPanel.add( buildCalendarNavigationPanel(). i ++ ){ TableColumn col = table. int count = table.ca.getColumnCount().janeg.setFont( header. 'nextBtn' month selection buttons * and a 'closeCalendarBtn'.getColumnModel(). } // Column headers are only displayed automatically // if the table is put in a JScrollPane. } /* * Creates a small panel above the month table to display the month and * year along with the 'prevBtn'. // Set the column widths. for( int i = 0.setLayout( new BoxLayout( panel. calPanel. calPanel.setPreferredWidth( 20 ). // Calendar (table) column headers // Set column headers to weekday names as given by // the default Locale. header.getTableHeader().BLACK ) ). i<names.getColumn( i ). JTableHeader header = table.janeg.Y_AXIS ) ). for( int i=1. table. panel.BOLD ) ).length. so need to add the headers // manually.calendar. // the table model ends up with an extra empty column as // the returned names begin at index 1. BorderLayout.NORTH ).ca/projects/calendar/CalendarComboBox. i < count.add( table ).setColumnIdentifiers( dayNames ). } display.setLayout( new BoxLayout( panel. panel. BoxLayout. http://www. i++ ){ dayNames[ i . JPanel panel = new JPanel(). panel.charAt( 0 ).deriveFont( Font.AUTO_RESIZE_OFF). not zero.getFont().add( panel ).add( header ).1 ] = "" + names[ i ].getShortWeekdays().html (4 of 9) [15/03/2004 8:46:49 AM] . Need to turn // auto resizing off to make this work.java. calPanel. col. String[] names = dfs. If used as is. Don't want // to use one here.setBorder( new LineBorder( Color.setModel( display ).X_AXIS ) ).setShowGrid( false ).setLayout( new BorderLayout() ).setAutoResizeMode(JTable.CalendarComboBox (Java2HTML) table. panel.

java.addActionListener( btnListener ).2 ) ).calendar. int fontSize = calLabel. closeCalendarBtn. panel. otherwise. Rows in the table correspond to 'weeks'.CalendarComboBox (Java2HTML) // Add a text display of the selected month and year.getSize(). calLabel. // Calendar navigation listeners prevBtn. JLabel // expands and contracts with the text size calLabel.add( calLabel ).deriveFont( Font. return panel. // Calendar (table) selection listener // Must be added to both the table selection model // and the column selection model.setActionCommand( "nextBtn" ).addListSelectionListener( listener ). // 'Combo-box' listeners input.ca. fontSize . } /* * Register all required listeners with appropriate * components */ private void registerListeners(){ ButtonActionListener btnListener = new ButtonActionListener().addActionListener( btnListener ).setActionCommand( "prevBtn" ).addActionListener( btnListener ). panel.html (5 of 9) [15/03/2004 8:46:49 AM] .setFont( calLabel.addActionListener( btnListener ).getSelectionModel().getFont().setActionCommand( "close" ). } /* * * * * Fill the table model with the days in the selected month.PLAIN. Strategy: http://www. // A JTextField is used for the label instead of a JLabel // as it is easier to ensure a consistent size. columns to 'days'.getColumnModel().add( prevBtn ).add( closeCalendarBtn ). table. closeCalendarBtn. // set button commands and add to panel prevBtn.getSelectionModel() . nextBtn.setEditable( false ).getFont(). comboBtn.addKeyListener( new InputListener() ).addListSelectionListener( listener ). table.janeg.janeg.ca/projects/calendar/CalendarComboBox. new // column selections on the same row are not recognized CalendarSelectionListener listener = new CalendarSelectionListener(). panel.add( nextBtn ). panel. nextBtn.

fill the calendar with the day values. col ). " + cal.calendar.DAY_OF_WEEK ) . row++ ){ for( int col = 0. // compute the number of days in the month and // the start column for the first day in the first week int actualDays = cal.get( Calendar. find the actual number of days in the month 4. row < 6 . col++ ){ if( ( col < startIndex && row == 0 ) || day > actualDays ){ // overwrite any left over values from old month display. } } } // set the month. cal.setText( months[ cal.1.YEAR ) ). 1 ).changeSelection( cal. // set the calendar selection table.MONTH ).DAY_OF_WEEK ) . find it's position in the first week of the month to determine the starting column for the day numbers 3.setValueAt( "".1.CalendarComboBox (Java2HTML) * * * * * * */ private 1. // fill the calendar for the new month int day = 1. row. */ private Popup getPopup(){ Point p = input.height) { // will fit below input panel popup = factory.get( Calendar. false ). calPanel. for( int row = 0.y + calendarSize. false. int startIndex = dayOne.java.get( Calendar.getPopup( input.MONTH ) ] + ". col ). if( ( p.getPreferredSize(). } /* * Gets a Popup to hold the calendar display and determines * it's position on the screen. http://www.1.get( Calendar.setValueAt( new Integer( day ).getLocationOnScreen().height ) < screenSize. Dimension inputSize = input. Dimension calendarSize = calPanel.getActualMaximum( Calendar.get( Calendar.ca.janeg. day++. col < 7. get the first calendar day in the new month 2.getPreferredSize().get( Calendar. cal.ca/projects/calendar/CalendarComboBox.YEAR ).html (6 of 9) [15/03/2004 8:46:49 AM] . row.get( Calendar. }else{ display.WEEK_OF_MONTH ) . year label calLabel.DATE ).janeg. erasing any days left over from the old month void updateTable( Calendar cal ){ Calendar dayOne = new GregorianCalendar( cal.

* * @return Calendar the currently selected calendar date */ public Calendar getDate(){ return current. * @param newDate the new date as a <code>Date</code> object.janeg.setTime(newDate). } /** * Overrides the method to return an Integer class * type for all columns.height ). int col ){ super( row.calendar.janeg. p.CalendarComboBox (Java2HTML) p. int col ){ return false. col ). The numbers are automatically * right-aligned by a default renderer that's supplied * as part of JTable. */ public boolean isCellEditable( int row. p.y + (int)inputSize.setValue(current.x. } else { // need to fit it above input panel popup = factory.ca/projects/calendar/CalendarComboBox. } return popup. } /** * Overrides the method to disable cell editing.(int)calendarSize.html (7 of 9) [15/03/2004 8:46:49 AM] .y . } /* * Creates a custom model to back the table.x.class.ca. input. * The default is editable. * @see Date * @author James Waldrop */ public void setDate(Date newDate) { current. p. } http://www. } /** * Sets the current date and updates the UI to reflect the new date. calPanel. } /* * Returns the currently selected date as a <code>Calendar</code> object.java. */ private class CalendarModel extends DefaultTableModel { public CalendarModel( int row.getTime()).getPopup( input.height ). */ public Class getColumnClass( int column ){ return Integer.

try{ value = display. input.getValueIsAdjusting() ) { int row = table.equals( "nextBtn" ) ){ current.MONTH. if( cmd. col). popup.ca/projects/calendar/CalendarComboBox. * * The combo button is disabled when the popup is shown * and enabled when the popup is hidden.java. 'comboBtn' and * 'closeCalendarBtn' actions.add( Calendar.show().equals( "prevBtn" ) ){ current. int col = table.janeg. 'nextBtn'.getTime() ).setValue( current. }else{ comboBtn.add( Calendar.hide(). }catch( ArrayIndexOutOfBoundsException ex ){ // ignore.MONTH. * */ private class CalendarSelectionListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent e){ if ( !e.getActionCommand().equals( "close" ) ){ popup.setEnabled( true ). }else if( cmd.getValueAt(row. } } /* * Captures a user selection in the calendar display and * changes the value in the 'combo box' to match the selected date. comboBtn. */ private class ButtonActionListener implements ActionListener { public void actionPerformed( ActionEvent e ){ String cmd = e.calendar. 1 ). input.setValue( current.setEnabled( false ).ca. happens when the calendar is // displayed for the first time } http://www.CalendarComboBox (Java2HTML) } /* * Captures the 'prevBtn'. -1 ).getTime() ).getSelectedRow(). } updateTable( current ).html (8 of 9) [15/03/2004 8:46:49 AM] . popup = getPopup().getSelectedColumn(). Object value = null. }else if( cmd. Failure to do * so results in the popup screen area not being cleared * correctly if the user clicks the button while the popup * is being displayed.janeg.

janeg.VK_TAB ) ) { current.getText() ).html (9 of 9) [15/03/2004 8:46:49 AM] .calendar.CalendarComboBox (Java2HTML) if( value instanceof Integer ){ int day = ( (Integer)value ).DATE.setTime( date ).getKeyChar(). try{ date = df. } } } } CalendarComboBox http://www.janeg.VK_ENTER || c == KeyEvent.setValue( current.intValue(). day ).parse( input.ca/projects/calendar/CalendarComboBox.getTime() ). Date date = null. current.set( Calendar. }catch( ParseException ex ){ // ignore invalid dates } // change the calendar selection if the date is valid // and the user hit ENTER or TAB char c = e.getDateInstance(). } } } } /* * Captures user input in the 'combo box' * If the input is a valid date and the user pressed * ENTER or TAB. input. updateTable( current ). the calendar selection is updated */ private class InputListener extends KeyAdapter { public void keyTyped(KeyEvent e) { DateFormat df = DateFormat. if( date != null && ( c == KeyEvent.java.ca.

html (1 of 2) [15/03/2004 8:46:50 AM] . ToolTip The demo doesn't include tool tips (the text you see when the mouse is over the component) but assigning one is easy. Setting the mnemonic for a button is relatively simple.Java Quick Reference .setMnemonic('h'). That's it.GUI Design Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes SCJD Study Notes .janeg.GUI Design SimpleExample Demonstrates q q q q changing the Look and Feel JRadioButtons. just call the the setMnemonic(char c) method. Button b = new Button("Hello"). any assigned mnemonic is appended to the tip as 'ALT+x' where 'x' = whatever characters been assigned. ButtonGroup. http://www. if you're in Metal Look and Feel and you a tool tip.SCJD Study Notes . no other coding required. just invoke the setToolTextTip(String) method. implementing WindowClosing UML Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback Mnemonics A mnemonic allows the user to activate a button by holding ALT + the assigned mnemonic character. and mnemonics setting up an ActionListener as an inner class creating an anonymous WindowAdapter. b.ca/scjd/gui/simple. One thing that's nice.

html (2 of 2) [15/03/2004 8:46:50 AM] .ca/scjd/gui/simple.Java Quick Reference .setToolTextTip("The Hello button"). Resources http://www.janeg.SCJD Study Notes .GUI Design b. This will work for every component as the method is defined in JComponent (the superclass of all Swing components).

Write high-performance RMI servers and Swing clients by Andy Krumel Rendering cells in Swing's JTable component by Brett Spell Add an undo/redo function to your Java apps with Swing by Tomer Meshorer Using the Swing Action Architecture by Mark Davidson (Sun article) Using Timers in Swing Applications by Hans Muller and Kathy Walrath (Sun article) Threads and Swing by Hans Muller and Kathy Walrath (Sun article) Using Dynamic Proxies to Generate Event Listeners Dynamically by Mark Davidson (Sun article) Card Panel . Book which can be viewed on-line or downloaded as a Word'97 document.html [15/03/2004 8:46:51 AM] . University of Canberra q Favourite Links About Feedback q q q Swing Resources and Articles at Sun q q q Creating a GUI with JFC/Swing tutorial Index of Swing Articles Java TM Look and Feel Graphics Repository. Newmarch.SCJD Study Notes .GUI Design Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects SCJD Study Notes . The Three Models Used in Designing for Ease of Use IBM Design site.an Alternative to Card Layout by Hans Muller (Sun article) Testing Java Swing-Based Applications by J. Building user interfaces for object-oriented systems.janeg. D.Java Quick Reference .GUI Design Design Theory q q q q Principles of good GUI Design by James Hobart The Design of Graphic User Interfaces on-line course. Part 1 thru 6 JavaWorld articles by Allen Holub Java Look and Feel Design Guidelines from Sun q Swing q q q q q q Swing by Matthew Robinson and Pavel Vorobiev.ca/scjd/gui/resource. a collection of Toolbar Icons from Sun Resource http://www.

exactly what the object you're building should do (requirements).Application Design . Think what would happen if every time you upgraded your PC you had to learn a new keyboard layout! Sales would plummet and programmers would become extinct.janeg. http://www. you need to act like an investigative reporter and discover the: q WHO q WHERE. The analog display blah. and q WHAT of an object's existance. A public interface describes the objects contract with users. Try to think in terms of the object vs the class when you start a design. This is not about setting every field to private and writing public gettors and settors. not how it does it. Object-Oriented programming design is based on the interface.OOD Java Quick Reference Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback SCJD Study Notes . The design process involves building a model of an object using abstraction.Java Quick Reference . "Always start by designing a minimal public interface. describe. When you begin to design an object. Encapsulation hides the non-essentials ie it hides the implementation details.ca/scjd/design/ood.Application Design ." State and Behaviour State An objects attributes define its state (condition). An instance is one object created from a class." not "This object uses the Java Date class and JPanel to display the date and time. initially.html (1 of 2) [15/03/2004 8:46:51 AM] . it is service oriented.. with what an object can do. Instance fields. The instance attributes are unique to each object. This paragraph is informal and written from a user's perspective ie "I want an object that can display the current date and the time in an analog or digital format. in a single paragraph. You need to make sure your public interface does not rely on how the objects behaviour is implemented..OOD Note q These notes are derived from the book Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty A class is a programming construct. it is task oriented." The implementation is how the object goes about providing the services In Procedural programming design is based on the implementation. The attributes can be defined as: 1.SCJD Study Notes . a Name class might have two attributes: firstName and lastName. Every object created from the Name class would have a different value for each attribute. For example. An interface describes the services the client wants accomplished ie the object's capabilities or functionality. blah .. q Who is going to use the object? What clients(actors) are going to use the object you're designing q Where is your object going to exist? What hardware and software is involved? Will it exist in a framework ie inside other objects? What operating system will it run on? q What functions should it have from the user's point of view? What services can it be reasonably expected to provide? As a first step. You need to be concerned. a template used to create objects. blah.

3. For example. The value in the id field would be common to all Employee objects. a class that defines buffer objects may have a MAX_BUFFER value.Java Quick Reference .janeg. Behaviour Design Traps It might be easier to describe well-designed code in terms of what it is not vs what it is. OOD OOP Resources http://www.ca/scjd/design/ood. Every data element and every method should contribute to that object. Objects with no data are ghosts.html (2 of 2) [15/03/2004 8:46:51 AM] . Multiple Personality Trap An object should model only one object. A state that holds true for every object in the class. Spectral Object Trap An object is not a collection of methods you pass data to. Class fields.SCJD Study Notes .Application Design . For example. not pass it to other parts of the program which then manipulate it. Class constants.OOD 2. Pre-defined conditions that can be applied to all objects in the class. an Employee class may include an id attribute that holds the last id number and is incremented every time a new Employee is created. The following is a summary of such information gleaned from various sources: Source: Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty Data Warehouse Trap An object is not a repository for data that the rest of your program will use! An object should manipulate it's own data.

Java Quick Reference - SCJD Study Notes - Application Design - OOP

Java Quick Reference

Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects Favourite Links About Feedback

SCJD Study Notes - Application Design - OOP
Must Read
q

If you read only one book before you start your SCJD assignment make it Effective Java by Joshua Bloch. This is an excellent book that will give you new insights into how the Java language is best utilized. It contains 57 items grouped into categories: Creating and Destroying Objects, Classes and Interfaces, General Programming, Threads, etc. that describe the programming idioms that work best along with the how and why of implementing them.

Other sources worth investigating: q JavaIdioms
q q q

The Essence of Object-Oriented Programming with Java and UML The Pragmatic Programmer Design Techniques Articles about Java program design by Bill Venners

OOD

OOP

Resources

http://www.janeg.ca/scjd/design/oop.html [15/03/2004 8:46:51 AM]

Java Quick Reference - SCJD Study Notes - Application Design

Java Quick Reference

Home SCJP2 Study Notes Case Studies SCJA Notes SCJD Notes Application Design GUI Design Database Processing Networking Threads Errors and Exceptions Security Documentation Projects

SCJD Study Notes - Application Design
Modeling Tools Use Case A semi-formal description of what a user wants from a system and how they expect to interact with the system to bring about a specific result. Generally people; however, a user can also be another system or another piece of the same system. Sometimes referred to as scenarios. q Structuring Use Cases with Goals by Alistair Cockburn
q q q q

Use and Abuse Cases(PDF) by Martin Fowler Modeling Essential Use Cases by Scott W. Ambler Roles before Objects by Doug Lea Dealing with Roles(PDF) by Martin Fowler

CRC

Class-Responsibility-Collaboration cards. Martin Fowler calls it "One of the most valuable techniques for learning OO" (UML Distilled p9) q A Laboratory For Teaching Object-Oriented Thinking by Ward Cunningham and Kent Beck, the developers of CRC. Two flavours: sequence and collaboration. Useful when trying to capture the behaviour of several objects within a single use case. Martin Fowler recommends using State diagrams to model the behaviour of one object across multiple use cases. (UML Distilled p78) q Introduction to UML sequence diagrams by Scott W. Ambler Classes describe objects in the domain and the static relationships that exist between them. Detail the class data (attributes) and operations (behaviour). q A general discussion of Class Diagrams by Martin Fowler. Includes tips on when and how they are best utilized. q UML Tutorial - Class Diagrams(PDF) by Robert C. Martin
q

Interaction Diagrams

Class Diagrams Favourite Links About Feedback

Class Diagrams in Analysis an exercise in developing Class Diagrams from a Use Case accompanied by lecture notes (PDF) which explain the analysis process.

Design Patterns

Patterns are example models of processes that crop up repeatedly in software development. For example, developers are often faced with problems that require moving through a list or collection. The Iterator pattern describes a standard technique for handling iterations. q The Design Patterns Java Companion by James Cooper
q q

Implementing Basic Design Patterns in Java by Doug Lea Speaking on the Observer pattern How can you use the Observer pattern in your Java design? (JavaWorld)

On-line Analysis and Design Tutorials/Lectures
q

Interactive Web Tutorial for OOP by Deniz Zubair choudhury

http://www.janeg.ca/scjd/design/resource.html (1 of 2) [15/03/2004 8:46:52 AM]

Java Quick Reference - SCJD Study Notes - Application Design
q

q q

The Essence of Object-Oriented Programming with Java and UML by Bruce E. Wampler (draft of book) Techniques for Object Oriented Analysis and Design by Martin Fowler Systems Analysis and Design A series of lectures and practical exercises based on the book Object-Oriented Systems Analysis and Design using UML by Simon Bennet, Steve McRobb, Ray Farmer Object-Oriented Analysis and Design lecture series by J.W. Schmidt, Claudia Niederée, and Michael Skusa A Commercially Robust Process for the Development of OO Software Systems(PDF)

q

q

Free Modeling Software
q q

DOME free modeling software from Honeywell. mUml from MountField Computers free for non-commercial use. Written entirely in Java using Swing GUI. Capabilities allow you to draw all 9 UML diagrams in colour. Diagrams can be saved as JPEGs or saved as HTML pages. If you have Visio v4, v5 or Visio 2000 you can download a free Visio Stencil and Template for UML courtesy of Navision and Paul Hruby. ArgoUML free case tool; part of the Tigris.org open-source platform. If you're using Linux or Sun Solaris, you can download a free copy of JVision for non-commercial use. (Sorry, if you're using Windows it will cost you.)

q

q q

Miscellaneous
q q

UML Reference Card Allen Holub has put together a great page with annotated UML diagrams. UML Dictionary put together by Kendall Scott, author of The Unified Modeling Language User Guide and four UML/OOP related books. OOP Resources

OOD

http://www.janeg.ca/scjd/design/resource.html (2 of 2) [15/03/2004 8:46:52 AM]

Java Quick Reference - Case Study - Mail Merge

Java Case Study - Mail Merge
q q q q q q q q

Overview User Defined Types Quasi Pseudo Code Notes on Design Using an Abstract class Extending a RuntimeException The GUI implementation Solves a problem or problem domain?

Source
The code for this study is from Developing Java Software, 2nd Edition by Russel Winder and Graham Roberts and may be downloaded from the authors support site. Home | Case Studies

http://www.janeg.ca/case/mail/mail_1.html [15/03/2004 8:46:52 AM]

Java Quick Reference - Mail Merge - Overview

Java Case Study - Mail Merge - Overview
Problem Statement
Implement an application, in Java, that will merge an address file with a letter file. The letter file is a LaTex document. The Java application will invoke LaTex via the operating system. The Latex application will process and print each newly created document.

Address File Structure
The address file will contain element groups tagged as follows: <NAME> <TELEPHONE> <FAX> <EMAIL> <ADDRESS> The address element must be the last in the group. Street, city and country information must be separated by commas. If the same element appears more than once within a group, the value of the last element is used.

Sample LaTex File
\documentclass{rlw_letter} \begin{document} \begin{letter}{<NAME>\\ <ADDRESS>} \opening{Dear <NAME>,} This is just some text to show where the text of the letter would be. \closing{Yours sincerely,} \end{letter} \end{document} Home | Case Studies | TOC | Next

http://www.janeg.ca/case/mail/mail_2.html [15/03/2004 8:46:53 AM]

LaTex

LaTex
LaTex is a typesetting system used in the production of technical and scientific documentation. For more information see The LaTex Home Page

http://www.janeg.ca/case/mail/latex.html [15/03/2004 8:46:53 AM]

Java Quick Reference - Case Study - Mail Merge - User Defined Types

Java Case Study - Mail Merge - User Defined Types
User Defined Types
Full UML Class Diagram The application is implemented with the following user defined types: q MailMerge
q

CommandServer
r r

UNIXCommandServer MSWindowsCommandServer

q q q

FailedCommandException MessageBox FilesSelector
r

FilesSelector$BrowseButtonActionListener

q q q

Report ExitActionListener ExitWindowAdapter Home | Case Studies | Previous | TOC | Next

http://www.janeg.ca/case/mail/mail_3.html [15/03/2004 8:46:53 AM]

http://www.janeg.ca/case/mail/uml.jpg

http://www.janeg.ca/case/mail/uml.jpg [15/03/2004 8:46:54 AM]

http://www.ca/case/mail/MailMerge.janeg.janeg.jpg http://www.ca/case/mail/MailMerge.jpg [15/03/2004 8:46:54 AM] .

ca/case/mail/CommandServer.janeg.janeg.jpg [15/03/2004 8:46:55 AM] .http://www.ca/case/mail/CommandServer.jpg http://www.

http://www.ca/case/mail/UNIXCommandServer.janeg.jpg http://www.janeg.jpg [15/03/2004 8:46:55 AM] .ca/case/mail/UNIXCommandServer.

janeg.janeg.ca/case/mail/MSWindowsCommandServer.http://www.jpg [15/03/2004 8:46:56 AM] .jpg http://www.ca/case/mail/MSWindowsCommandServer.

janeg.ca/case/mail/FailedCommandException.ca/case/mail/FailedCommandException.jpg http://www.http://www.janeg.jpg [15/03/2004 8:46:56 AM] .

janeg.jpg http://www.ca/case/mail/MessageBox.janeg.ca/case/mail/MessageBox.http://www.jpg [15/03/2004 8:46:57 AM] .

jpg http://www.janeg.http://www.janeg.ca/case/mail/FileSelector.ca/case/mail/FileSelector.jpg [15/03/2004 8:46:57 AM] .

jpg [15/03/2004 8:46:58 AM] .janeg.jpg http://www.ca/case/mail/BrowseButton.ca/case/mail/BrowseButton.http://www.janeg.

ca/case/mail/Report.janeg.jpg [15/03/2004 8:46:58 AM] .ca/case/mail/Report.http://www.jpg http://www.janeg.

http://www.jpg [15/03/2004 8:46:58 AM] .janeg.ca/case/mail/ExitActionListener.janeg.ca/case/mail/ExitActionListener.jpg http://www.

jpg http://www.ca/case/mail/ExitWindowAdapter.http://www.janeg.ca/case/mail/ExitWindowAdapter.jpg [15/03/2004 8:46:59 AM] .janeg.

Java Quick Reference .Mail Merge .Quasi Pseudo-Code When MailMerge is started it .ca/case/mail/mail_4.Mail Merge . addressFileName..Case Study . passing it the new MailMerge instance the FileSelector captures user input: letterFileName.Quasi Pseudo Code Java Case Study .. gets an instance of CommandServer based on the operating system if( args == 0 ) { creates another instance of MailMerge creates a FileSelector. printerName and updates the fields in the MailMerge instance destroys itself when the user dismisses it creates a Report to display values input by user destroys itself when the user dismisses it } else { retrieves the file and printer names from the command line arguments } opens the files reads the letter file into memory for( each record in the address file ) { reads a record displays the values creates a temporary file merges the record with the letterfile writes the merged result to the temporary file sends commands to the operating system via the CommandServer to create a DVI file convert the DVI file to a PostScript file spool the postscript file to the printer delete the temporary files } closes the address file exits Home | Case Studies | Previous | TOC | Next http://www.janeg.html [15/03/2004 8:46:59 AM] .

he clicks ok. result in a JFileChooser dialog being displayed.swing.FileReader java.io.janeg. Because MailMerge has only static fields. javax.swing.Notes on Design Java Case Study . For example. it is implemented as an inner class.JButton javax. The value of the parameter is saved so that each new instance of the listener knows which field it must set.JOptionPane javax.JDialog javax. when clicked. This involved having MailMerge extend JFrame. the ExitWindowAdapter.exit(0).swing. For example.BufferedWriter java. When finished. the listener attached to the okButton in FileSelector is declared as an anonymous class implementing the ActionListener interface (see the source code for FileSelector) When a listener is required for an event specific to the class but can be used by more than one component belonging to the class. When a listener is required for a class but its functionality is not specific to the class (it has a behaviour that could apply in other situations) it is implemented as a separate class. At that point the input is saved to the MailMerge instance originally passed to FileSelector. is implemented as a separate class.io. (See the import statements in the MailMerge source code).io. Java Libraries Standard Java library classes were used for file handling: java. The BrowseButtonActionListener class is declared within the FileSelector class. which simply calls System.JFileChooser javax.io. A GUI interface was added later. however.io. allowing it to be re-used by other classes.JLabel javax. If MailMerge is started with no command line parameters a FileSelector dialog is displayed.swing.File java. The main window. updating an instance of MailMerge effectively updates the original MailMerge (remember.ca/case/mail/mail_5.swing. http://www.JPanel Event Listeners When a listener is required for an event specific to the class it is implemented as an anonymous class.Mail Merge . It implements the ActionListener interface and provides a constructor that takes a JTextField.FileNotFoundException java. The user enters the file names or clicks a browse button which displays a JFileChooser dialog. The standard classes String and StringBuffer were used for string manipulation.BufferedReader java.io. is never displayed. only one copy of a static field exists for all instances of the class).html (1 of 2) [15/03/2004 8:46:59 AM] . For example.swing.Notes on Design Text and GUI Modes The application was designed to be run in text mode.Mail Merge .Java Quick Reference .IOException java. Standard Swing classes were extended to create all the GUI elements. a FileSelector dialog has two browse buttons both of which.io.swing.JFrame javax. The original class spawns another instance of MailMerge which acts as the parent of the GUI elements.swing.JTextField javax.FileWriter All of these are listed using import-by-type versus import-on-demand statements.Case Study .

Also.editMarkers() ) are passed as final. there is no wildcard expansion unless the operating systems command shell is explicitly started 2. The first call to the method creates an instance of the class and assigns it to a private static field. operating systems have different command syntaxes 3. The use of final signals this intent.Java Quick Reference . Subsequent calls to getInstance() will return the same instance.ca/case/mail/mail_5. From the name it is evident that the class will cause a window componet to be exited and that the class extends the WindowAdapter class versus implementing WindowListener interface. the Java method used to pass commands to the operating system does not start a command shell Home | Case Studies | Previous | TOC | Next http://www.Notes on Design Event listeners are named according to the interface they implement or the adapter they extend and the component they will be registered with.html (2 of 2) [15/03/2004 8:46:59 AM] . Passing parameters All method parameters (except those in MailMerge.janeg. For example. It has a private constructor. The only way to instantiate the class is by calling the public static getInstance() method. An instance specific to the operating system is required as: 1. instance. rather than name the listener responsible for closing a window as ExitWindow it is named ExitWindowAdapter. it allows the compiler to optimize the code for better performance. Passing commands to the operating system CommandServer is implemented using the Singleton pattern.Case Study .Mail Merge . It is considered good practice to pass parameters as final if the method will not modify the value in any way.

ca/case/mail/mail_6. This skeletal implemention could then be extended by subclasses. the bulk of the code is identical across operating systems. An alternative would have been to define CommandServer as an interface and provide a separate CommandServerImpl class that defined the common code.Using an Abstract class CommandServer was implemented as an abstract class. If CommandServer was defined as an interface adding methods would break existing code.Using an Abstract class Java Case Study .Mail Merge . Had the type been defined as an interface a good portion of the code would need to be repeated in each implementation class.Case Study . all types based on the interface would need to add implementation for the new methods.html [15/03/2004 8:47:01 AM] .Java Quick Reference . Especially if you decided to add additional functionality.janeg. Not sure the alternative would buy anything in this example. Home | Case Studies | Previous | TOC | Next http://www. Operating systems offer a vast array of commands and it's highly likely that one day you'll want to add more methods to handle them.Mail Merge . Right now the class has two methods printFile() and deleteFiles(). The subclasses UNIXCommandServer and MSWindowsCommandServer are specializations. Why? In this instance.

Mail Merge .Mail Merge .Java Quick Reference .html [15/03/2004 8:47:02 AM] . The application cannot be reasonably expected to handle these situations therefore the choice of extending RuntimeException versus Exception is justified.ca/case/mail/mail_7. GhostScript may not be installed.Case Study .Extending RuntimeException Generally you hear that you should extend Exception versus RuntimeException when you define your own exceptions. The circumstances surrounding the events are a result of the operating system setup. print the file or delete temporary files. LaTex may not be installed. Home | Case Studies | Previous | TOC | Next http://www.Extending RuntimeException Java Case Study . RuntimeExceptions are used for exceptions that an application cannot reasonably be expected to handle. the user may not have delete authority for the drive he's accessing. The FailedCommandException is thrown when a CommandServer object cannot execute LaTex.janeg.

changed all references in the MailMerge class to use the new MailMergeInputFields object and JFrame reference where necesssary. if the application is started in text mode. no GUI elements would be created.ca/case/mail/mail_8.Case Study . Changed all references in the classes to use the new object. The JFrame would be used as the parent of any GUI components and. Modified the MailMerge class: r r r r removed the inheritance to JFrame replaced the indivual fields letterFileName.The GUI implementation The handling of the GUI is rather awkward. revising the code as follows: 1.Java Quick Reference . Created a new class. add a field of that data type. it's not intuitive.html [15/03/2004 8:47:02 AM] . Tried the above as a refactoring exercise. 3.The GUI implementation Java Case Study . setup() and processFiles() and modified the terminate() method so it could be used as a single exit point from the application. addressFileName and printerName with a MailMergeInputFields object removed the MailMerge instance and added a JFrame reference. Trying to refactor a program helps you test your understanding of how it works.Mail Merge . The initial MailMerge window is never displayed and a second MailMerge instance is created and passed to GUI components. The revised class files are: q MailMergeInputFields q q q q MailMerge Note: the commands directed to LaTex have been commented out as it is not installed on my system. MailMergeInputFields 2. One possible alternative would be to create a seperate object to hold the data input fields. add a JFrame field and add a second constructor that creates the JFrame and takes the new object as a parameter.janeg. Made a few other minor changes: split the code in main() into two separate methods. This method also hides the manner in which the required fields in the original MailMerge are updated. Modified the FileSelector and Report classes to take a MailMergeInputFields object and a JFrame object instead of a MailMerge object. FilesSelector Report Revised UML Diagram Home | Case Studies | Previous | TOC | Next http://www.Mail Merge .

janeg.jpg [15/03/2004 8:47:02 AM] .ca/case/mail/MailMergeInputFields.http://www.ca/case/mail/MailMergeInputFields.jpg http://www.janeg.

jpg http://www.ca/case/mail/FileSelector_1.http://www.janeg.jpg [15/03/2004 8:47:03 AM] .janeg.ca/case/mail/FileSelector_1.

janeg.http://www.jpg [15/03/2004 8:47:03 AM] .jpg http://www.janeg.ca/case/mail/Report_1.ca/case/mail/Report_1.

ca/case/mail/MailMerge_1.janeg.janeg.http://www.jpg http://www.jpg [15/03/2004 8:47:04 AM] .ca/case/mail/MailMerge_1.

jpg [15/03/2004 8:47:06 AM] .http://www.ca/case/mail/uml_1.janeg.ca/case/mail/uml_1.janeg.jpg http://www.

One of the key problems in establishing requirements is determining exactly what the problem domain is. If the person requesting the system and the person desigining the system have different ideas concerning what is inside the domain then the resulting system will either fail to meet user expectations or go beyond user expectations. The scope of a problem domain can be as narrow or as wide as the user wants.Java Quick Reference . especially if you could have produced code that met the users expectations in half the time and at half the cost. Home | Case Studies | Previous | TOC http://www.Solves a problem or problem domain? Java Case Study . provide a solution for the domain. the application would not provide a solution for the domain. In the first instance you'll have an unhappy user.Mail Merge .Solves a problem or a problem domain? Does the example solve a specific problem or solve a problem domain? As the original problem domain was defined as "create a system to merge addresses with a LaTex document" the application does.e.janeg. then no. You may also have an unhappy user in the second instance. The code would have to be altered either by hard-coding the new location (not a recommended solution) or by providing the user a means to input the required location.ca/case/mail/mail_9. There are hard-coded elements that narrow the domain to a Windows system which uses Ghostview to print PostScript files and has the sofware stored at c:/GSTools/GSView/.Case Study .html [15/03/2004 8:47:06 AM] . Had the problem domain been defined in wider terms i. for the most part.Mail Merge . If the code was used on a system that stored Ghostview in another location it would fail. as "develop a mail merge system".

Vol.Case Study .JCalculator q q q q q q q Overview User Defined Types Where the action is Command Behaviour Unary Function Behaviour Binary Function Behaviour Summary Source The code for this study is from Sum it up with JCalculator an article by Claude Duguay in JavaPro.Java Quick Reference .janeg.JCalculator Java Case Study .html [15/03/2004 8:47:07 AM] . August 2001.ca/case/jcalc/jcalc_1.5 No. 8.and may be downloaded from Devx Home | Case Studies http://www.

Overview Java Case Study . The application can be started in simple or expanded mode.html [15/03/2004 8:47:08 AM] .Java Quick Reference .Case Study .ca/case/jcalc/jcalc_2. memory recall. GUI Simple View GUI . Provide basic arithmetic and trigonometric functions along with features found on most standard calculators: clear an entry.JCalculator .Overview Problem Statement Implement a numerical calculator that can easily be added to any Swing application. etc. clear all entries.janeg.Exanded View Home | Case Studies | TOC | Next http://www.JCalculator . memory clear.

JCalculator .defines a button used by the calculator object CalculatorCommands .defines objects used to display information in the calculator CalculatorStack .Java Quick Reference .User Defined Types Java Case Study .html [15/03/2004 8:47:08 AM] .User Defined Types User Defined Types Full UML Class Diagram The application is implemented with the following user defined types: q JCalculator .Case Study .JCalculator .ca/case/jcalc/jcalc_3.defines an object to hold the intermediary results of calculator button operations Home | Case Studies | Previous | TOC | Next http://www.janeg.defines a calculator object q q q q CalculatorButton .defines the commands associated with calculator buttons CalculatorField .

http://www.janeg.ca/case/jcalc/images/FullUml.ca/case/jcalc/images/FullUml.jpg (1 of 2) [15/03/2004 8:47:09 AM] .janeg.jpg http://www.

ca/case/jcalc/images/FullUml.janeg.jpg (2 of 2) [15/03/2004 8:47:09 AM] .http://www.ca/case/jcalc/images/FullUml.jpg http://www.janeg.

janeg.ca/case/jcalc/images/JCalculator.jpg [15/03/2004 8:47:10 AM] .jpg http://www.ca/case/jcalc/images/JCalculator.http://www.janeg.

ca/case/jcalc/images/CalculatorButton.janeg.http://www.janeg.jpg [15/03/2004 8:47:10 AM] .ca/case/jcalc/images/CalculatorButton.jpg http://www.

jpg http://www.janeg.ca/case/jcalc/images/CalculatorCommands.jpg [15/03/2004 8:47:11 AM] .janeg.http://www.ca/case/jcalc/images/CalculatorCommands.

janeg.ca/case/jcalc/images/CalculatorField.janeg.http://www.jpg [15/03/2004 8:47:11 AM] .jpg http://www.ca/case/jcalc/images/CalculatorField.

http://www.jpg [15/03/2004 8:47:11 AM] .ca/case/jcalc/images/CalculatorStack.janeg.janeg.jpg http://www.ca/case/jcalc/images/CalculatorStack.

Unary and Binary. } http://www. In this example. the actionPerfomed() method in a Command pattern example is very simple: public void actionPerformed(ActionEvent e){ command.Command is a command object. CalculatorStack stack = calculator. public void actionPerformed(ActionEvent event) { if (command != null) { if (command instanceof CalculatorCommands. where "8" is the label that will appear on the button. this. (see CalculatorCommands) Each command object implements the exec() method declared in the Command interface. String is the buttons label text. Each calculator button is given a specific command object.Where the action is Where the action is The design utilizes the Command Pattern with all the action being handled by CalculatorButton. One. this is the current JCalculator object and new CalculatorCommands. an ActionEvent is generated and listeners are notified.Function)command).Where the action is Java Case Study . Generally. all the individual commands i.Java Quick Reference . All of them are of type CalculatorCommands.pushFunction((CalculatorCommands. the button itself is controlling some of the behaviour. JCalculator calculator.Unary) { evaluate().exec(). CalculatorCommands. Unary or Binary. JCalculator is a reference to the current calculator object and CalculatorCommands. evaluate(). stack. The Function interface extends the Command interface and Unary and Binary extend Function. For example. The implementation of the Command pattern in this example is a little unusual. Clear.getStack().Case Study .html (1 of 2) [15/03/2004 8:47:12 AM] . } where all the behaviour associated with the button would be implemented in the exec() method of the command object.e. Plus.janeg.Eight() creates the command object that will be associated with the CalculatorButton. When a calculator button is clicked.JCalculator . The CalculatorButton constructor takes the following form: public CalculatorButton( String text. The operation performed is determined by the buttons command object. The CalculatorCommands class contains the definitions for three other interfaces: Function. In the example. CalculatorCommands. A CalculatorButton object acts as it's own listener by implementing the actionPerfomed() method of the ActionListener interface. code that adds a CalculatorButton to the JCalculator object is: add( new CalculatorButton( "8".JCalculator .Command is an interface defined within the CalculatorCommands class. are declared as static member classes of CalculatorCommands.Command command) where. Individual command objects directly implement Command.ca/case/jcalc/jcalc_4. new CalculatorCommands.Eight() ) ).Command. etc.

Binary) { evaluate(). } Command logic is being handled within the actionPerformed() method and a portion of the command behaviour is implemented in the CalculatorButton.Function)command). Home | Case Studies | Previous | TOC | Next http://www. stack.Java Quick Reference .popFunction(). CalculatorField field = calculator. CalculatorCommands.Function)) { command.Where the action is if (command instanceof CalculatorCommands.getStack().getStack().evaluate() method rather than by the command object itself.ca/case/jcalc/jcalc_4.pushNumber(field.isEmpty() && stack.getNumber()).janeg. field.exec(calculator).JCalculator .exec(calculator). protected void evaluate() { CalculatorStack stack = calculator.Case Study . stack.html (2 of 2) [15/03/2004 8:47:12 AM] . stack. if (!stack. field. CalculatorStack stack = calculator.Function function = stack. } if (!(command instanceof CalculatorCommands. } } This makes it a little more difficult to work out what is actually happening when a calculator button is clicked on. UML Sequence diagrams can help when you're trying to sort out interactions between objects. function.pushNumber(field. } } // Handle '=' else evaluate().isFunction()) { CalculatorField field = calculator.getNumber()).pushFunction((CalculatorCommands.getField().popNumber()).clearField().getField().setNumber(stack.

When a button associated with a Command type is clicked. The method checks to make sure the command associated with itself is not a Function and calls the exec() method of it's Command object. invoking its actionPerfomed() method.Command interface. This generates an ActionEvent and the button is notified.Java Quick Reference . what we see before we click on the '1' button is: http://www.addDigit(1).html (1 of 2) [15/03/2004 8:47:13 AM] . The exec() method in the One class is implemented as follows: public void exec(JCalculator calculator) { CalculatorField field = calculator.Command Behaviour Command Behaviour Command objects which are not Functions (One. From the above we can see that 1. the object is type One. etc) directly implement the CalculatorCommands.janeg. the command object then uses the field reference to set the text in the field or add a digit to the text already being displayed Let's say a user clicks on the "1" calculator button. the CalculatorButton. } The addDigit() of CalculatorField actually concatenates the digit '1' to any text currently being displayed. the button invokes the exec() method of its assoicated command object.JCalculator . Two.evaluate() method is not invoked. field. the actionPerformed() method invokes the objects exec() method. In this case.Case Study .ca/case/jcalc/jcalc_5. the command object uses the reference to the calculator object to get a reference to the CalculatorField being used to display the numbers entered by the user and the results of any calculations 4. when an ActionEvent is triggered it is sent to a CalculatorButton 2. For example. passing it a reference to the calculator object 3.Command Behaviour Java Case Study .getField().JCalculator . Clear.

ca/case/jcalc/jcalc_5.janeg.html (2 of 2) [15/03/2004 8:47:13 AM] . Home | Case Studies | Previous | TOC | Next http://www.Java Quick Reference . Unary function commands are a bit more complicated.JCalculator .Command Behaviour What we see after clicking the '1' button is: That's fairly straight forward.Case Study .

stack.JCalculator .sqrt(stack.Sqrt which implements Unary. The code for Sqrt is: public static class Sqrt implements Unary { public void exec(JCalculator calculator) { CalculatorStack stack = calculator. http://www.Case Study . Lets assume the calculator button that was clicked has a Sqrt command of type CalculatorCommands.Java Quick Reference .JCalculator .html (1 of 4) [15/03/2004 8:47:15 AM] .popNumber())).getStack(). } } The Sqrt button is clicked.Unary Function Behaviour Java Case Study .janeg.Unary Function Behaviour Unary Function Behaviour Every button has an associated CalculatorCommands.Command object reference and a JCalculator reference.ca/case/jcalc/jcalc_6.pushNumber(Math. an ActionEvent is raised and the buttons actionPerformed() method is invoked.

Unary Function Behaviour 1. the buttons reference to the calculator object is used to get a reference to the calculators stack 4. let me have your Stack. Do we have a command? Oh yeah.Java Quick Reference .Case Study . lets try to think of it as a conversation between actors." "Sure thing.JCalculator . here. the result returned by Math. there is nothing else to do Whew! There are an awful lot of busy objects! The actual job of providing the square of a number is handled by the command object. Stack." ActionPerformed: of Sqrt.janeg. the Sqrt object uses its calculator reference (the one passed to exec() ) to get a reference to the calculator stack 16. the actionPerformed() method checks its objects (the buttons) command object type and determines its of type CalculatorCommands.html (2 of 4) [15/03/2004 8:47:15 AM] . the buttons command object (in this case aSqrt) is pushed onto the stack 7.Button's helper q Stack . but the responsibility for getting everything ready for the Sqrt object is being handled by the button object." http://www. the Sqrt object is popped off the calculators stack 12.a CalculatorButton q Calculator . it invokes its own evaluate() method 3.a JCalculator that belongs to Button q Sqrt . pass me your Stack for a minute. the evaluate() method returns control to the actionPerformed() method 21.Button's helper q Evaluate . you need to "Ok. the result pushed onto the stack by the Sqrt object is retrieved and passed to the calculator field by invoking the fields setNumber() method 20. the stack isEmpty() method is invoked and returns 'true' so evaluate() returns control to the actionPerformed() method 5. can you check things for me?" Evaluate: Calculator: Evaluate: it's up to you. control returns to the buttons evaluate() method 19. ActionPerformed. still not all that clear. the Sqrt objects exec() method is invoked and a copy of the buttons calculator reference is passed as an argument 15. the field reference is used to retrieve the number currently displayed 13.a CalculatorCommands.sqrt() is pushed onto the stack 18. a Sqrt and its a Unary." [Hands Stack to Evaluate] "Oops . Sqrt.a CalculatorStack that belongs to Buttons calculator q Display .sqrt() 17.. this time the stack is not empty and its top object is a function (the Sqrt object) 10.. a reference to the calculators stack is retrieved 9. the number pushed onto the stack in evaluate() is popped off the stack and used as an argument to Math. The cast: q Button .sqrt .Unary that belongs to Button q Math. the buttons evaluate() method is again invoked 8. "Calculator. its empty nothing for me to do..a friend of Sqrt's q ActionPerformed ." "Here he is. your turn again. take a copy [Hands Sqrt to Stack] "Ok Evaluate.ca/case/jcalc/jcalc_6. the retrieved number is pushed onto the stack 14. the actionPerformed() method retrieves a reference to the calculators stack through the buttons calculator reference 6.a CalculatorField that belongs to Buttons calculator Button: get to work!" ActionPerformed: Evaluate "Hey. Calculator. Hmmm . the buttons calculator reference is used to retrieve a reference to the calculators display field 11. I've just been clicked! ActionPerformed.Unary 2.

let me have the number Sqrt just gave you. we're all done now. Hey Evaluate. here you need to talk to [Hands Sqrt a connection to Calculator] Sqrt: "Calculator. Oops. The calculator is basically acting as a holder for all the objects. you do your thing." "Great. I need to pass it to "Here Sqrt.sqrt: back now.Case Study ." [Calculator hands over Stack] Stack (sotto voice): "Hey.. I'm tired of being man handled! Geesh. "Stack." Math.Unary Function Behaviour Evaluate: Calculator: Evaluate: Stack: Evaluate: Stack: Evaluate: "Calculator. give me Stack please. let me have that function and Display." "Do you have a function?" "Let me see. don't you guys have anything better to do!" Sqrt: Math.sqrt.ca/case/jcalc/jcalc_6." [Hands Stack to Evaluate] "Alright Stack are you empty?" "Nope.janeg. can you give me your Display?" [Calculator hands Display to Evaluate] Evaluate: "Stack." [Stack the number to Evaluate].JCalculator . take number back now. "Display." Sqrt: I'm finished. give me the number your holding." [Display takes the number and holds it up for "Stack. I got a function on top of me.. yup. Calculator. you can have it "Here you go Stack . I'm finished!" "Button. you give Stack the number you're holding. can you show this to http://www.html (3 of 4) [15/03/2004 8:47:15 AM] ." "Thanks guys. can you let me see Stack again?" "Sure. I did my thing with the number." Evaluate: hands everyone?" Display: all to see] Evaluate: ActionPerformed: Button: "Ok ActionPerformed." [Stack hands Sqrt to Evaluate and Display gives Stack a number] Evaluate: Calculator" "Ok Sqrt. What a team!" [The End] That's a little clearer. The actionPerformed() and evaluate() methods in CalculatorButton are directing events and the actual work/function is being handled by the "Sure thing.Java Quick Reference .

ca/case/jcalc/jcalc_6.html (4 of 4) [15/03/2004 8:47:15 AM] .JCalculator .janeg.Unary Function Behaviour CalculatorCommands.Case Study .Command object.Java Quick Reference . So what happens if the command object is a Binary function? Home | Case Studies | Previous | TOC | Next http://www.

CalculatorStack stack = calculator.pushFunction((CalculatorCommands.Java Quick Reference . How does a Binary function get executed? You'd expect the user to enter another digit followed by "=".Function)) { http://www.Case Study .clearField().Unary) { evaluate().Binary) { evaluate().html (1 of 4) [15/03/2004 8:47:17 AM] .Function)command). stack.getNumber()).getStack(). field.janeg.pushNumber(field. stack. CalculatorStack stack = calculator. the stack is being setup but no calculations are happening. public void actionPerformed(ActionEvent event) { if (command != null) { if (command instanceof CalculatorCommands.Binary Function Behaviour Java Case Study .getField(). evaluate().Function)command). } if (command instanceof CalculatorCommands. Lets take another look at actionPerformed(). } if (!(command instanceof CalculatorCommands.getStack().ca/case/jcalc/jcalc_7. CalculatorField field = calculator.Binary Function Behaviour Binary Function Behaviour Hmmm .pushFunction((CalculatorCommands.JCalculator . stack.JCalculator ..

} It looks like "=" is not a Command object.exec(calculator). Only the evaluate() method comes into play. so evaluate() pops off the function. Ok. so let's say the user enters '1 + 1 ='.Binary Function Behaviour command. Then Binary. the '1' and '+' placed there earlier. pushing the result back onto the stack. pushes the current number (the one in the display area) onto the stack and then invokes the functions exec() method. The evaluate() method then pops the result off the stack and calls the display fields setNumber() method.janeg. which shows the result of the operation to the user.html (2 of 4) [15/03/2004 8:47:17 AM] .Java Quick Reference .ca/case/jcalc/jcalc_7. what happens? This time there is something on the stack.Case Study .JCalculator .exec() method then retrieves both the numbers from the stack and performs its operation. But what happens if '=' isn't pressed after the second digit is entered? What if the user enters '1 + 1 + 2' before hitting '='? http://www. } } // Handle '=' else evaluate().

ca/case/jcalc/jcalc_7.Binary Function Behaviour Almost the same thing as happens when '=' is pressed except that the previous function is evaluated and the result of the operation is placed on the stack followed by the current function.Case Study . The '1 + 1 + 2' would result in the following: User Enters 1 + 1 + Field Display 1 blank 1 blank Stack empty + 1 + 1 + 2 ( result of previous stack http://www.html (3 of 4) [15/03/2004 8:47:17 AM] .Java Quick Reference .JCalculator .janeg.

html (4 of 4) [15/03/2004 8:47:17 AM] .janeg.ca/case/jcalc/jcalc_7.JCalculator .Java Quick Reference .Binary Function Behaviour value '1' '+' current display value of '1' ) 2 = added to 2 4 + 2 empty ( previous result value is current display value ) Home | Case Studies | Previous | TOC | Next http://www.Case Study .

Case Study . straight forward design. the code was not written as a demonstration of design technique.ca/case/jcalc/jcalc_8. After working through the sequence diagrams though. Home | Case Studies | Previous | TOC | http://www. originally I thought that this was an elegant.JCalculator .Summary Summary Well.janeg.Java Quick Reference . and it does work quite nicely. I now have my doubts.Summary Java Case Study .JCalculator . the author provided it as a plug-in component that can be used in any program.html [15/03/2004 8:47:17 AM] . I don't think working out code logic should be quite that difficult! Admittedly.

io Package Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java.lang Package The java.awt Package The java. classes and interfaces for serialization 3.Overview q the package contains three main groups of classes and interfaces 1. usually provide methods which return a stream for either reading or writing data streams can be chained together q q Filter Streams q q q filter streams perform some processing or filtering as the data is passed through a filter ouput stream performs the processing before the data is written out a filter input stream performs the processing after the data is read from its original source Character Streams class FilterReader class FilterWriter FilterStream SuperClasses Byte Streams class FilterInputStream class FilterOutputStream q there are number of filter streams for both byte streams BufferedInputStream DataInputStream LineNumberInputStream PushbackInputStream and character streams BufferedReader LineNumberReader PushbackReader BufferedOutputStream DataOutputStream PrintStream q PrintWriter http://www.Java Quick Reference .java.util Package The java.janeg. classes and interfaces for working with the file system Data Streams (JCL1) q q q data streams that read values from a data source are input streams data streams that write values to a data repository are output streams the data can be either byte or character values Character Streams abstract class Reader abstract class Writer DataStream SuperClasses Byte Streams abstract class InputStream abstract class OutputStream q there are two classes which convert bytes to characters class InputStreamReader extends Reader class OutputStreamWriter extends Writer data containers. for example files.html (1 of 2) [15/03/2004 8:47:19 AM] . classes to build data streams 2.io Package .ca/scjp/io/overview.

java.Java Quick Reference .io Package In-Memory Streams q there are also classes for reading and writing data held in memory CharArrayReader CharArrayWriter StringReader StringWriter the StringReader/Writer classes read data from a StringBuffer object ByteArrayInputStream ByteArrayOutputStream q Pipes q there are classes that allow you to build streams that operate between threads PipedInputStream PipedOutputStream PipedReader PipedWriter Files q there are a number of classes for working with the file system File FileDescriptor FileInputStream FileReader FileOutputStream FileWriter FilenameFilter FilePermission RandomAccessFile note that File.ca/scjp/io/overview.html (2 of 2) [15/03/2004 8:47:19 AM] . FileDescriptor and RandomAccessFile are direct subclasses of Object Note q The File class can be used to create directories Serialization (JCL1) q serialization is the process of converting an object to a stream of bytes in such a manner that the original object can be rebuilt (lets you write an object to a file or other data container) Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www.janeg.

html [15/03/2004 8:47:19 AM] . FileOutputStream Sink Type Character Streams Memory CharArrayReader.Java Quick Reference . CharArrayWriter StringReader. StringWriter Pipe File q PipedReader. BufferedOutputStream Process Buffering Filtering Converting between Bytes and Characters Concatenation Object Serialization Data Conversion Counting FilterReader.java. files.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes The java.io Package . FilterWriter FilterOutputStream InputStreamReader. ByteArrayOutputStream StringBufferInputStream PipedInputStream. ObjectOutputStream DataInputStream.lang Package The java. BufferedWriter Byte Streams BufferedInputStream. pipes Byte Streams ByteArrayInputStream.Data Streams q q Suns Java Tutorial on I/O also breaks up the classes into Data Sink Streams and Data Processing Streams a sink is a specialized data container ie strings. DataOutputStream LineNumberInputStream PushbackInputStream PrintStream LineNumberReader PushbackReader PrintWriter SCJD Notes Projects Favourite Links About Feedback Peeking Ahead Printing Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www.util Package The java. FileWriter data processing streams perform some type of operation ie buffering or character encoding CharacterStreams BufferedReader. PipedOutputStream FileInputStream.janeg.awt Package The java. FilterInputStream.io Package .Data Streams Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.ca/scjp/io/datastreams. OutputStreamWriter SequenceInputStream ObjectInputStream. PipedWriter FileReader.

java.ca/scjp/io/char.awt Package The java. Images are from the Sun Tutorial on I/O character streams can read or write any Unicode character set.io Package .util Package The java.Java Quick Reference . q SCJA Notes SCJD Notes Projects Favourite Links About Feedback q Note: Classes shown in 'yellow' are abstract. Items shown in 'gray' read and write from data sinks.io Package .lang Package The java.html [15/03/2004 8:47:20 AM] . Byte streams are limited to ISO-Latin-1 8-bit encoding.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies The java.janeg. Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www.Character Streams q Reader and Writer are the abstract superclasses for all character streams.Character Streams Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.

io Package References Miscellaneous Notes Tips & Traps Mock Exams The java. Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www. Classes in 'gray' read and write to data sinks. Images from Sun Java I/O tutorial ObjectInputStream and ObjectOutputStream are used for serialization !!! Warning !!! Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback These classes cannot be used to read or write Unicode characters.Byte Streams q use InputStream and OutputStream classes to read 8-bit bytes q Note:Classes in 'yellow' are abstract.Byte Streams Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.html [15/03/2004 8:47:20 AM] .lang Package The java.Java Quick Reference .io Package .java.io Package .janeg.ca/scjp/io/byte.awt Package The java.util Package The java.

ca/scjp/io/file.janeg. however. for Win32 String pathSeparator string representation of the pathSeparator character q q q q FileName Methods q there are a number of methods for retreiving filenames. String child) where.Java Quick Reference . String child) File(File parent.io Package . etc getAbsolutePath() getCanonicalPath() getName() getParent() getPath() compareTo() getAbsoluteFile() getCanonicalFile() getParentFile() http://www. or. parent is the pathname child is the filename used to create an instance of a File BUT does not actually create a file // does not create a file on the system new File("test. paths.File Class Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.txt").createNewFile().File Class q q used to access file and directory objects using the file-naming.awt Package The java.lang Package The java. the method createTempFile() which creates the file in the default temporary directory using specified file extensions the class has four CONSTANTS which define properties of the file conventions on the operating system char separatorChar the field is initialized to hold the system separator / for UNIX \ for Win32 : for Mac String separator a string representation of the separatorChar char pathSeparator initialized to hold the character used by the system to separate file names in a list : for UNIX .txt").util Package The java.io Package . // returns 'false' if file exists f.java. path conventions of the implementing operating system the class has three constructors File(String pathname) File(String parent.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java.html (1 of 3) [15/03/2004 8:47:21 AM] . you can use the createNewFile() method File f = new File("test.

println( f1.getAbsolutePath() ). the following code creates a file 'test2. "test2.".txt the canonical path is the same as the absolute path BUT all relative indicators are resolved For example. Two files are equal() if they have the same path.println( f1.html (2 of 3) [15/03/2004 8:47:21 AM] .java. NOT if they refer to the same underlying file system object. Output (on Win98): D:\Java\jeg\io\. the reference will return the original path and name // File object reference q q q http://www.txt toURL() will construct a valid URL identifier for the File System.janeg..createNewFile().. Output: file:/D:/Java/jeg/io/test1.Java Quick Reference .out. Output (on Win98): // '.' in absolute path is resolved D:\Java\jeg\test2.out.println( f.ca/scjp/io/file.\test2.txt' in the directory directly above the current directory: File f1 = new File(".txt") f1.out. File Status Methods q there are methods to check the status of a file canRead() canWrite() exists() length() lastModified() setLastModified() setReadOnly() isDirectory() isFile() isHidden() isAbsolute() Modifiying Files and Directories q there are a number of methods for modifiying files and creating directories delete() mkdir() listFiles() deleteOnExit() mkdirs() listRoots() renameTo() list() and listFiles() can be used with FilenameFilters ie '*' listRoots() returns the system drives while renameTo() will change the name of the file on the system.File Class q toURL() the absolute path is system dependent and may include relative indicators For example. System.getCanonicalPath() ).toURL() ).equals() method.txt Note q q q q the File class overrides the Object.io Package .. System.

txt // original path for 'f' And if you check to see which file actually exists on the system: System.txt").println( f2.exists() ). System.out.Java Quick Reference . f. // renames the file System.janeg. // creates the file // new File reference File f2 = new File("testRename.println( f.getAbsolutePath() ).renameTo(f2).out.out.println( f. Output: false true Note q There is no method which allows you to change directories! Security q q many of the above methods will work correctly only if they are allowed by the security permissions for example.ca/scjp/io/file.exists() ). Output (on Win98): D:\Java\jeg\io\test1. an Applet would probably not be allowed to create a new file Source Code for Examples q TestFileClass.File Class File f = new File("test. f.txt").html (3 of 3) [15/03/2004 8:47:21 AM] .createNewFile().java.java Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www.io Package .

io Package . byte order specified by a mandatory initial byte-order mark (either order accepted on input.a.ca/scjp/io/readwrite.janeg.Readers and Writers Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. FileReader InputStreamReader reads bytes and translates them to Unicode characters using the specified character encoding or the default system encoding the class has two constructors InputStreamReader(InputStream in) InputStreamReader(InputStream in. a. ISO646-US.awt Package The java. ISO-LATIN-1 UTF-8 Eight-bit Unicode Transformation Format UTF-16BE Sixteen-bit Unicode Transformation Format. 1. q Character Encoding q q q Character encodings specify how 8-bit bytes are translated to 16-bit Unicode they are represented by Strings which follow the naming standards set by IANA Character Registry every implementation of Java is required to support the following sets: US-ASCII Seven-bit ASCII.io Package .k.k. little-endian byte order UTF-16 Sixteen-bit Unicode Transformation Format. big-endian used on output) specific platforms ie those used in Japan.java. may include other encodings SCJD Notes Projects ISO-8859-1 Favourite Links About Feedback q http://www. China. the Basic Latin block of the Unicode character set ISO Latin Alphabet No.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes The java.a. Mid-East. etc.Readers and Writers InputStreamReader q q q InputStreamReader extends Reader and has one subclass.a. You can then read the stream using any of the Reader methods. a.util Package The java. a.html (1 of 2) [15/03/2004 8:47:22 AM] . String enc) you use OutputStreamWriter by first creating an instance of it for a byte output stream. big-endian byte order UTF-16LE Sixteen-bit Unicode Transformation Format. String enc) to use an InputStreamReader you must first create an instance of it for a byte input stream.k.Java Quick Reference . you can then write to the stream using an Writer methods.lang Package The java. FileWriter OutputStreamWriter translates between Unicode characters and bytes using the specified character encoding or the default system encoding the class also has two constructors OuputStreamWriter(OutputStream out) OuputStreamWriter(OutputStream out. q OutputStreamWriter q q q OutputStreamWriter extends Writer and has one subclass.

ca/scjp/io/readwrite.io Package . } Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www. "iso-8859-6"). return new InputStreamReader(fileIn.janeg.java.html (2 of 2) [15/03/2004 8:47:22 AM] .Java Quick Reference . to read bytes encoded under ISO 8859-6 for Arabic characters public Reader readArabic(String file) throws IOException { InputStream fileIn = new FileInputSgream(file).Readers and Writers q q the streams are used to read and write data encoded in a character set which is different than the default system encoding For example (JPL pg238).

in as it assumes Latin-1 character encoding. and any of it's subclasses. it can take any InputStream object.awt Package The java.lang Package The java. FilterReader classes take a Reader object. FilterWriter classes take a Writer object.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q q Filters sit between input and output streams.janeg. processing the bytes being transferred FilterInputStream extends InputStream and FilterOutputStream extends OutputStream this means a FilterInputStream.io Package .Java Quick Reference . http://www. Create subclasses of FilterInputStream and FilterOutputStream 2.ca/scjp/io/filters.java.Filters q q q q Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. int size) DataInputStream(InputStream in) LineNumberInputStream(InputStream in) PushbackInputStream(InputStream in) PushbackInputStream(InputStream in. Override the read() and write() methods 3. int size) DataOutputStream DataOutputStream(OutputStream out) PrintStream PrintStream(OutputStream out) PrintStream(OutputStream out.Filters Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments The java.html (1 of 2) [15/03/2004 8:47:22 AM] . Override any other methods you might need 4. PrintStream is included for historical reasons. can take any InputStream as an argument and a FilterOutputStream can take any OutputStream this allows the chaining of filter streams ie a FilterInputStream can take another FilterInputStream. it can take any OutputStream object. you can have as many filters as you like but the last in the chain must be an OutpuStream both methods simply override all their inherited methods. It should only be used with System. passing all their processing along to the underlying Input or Output stream Constructors BufferedInputStream(InputStream in) BufferedInputStream(InputStream in. the original source can be an object that is not a filter stream as long as it isn't reading from another input stream Output filters can also be chained. most Reader and Writer classes can also act as filters as most of them already have constructors which take another character stream to create your own filter streams 1. int size) FilterInputStream Subclasses Subclass BufferedInputStream DataInputStream LineNumberInputStream PushbackInputStream FilterOutputStream Subclasses Subclass Constructors BufferedOutputStream BufferedOutputStream(OutputStream out) BufferedOutputStream(OutputStream out.io Package .util Package The java. If an output filter. you should use PrintWriter when doing character related I/O . boolean autoflush) q q technically. Make sure the input and output streams work together Summary q q q q If its an input filter.

ca/scjp/io/filters.io Package .java.Java Quick Reference .java Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www.Filters Source code for Examples q TestFilterWriter.janeg.html (2 of 2) [15/03/2004 8:47:22 AM] .

Java Quick Reference . specialized write() methods to handle the various primitive types and UTF-8 characters DataOutputStream Methods write(int oneByte) write(byte[] buf) write(byte[] buf. int offset.java.lang Package The java.util Package The java. All the methods throw IOException Source Code for Examples q DataIOTest. int count) readBoolean() readByte() readChar() readDouble() readFloat() readFully(byte[] buf) readFully(byte[] buf. and DataOutputStream.io Package . DataInputStream has specialized read() methods. like all filters. int offset.java Pkg Overview Data Streams Character Streams Byte Streams File Class Readers & Writers http://www.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q DataInputStream and DataOutputStream.Data Input and Output Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments The java. must be attached to some other stream DataInputStream implements DataInput and has one ctor DataInputStream(InputStream in) DataOutputStream implements DataOutput has one ctor DataOutputStream(OutputStream out) and one field written which contains the number of bytes written.awt Package The java.janeg.MAX_VALUE. Note: if this overflows it is set to Integer.ca/scjp/io/data.io Package . int offset. int count) readInt() readLine() readLong() readShort() readUnsignedByte() readUnsignedShort() readUTF() skipBytes() writeInt(int val) writeLong(long val) writeShort(int val) writeUTF(String str) Items in red are deprecated. int count) writeBoolean(boolean b) writeByte(int val) writeBytes(String str) writeChar(int val) writeChars(String str) writeDouble(double val) writeFloat(float val) DataInputStream Methods read(byte[] buf) read(byte[] buf.html (1 of 2) [15/03/2004 8:47:23 AM] .Data Input and Output q q q Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.

Java Quick Reference .io Package .ca/scjp/io/data.html (2 of 2) [15/03/2004 8:47:23 AM] .janeg.Data Input and Output Filter Streams Data Input/Output Reading & Writing Files Serialization http://www.java.

String mode) public RandomAccessFile(File file. To guarantee the data is written to disk use the FileDescriptor method sync() FileReader and FileWriter read and write 16-bit Unicode characters FileInputStream and FileOutputStream read and write bytes q q Random Access Files (JPL pg 258) q the RandomAccessFile class is NOT a subclass of InputStream. a constructor that takes a File object 3. String mode) the mode argument must be either "r" or "rw" to indicate if the file is to be opened for reading only or reading and writing if the file is opened for writing and it does not exist. instead it incorporates all their functionaly plus additional methods by implementing the DataInput and DataOutput interfaces.html (1 of 2) [15/03/2004 8:47:24 AM] . boolean append) if the file exists. This can be accessed by calling getFD() a FileDescriptor object represents a system-dependent value that describes an open file FileOutputStream has one additonal constructor FileOutputStream(String name.util Package The java. Note q q q flush() does NOT guarantee that the contents will be written to disk. you can set append to true to force the write to occur at the end of the file.awt Package The java.Java Quick Reference . a constructor that takes a FileDescriptor object when constructors (1) or (2) are used. the class has two constructors public RandomAccessFile(String name. it will be created as with the other File streams.lang Package The java. a constructor that takes a filename as a String 2.ca/scjp/io/rwfiles. Note q You cannot use a RandomAccessFile object where any of the other input and output streams are required. a FileDescriptor object is created when the file is opened the class allows you to set a read/write pointer to any position in the file key methods are: public public public public long void void long getFilePointer() throws IOException seek(long pos) throws IOException skipBytes(int count) throws IOException length() throws IOException q Favourite Links About q Feedback q q q q http://www.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects The java.Reading and Writing Files q q q q FileStreams have three types of constructors 1. otherwise.io Package . a new FileDescriptor object is created. OutputStream.io Package .janeg.java. Reader or Writer.Reading and Writing Files Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. the existing file is overwritten FileOutputStream (and FileWriter) have a flush() method that forces the underlying buffer to be flushed.

CopyBytes.Reading and Writing Files Source code examples q q q q q Read a file using FileInputStream Write to a file using FileWriter Copy a file (jung.io Package .ca/scjp/io/rwfiles.txt) to another file using FileReader and FileWriter An example.java.janeg. to do the same thing using FileInputStream and FileOutputStream Test using a RandomAccessFile Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www.Java Quick Reference .html (2 of 2) [15/03/2004 8:47:24 AM] .

has become its proselyte. Jung. since it is not represented and personified by any mass organization.txt The bigger the crowd the more negligible the individual becomes.ca/scjp/io/jung. C.janeg.G. should feel that his life has lost its meaning--which. after all. But if the individual. 1958 http://www. is not identical with the public welfare and higher standards of living--then he is already on the road to State slavery and. The Undiscovered Self. New American Library.ca/scjp/io/jung.txt [15/03/2004 8:47:25 AM] . without knowing or wanting it. But that is just what is happening today: we are all fascinated and overawed by statistical truths and large numbers and are daily apprised of the nullity and futility of the individual personality.http://www.janeg. The man who looks only outside and quails before the big battalions has no resource with which to combat the evidence of his senses and his reason. overwhelmed by the sense of his own puniness and impotence.

protected.Serialization Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. arrays.io Package .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java.defaultWriteObject() and read back using ObjectOutputStream. this applies to all public. a NotSerializableException is thrown deserialization is the process of restoring a serialized object to a copy of the original object all Java primitive types.ca/scjp/io/serialize.html [15/03/2004 8:47:26 AM] .janeg.lang Package The java.Serialization Serialization (JCL1) q q q serialization is the process of converting an object to a stream of bytes in such a manner that the original object can be rebuilt (lets you write an object to a file or other data container) an object can be serialized only if it's class implements the Serializable or Externalizable interface.awt Package The java.java.Java Quick Reference .io Package .defaultReadObject() all the objects referred to directly or indirectly are also serialized if a field contains an object that is not serializable. Strings and objects can be serialized/deserialized primitive types can be serialized using DataInputStream Interface and deserialized using DataOutputStream Interface Pkg Overview Data Streams Filter Streams Data Input/Output Character Streams Reading & Writing Files Byte Streams Serialization File Class Readers & Writers http://www. package and private fields (JCL1) Note Only the accessible fields of the superclasses are serialized q q q q q q the serialized fields are written out using ObjectOutputStream.util Package The java. it's superclass must have a no-arg default constructor or be Serializable itself a classes serializable fields are all of its nontransient and nonstatic fields.

util Package .lang Package The java.janeg. etc. sort.util Package The java.html [15/03/2004 8:47:27 AM] .awt Package The java.The Collections Framework q a collection is a container or object that groups multiple objects into a single unit a Collections Framework provides a unified system for organizing and handling collections and is based on four elements: 1. Interfaces that characterize common collection types 2.ca/scjp/util/framework.Java Quick Reference . iterate. q q the Collection Framework in Java has six core collection Interfaces: q SCJA Notes SCJD Notes Projects Favourite Links About Feedback q the Collection Framework also provides an interface for traversing collections: Interator and it's subinterface ListIterator the Iterator interface should be used in preference to the earlier Enumeration interface Collections Framework Collection Abstract Classes Iterator List http://www. Classes which provide implementations of the Interfaces 4.The Collections Framework Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies The java. Abstract Classes which can be used as a starting point for custom collections and which are extended by the JDK implementation classes 3. Algorithms that provide behaviours commonly required when using collections ie search.

MAX_VALUE returns the collection elements as an array. If the collection class guarantees an order.html (1 of 2) [15/03/2004 8:47:28 AM] . and 2. a new array of the same type is returned. no-argument constructor. There is no guarantee as to the order of the returned elements unless the collection is an instance of a class that guarantees the order. retainAll(Collection c) retains all the elements in this collection that are contained in the specified collection Modification Methods http://www.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java.MAX_VALUE if the collection equals or exceeds Integer. the array element after the last collection element is set to null Bulk Methods size() toArray() toArray(Object a[]) containsAll(Collection c) returns true if the collection contains the all the elements in the specified collection addAll(Collection c) clear() adds all the elements in the specified collection to this collection removes all the elements in the collection removeAll(Collection c) removes all the this collections elements that are in the specified collection.util Package The java. returns the number of elements in the collection or Integer. instead they implement the subinterfaces List or Set it is typically used to manipulate and pass collections around in a generic manner classes which implement Collection or one of it's subinterfaces must provide two constructors 1. returns all the elements in the collection whose type is that of the array type.util Package .lang Package The java.The Collection Interface Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. a constructor which takes a Collection as an argument and creates a new collection with the same elements as the specified collection Query Methods contains(Object o) isEmpty() iterator() returns true if the collection contains the specified element returns true if the collection has no elements returns an Iterator object.awt Package The java. a default. If the collection does not fit in the array. which creates an empty collection. the array elements are in the guaranteed order.Java Quick Reference .ca/scjp/util/collection. If the array is larger than the collection.janeg.The Collection Interface q q q q this is the root interface for the collection heirarchy it is not directly implemented by an SDK class.

removes the specified object from the collection.janeg.ca/scjp/util/collection.The Collection Interface add(Object o) adds an element to the collection. Returns false if the element is not added as the collection class guarantees no duplicates. if it exists.html (2 of 2) [15/03/2004 8:47:28 AM] .Java Quick Reference .hashCode() hashCode() Tips q any SDK class which implements Collection or any of it's subinterfaces will contain the two required constructors CollectionName() and CollectionName(Collection c) Collections Framework Collection Abstract Classes Iterator List http://www. equals() and hasCode() remove(Object o) equals(Object o) programmers may override the Object.equals() method to implement collection specific comparisons eg "value" comparison vs "reference" comparison programmers overriding equals() must also override Object.

5.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java. AbstractCollection AbstractList AbstractMap AbstractSequential AbstractSet q q JSK implementations extend the applicable Abstract class and implement the appropriate Interface Collections Framework Collection Abstract Classes Iterator List http://www.Collections Abstract Classes Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.janeg. 4.util Package The java.ca/scjp/util/abstract.Java Quick Reference . 2.html [15/03/2004 8:47:28 AM] .util Package .The List Interface q provide skeletal implementations that can be used as the basis for building custom collection classes available classes are: 1. 3.awt Package The java.

the size of the list if there are no more elements returns the previous element in the List previousIndex() returns the index of the previous element in the list. which allows a programmer to traverse a List in either direction and make modifications to the underlying List java.janeg. or.awt Package The java. If positioned at the first element.The Iterator Interface q q used to sequentially access collection elements element order depends on the collection ie List elements are presented as they appear in the List.util.util Package The java.ListIterator Methods Query Methods hasNext() hasPrevious() next() nextIndex() previous() returns true if there are more elements in a forward direction returns true if there are more elements in a backward direction returns the next element in the List returns the index of the next element in the list. remove() removes the last element in the List retrieved by a next() or previous() operation.The Iterator Interface Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.util Package . returns -1 Modification Methods add(Object obj) inserts the new object immeadiately before the element which would be returned by next(). Can only be made once after a next() or previous() operation and cannot be made if there has been an intervening add(). set(Object obj) replaces the last element in the List retrieved by a next() or previous() operation.ca/scjp/util/iterator. Set elements can be in any order Iterator Methods hasNext() returns true if the iteration has more elements next() returns the next element in the iteration remove() removes the most recently retrieved element from the underlying collection q has one subinterface. Collections Framework Collection Abstract Classes Iterator List http://www.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java.html [15/03/2004 8:47:28 AM] .lang Package The java.Java Quick Reference . ListIterator. there can be no intervening call to add() or remove().

attempts to modify a list that does not support the above will result in an UnsupportedOperationException there is no way to append Lists unless you provide your own method java. Serializable Elements are ordered.html (1 of 2) [15/03/2004 8:47:29 AM] .janeg. LinkedList retains a reference to both the first and last elements. except at the end of the array. The vector will grow automatically to take new objects. Internally uses an array to store elements.util Package .awt Package The java. Otherwise. add an element 2. Internally uses a doubly linked list to store elements.util Implementations of List ArrayList extends AbstractList implements List. May contain null elements.util Package The java. Serializable Older class that was modified in JDK 1. Cloneable.Java Quick Reference . while adding and removing elements. index access is slow as the entire list must be traversed. Adding and removing elements involves updating two links.The List Interface q q q q q q q q a List is a collection whose elements can be accessed by an index the indices are zero-based a list has methods for inserting and removing elements a list can contain duplicate elements a List provides a special ListIterator which allows you to move backwards and forwards through the elements there are three basic ways in which a List can be modified: 1.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects The java. manipulated the same as an array. An expansible array. is expensive. You can also shrink a Vector.ca/scjp/util/list. Serializable Elements are ordered. Vector extends AbstractList implements List. replace an element a list can support any or none of the above. LinkedList extends AbstractSequentialList implements List. retrieving the first or last element is efficient. All methods are synchronized Favourite Links About Feedback List Methods http://www. Cloneable. Index access is quick.lang Package The java.The List Interface Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.2 to implement List. remove an element 3. Cloneable.

janeg. int toIndex) returns the portion of the list between the specified indices exclusive of the toIndex element Collections Framework Collection Abstract Classes Iterator List http://www. shifiting all the elements and subtracting one from their indices Search Methods indexOf(Object o) lastIndexOf(Object o) returns the index of the first occurence of the specified element or -1 if it is not found returns the index of the last occurence of the specified element or -1 if it is not found List Iterator listIterator() listIterator(int index) returns a list iterator of the elements in their proper sequence returns a list iterator of elements starting at the specified index remove(int index) subList(int fromIndex.Java Quick Reference .html (2 of 2) [15/03/2004 8:47:29 AM] . Object element) returns the element at the specified position replaces the element at the specified position with the given object inserts the specified element at the specified position. Object element) add(int index.ca/scjp/util/list. shifting all the elements and adds one to their index values removes the element at the specified position.The List Interface Positional Methods get(int index) set(int index.

io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java. all other classes inherit it's methods protected Object clone() throws CloneNotSupportedException returns an identical copy of an object. they are known as class descriptors provides over 30 methods which can be used to obtain information on a running class some of the more useful methods are: getName().lang Package . toString(). isInterface().Java Quick Reference . public final void wait(long timeout) throws InterruptedException.Main Classes q q q the java. int nanos) throws InterruptedException causes the current thread to wait until another thread invokes notify() or notifyAll() for this object. supports hash tables public final void notify() wakes up a single thread waiting on the object's monitor public final void notifyAll() wakes up all threads waiting on the object's monitor public String toString() returns a string representation of the object public final void wait() throws InterruptedException. getSuperclass().Main Classes Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. the specified time elaspses Class q q q q q q the Class class was introduced in JDK 1.2 instances of the Class class represent classes and interfaces in a running Java application also represents arrays.lang Package Certification .ca/scjp/pkglang/classes.awt Package The java. The object must implement the Cloneable interface public boolean equals(Object obj) returns true if obj is the same object as the referenced object protected void finalize() throws Throwable called by the garbage collector prior to collecting the object public final Class getClass() returns the runtime class of an object public int hashCode() returns a distinct integer representing a unique object. public fianl void wait(long timeout.lang Package contains classes that are fundamental to the Java programming language it is always implicitly imported the most important classes are Object and Class Object q the Object class is at the root of the class heirarchy.util Package The java. or. all of which are Class instances at runtime objects of the Class class are automatically created as classes are loaded by the JVM.java.html (1 of 2) [15/03/2004 8:47:30 AM] . primitive types and void.lang Package The java.janeg. newInstance() http://www.

Short. Comparable. Byte. and isCompatibleWith() which is used to determine wether a package is comparable to a particular version. Defines the compareTo() method. Runnable. Contains no methods. Integer.2. getAllPackages().html (2 of 2) [15/03/2004 8:47:30 AM] .Java Quick Reference . all the Exception and Error classes. which provide package objects that are known to the class loader. Runtime.java. including Throwable Interfaces q q q Cloneable. tan String and StringBuffer classes provide commonly used operations on character strings System operation classes: ClassLoader. Float. creation of external processes. Long and Double Math class provides commonly used mathematical functions ie cos. SecurityManager. security.Main Classes Other classes q q q q q q Wrapper classes used to represent primitive types as Objects: Boolean. Defines the run() method which is invoked when a thread is activated.ca/scjp/pkglang/classes. Provides methods for obtaining package version information stored in the manifest of jar files. Used to differentiate between objects that are cloneable and non-cloneable.lang Package . Useful methods include: getPackage(). Character.2. and host inquiries ie time of day Package class is new to JDK 1. sine. Wrapper Classes Math Class String Immutability String Class StringBuffer Class Main Classes http://www. Process and System which manage the dynamic loading of classes. Objects implementing this interface can be compared and sorted.janeg. new in JDK 1.

hashCode() and toString() in Object r equals() returns true if the values of the compared objects are the same r hashCode() returns the same hashcode for objects of the same type having the same value r toString() returns the string representation of the objects value all have a public static final TYPE field which is the Class object for that primitive type all have two static fields MIN_VALUE and MAX_VALUE for the minimum and maximum values that can be held by the type The java. Double. Throws a NumberFormatException if the String cannot be converted to a number Note q The java. except Character. Note q The constructors and methods described above do NOT exist for the Void class although it does have the TYPE field.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies q q SCJA Notes SCJD Notes Projects q Favourite Links About Feedback q Void q there is also a wrapper class for Void which cannot be instantiated. Float.java.util Package q The Character class does not have a constructor that takes a String argument all. Integer and Short extend the abstract Number class all are public final ie cannot be extended get around limitations of primitive types allow objects to be created from primitive types all the classes have two constructor forms r a constructor that takes the primitive type and creates an object eg Character(char). Double. These are all abstract methods defined in Number and overridden in each class r public byte byteValue() r public short shortValue() r public int intValue() r public long longValue() r public float floatValue() r public double doubleValue() all the classes override equals().awt Package The java. Long.janeg. have a valueOf(String s) method which is equivalent to new Type(String s) all have a typeValue() method which returns the value of the object as it's primitive type.Wrapper Classes q q q q q q one for each primitive type: Boolean. Float.ca/scjp/pkglang/wrapper. and Short Byte. Character. Integer. Integer(int) r a constructor that converts a String into an object eg Integer("1"). Character q contains two methods for returning the numeric value of a character in the various number systems http://www.lang Package The java.lang Package .html (1 of 2) [15/03/2004 8:47:30 AM] .Wrapper Classes Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package Certification . Byte.Java Quick Reference .

int radix) r public static int getNumber(char ch) and one method to return the character value of a number r public static char forDigit(int digit.Java Quick Reference .html (2 of 2) [15/03/2004 8:47:30 AM] . Byte and Long q q all have parseType methods eg parseInt().ca/scjp/pkglang/wrapper. toOctalString() and toHexString() which take an integer value and convert it to the appropriate String representation Float and Double q q q q both classes have static fields which define POSITIVE_INFINITY. isDefined(). int radix) has two case conversion methods r public static char toLowerCase(char ch) r public static char toUpperCase(char ch) also contains a variety of other methods to test wether a character is of a specific type eg isLetter().janeg.lang Package . isSpaceChar(). etc that take a String and parse it into the appropriate type the Integer and Long classes also have the static methods toBinaryString().java. etc getType() returns an int that defines a character's Unicode type r Integer.Wrapper Classes q q q q public static int digit(char ch. Short. NEGATIVE_INFINITY. and NaN and the following methods to test a value r public boolean isNan() r public static boolean isNaN(type value) r public boolean isInfinite() r public static boolean isInfinite(type value) Float also has a constructor that takes a double value both classes have methods to convert a value into a bit pattern or vice versa r public static int floatToIntBits(float value) r public static float intBitsToFloat(int bits) r public static long doubleToLongBits(double value) r public static double longBitsToDouble(long bits) Wrapper Classes Math Class String Immutability String Class StringBuffer Class Main Classes http://www. parseShort.

type b) r static type min(type a.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes IEEEremainder q q calculates the remainder as defined by IEEE-754 the remainder operator. type b) E: PI: q q q q q q q The java.IEEEremainder( 7. it returns the value as a negative Math.abs(Float.5: -2.abs(Float.abs(-0.0 q Math.MIN_VALUE): -2147483648 ceil() q returns the smallest double value not less than the argument and equal to an integer (counts up) http://www.MIN_VALUE.0): 0.59 Math.141592653589793 contains methods for common mathematical operations ie abs.lang Package Certification .5 0. all methods are static the Math class cannot be instantiated methods involving angles use radians vs degrees and minutes all methods.59): 1234.java.IEEEremainder keeps resulting values y units apart Math.NEGATIVE_INFINITY): Infinity Math.lang Package .5: 2.Java Quick Reference .util Package The java.Math Class Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. except random which takes no arguments the following methods are overloaded to return and handle int.Math Class q contains static constants E and PI 2.5): Math. makes values symmetric around zero ie negative and positive values return corresponding remainders 7 % 2. long and float r static type abs(type a) r static type max(type a.html (1 of 4) [15/03/2004 8:47:30 AM] . etc.0 Math. %.abs(1234.abs(Integer.5 abs() Projects q returns the absolute or positive value of the argument Favourite Links About Feedback Math.lang Package The java.0 -7 % 2.IEEEremainder(-7. 2.718281828459045 3.ca/scjp/pkglang/math. 2. in which case.awt Package The java. sin. round. except round().5): -0.NaN): NaN q EXCEPT if the value is equal to Integer. exp.janeg. return a double all methods take at least one double as an argument.

returns zero if the argument is a negative infinity or less than the MIN_VALUE for the type. negative or positive zero.0 and 0.NaN): min() and max() q q min() returns the smallest of two values max() returns the largest of two values Math.01): Math.ceil(-9.ceil(-0.NaN): floor() q q q q returns the largest double value not greater than the argument and equal to an integer (counts down) if the argument is an integer.5.0 -1.min(Float.0 NaN // counts down (towards zero) // counts down (away from zero) Math.java.min(0.ceil( 9. returns -0 9.floor( 9. 1.Random class 0.POSITIVE_INFINITY)). returns the MAX_VALUE http://www. returns the argument if the argument is between -1.5.01): Math. returns the MIN_VALUE if the argument is a positive infinity or greater than the MAX_VALUE for the type.0.0 if you want to seed the number or generate random numbers in different ranges use the java.0 NaN // counts up (away from zero) // counts up (towards zero) Math.03): Math.03): Math.0 and 1. infinity.5 to the argument and returns the closest int if the argument is not a number.NaN.0 -10.ceil(10): Math.5 Math.5 Math.ceil(Double.0 10.0): -0.janeg.lang Package .min(-1. returns the argument if the argument is between -0 and 0.0 // zeros are not equivalent Math. 1. returns the argument if the argument is NaN.Java Quick Reference .0 -0.ca/scjp/pkglang/math. Float. returns the argument if the argument is NaN or infinity.floor(-0.util.max(-1.floor(-9.floor(10): Math.0 -9.5): -1. returns 0 10.5): 1.random(): round() q q q q q q has two versions r public static long round(double a) r public static int round(float a) only method that does not return a double adds 0.2379468138972043 Math. -0.Math Class q q q if the argument is already an integer.floor(Double.01): Math.0 10.html (2 of 4) [15/03/2004 8:47:30 AM] .01): Math. NaN random() q q returns a pseudo-random positive double number between 0.

returns -0. returns NaN if the result is negative zero.ca/scjp/pkglang/math.rint( 5. ie 2/PI = 90 degrees sin(double a) if the result is NaN or infinity. returns NaN if the result is negative zero. returns NaN if the result is negative zero.round( 1.janeg.49): sqrt() q q returns the positive square root of a number returns NaN if argument is negative 6.708203932499369 NaN Math.0 Math.Math Class Math.html (3 of 4) [15/03/2004 8:47:30 AM] .0 asin(double a) returns a value between -PI/2 and PI/2 if the result is NaN or absolute value is greater than 1.POSITIVE_INFINITY): 9223372036854775807 Math.lang Package .0 Math. returns -0.5): Math. returns -0.rint( 5. favours the even integer 6.5): Math.5): -1 Math.rint(-5.2): Trigometric functions all results are returned in radians there are 2 * PI degrees in a circle.java. returns NaN tan(double a) if the result is NaN or infinity.round(Float.MAX_VALUE is 3.round(Float.0 -6.0 acos(double a) returns a value between 0.0 -5.sqrt(45): Math.Java Quick Reference .0 and PI if the result is NaN or absolute value is greater than 1.5): 2 Math.MAX_VALUE the round method returns Integer.MAX_VALUE rint() q q rounds to the closest integer if integers are equidistant.rint(-5.round(-1.NEGATIVE_INFINITY): -2147483648 Math.0 5.0 cos(double a) if the result is NaN or infinity.NaN): 0 Math.sqrt(-45): pow(double a.pow(2.4028235E38) Note q If the value is Float.MAX_VALUE): 2147483647 (Float. double b) q returns the first argument raised to the power of the second argument 4.round(Double. returns NaN q q http://www.49): Math.round(Float.

returns NaN q if the argument is positive infinity.cos(90): Math.0 or 0.4480736161291701 -1.995200412208242 0.log(0.html (4 of 4) [15/03/2004 8:47:30 AM] . returns negative infinity Math.exp(Float.lang Package . to convert between radians and degrees r double toRadians(double angdeg) r double toDegrees(double angdeg) Math.PI/2): 0.toRadians(90) Math.0): -Infinity q exp() returns e to the power of the argument q if the argument is NaN.302585092994046 Math. returns positive infinity q if the argument is negative infinity.POSITIVE_INFINITY): Math.5596856728972892 1.janeg.NaN): Math.log(10): 2.0 Logarithms q q q q q two functions to handle logs r double log(double a) r double exp(double a) log() returns the natural logarithm of the argument if the argument is less than zero. returns -0. returns positive infinity if the argument is -0.sin(90): Math.java.ca/scjp/pkglang/math.8939966636005579 -0. returns positive zero Math. new in JDK 1.exp(Float.toDegrees(Math.0 Example Code q TestMath.exp(Float. returns NaN if the result is negative zero.0 1.java Wrapper Classes Math Class String Immutability String Class StringBuffer Class Main Classes http://www.NEGATIVE_INFINITY): 148.log(-10): NaN Math.0.acos(-0): Math.5707963267948966 90. double b) converts rectangular co-ordinates to polar co-ordinates q has two additional methods.Math Class atan(double a) returns a value between -PI/2 and PI/2 if the result is NaN.Java Quick Reference .0 q atan2(double a.tan(90): Math.exp(5): Math.4131591025766 NaN Infinity 0.asin(-0): Math. returns NaN if the argument is positive infinity.atan(90): Math.2.5707963267948966 1.

the second assignment of "Goodbye" to String.String Immutability Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback The java.html [15/03/2004 8:47:31 AM] .awt Package The java.lang Package . q in the above example.ca/scjp/pkglang/immutable.lang Package Certification .janeg. str = "Goodbye". what actually happens is that a new string "Goodbye" is created and the object reference of the new string is stored in the variable str q operations that seem to modify a String object actually create new read-only String objects.java. leaving the original object unchanged q the StringBuffer class provides mutable or flexible string handling Also see String literals Main Classes Wrapper Classes Math Class String Immutability String Class StringBuffer Class http://www.String Immutability q String objects are read-only or immutable ie the contents of a String object never change String str = "Hello".lang Package The java.util Package The java.Java Quick Reference .

3) "Returns a canonical representation for the string object. Otherwise.5) example code: q the JLS gives example code using literals in the following classes: r class test r class Other (in the same java file as class test) r class other.intern() is true if and only if s. if the pool already contains a string equal to this String object as determined by the equals(Object) method.String Literals q String literals are enclosed in double quotes "This is a string literal. It follows that for any two strings s and t. String literals or strings that are the values of constant expressions.intern() == t.Java Quick Reference .String Literals Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.util Package The java.html (1 of 3) [15/03/2004 8:47:32 AM] .Language Fundamentals . public String. When the intern method is invoked." Character escape codes can be used in String literals "A line with a carriage return \r" !!! Warning !!! q q You cannot use the character literals \u000a (newline) or \u000d (carriage return) in String literals as they will be interpreted as LineTerminators. this String object is added to the pool and a reference to this String object is returned. A pool of strings.Other (in a different package) http://www. s." A string constant expression occurs when two or more string literals are concatenated "This is " + "a string " + "constant expression. then the string from the pool is returned.10.5) "A line with unicode carriage return character \u000d" q If you use octal values in Strings to represent characters be sure to use a zero prefix (JPL pg33) Note: the zero prefix is not required for octal values in char literals "\0116" "\116" octal value equivalent to escape char \t followed by 6 "\t6" interpreted as letter N Each String literal is a reference to an object of class String.intern() (JSK 1. All literal strings and string-valued constant expressions are interned. not as input characters (JLS §3.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Language Fundamentals .janeg. is maintained privately by the class String. are interned so as to share unique instances.awt Package The java.ca/scjp/lang/strLiteral.lang Package The java.equals(t) is true.10." Output from (JLS § 3. initially empty.

janeg. or by explicitly using the intern() method.Other. a reference to an existing string. (str1 +" Oh my!"). using constant expressions computed at compile time 5.html (2 of 3) [15/03/2004 8:47:32 AM] . "Lions and Tigers and Bears! Oh my!". in different classes in different packages 4. " Oh my!". "Lions and Tigers and Bears!".lang.3 for the java.ca/scjp/lang/strLiteral.intern() hello == ("Hel" + lo) true true true true true false q literal strings will represent the same reference if they are created 1.Java Quick Reference . their references will be different str1 str2 str3 str4 str5 str6 str7 str8 = = = = = = = = "Lions and Tigers and Bears!". in the same class and in the same package 2.hello == hello other. str1 + str5.intern()." In other words. a string literal. q String String String String String String String String Comparison output: str1 == str2 -> true str1 == str3 -> true str1 == str4 -> false str2 == str3 -> true str2 == str4 -> false str3 == str4 -> false str6 == str7 -> false str6 == str8 -> true // // // // // // // // the str2 literal existed ("interned") hold the same reference str4 explicitly created hold the same reference str4 explicitly created str4 explicitly created str7 computed at runtime explicit use of intern() at runtime JSK 1. because the compiler knows the strings original value cannot be changed once it's created it can safely use existing data and avoid cluttering up memory with duplicates.String Literals q the code gives the following output: String variables initialized as: String hello = "Hello" String lo = "lo" (1) (2) (3) (4) (5) (6) q hello == "Hello" Other. str2.String class states: "Strings are constant. new String("Lions and Tigers and Bears!"). Because String objects are immutable they can be shared. String buffers support mutable strings.Language Fundamentals . their values cannot be changed after they are created. http://www. their references will be the same if String objects having the same data are created explicitly with the new operator or their values are computed at runtime.hello == hello hello == ("Hel"+"lo") hello == ("Hel"+lo). in different classes within the same package 3. by explicitly using the intern() method and the resulting string is already in the string pool literal strings will represent different references if they are newly created at runtime (Line 6) Summary q if String objects having the same data are created using a constant expression.

Language Fundamentals .java Traps q using == operator to compare contents of two string reference variables pointing to different String objects Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays Source Methods Primitives String Literals Class Literals http://www.Java Quick Reference .ca/scjp/lang/strLiteral.html (3 of 3) [15/03/2004 8:47:32 AM] .janeg.String Literals Example code q TestStringLiteral.

3): q A package declaration q import declarations q top-level class and interface declarations Package declaration q q q if used. Example Code q TestPkgImport. each of which is optional (JLS §7.java Tips q q an empty source file will compile without error if a .lang Package The java.Source Files Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. the import statement must be the first non-comment statement in the file top-level class and interface declarations q q A top-level class or interface is defined as any class or interface whose declaration is not contained within the body of any other class or interface declaration. you can declare multiple classes and interfaces within a file with the following caveats: r r SCJA Notes SCJD Notes Projects Favourite Links About Feedback The Sun SDK allows one and only one public class or interface within a source code file. (JLS §8 and §9). you can use as many import statements as you want if no package statement appears in the source code file.Language Fundamentals .Java Quick Reference .Source Files A Java source code file or compilation unit has three basic parts.janeg.java extension Non-public classes may have main() methods.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies Language Fundamentals .ca/scjp/lang/source.java file does not contain a public class or interface it can have any name Traps q q q code with package or import declarations given in wrong order more than one package declaration file with more than one public class or interface declaration http://www. it must be the first non-comment statement in the source code file you can not declare more than one syntax: package packageName. The filename must exactly match the name of the public class or interface declared in the file and have the .html (1 of 2) [15/03/2004 8:47:32 AM] . Import declarations q q q if used.util Package The java.awt Package The java. If they have no access modifier (package access) they may still be run from the command-line using the classname. must be the first non-comment statement directly following the package declaration.

java does not match public class name as declared within the file Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays Source Methods Primitives String Literals Class Literals http://www.ca/scjp/lang/source.janeg.Source Files q filename.Language Fundamentals .html (2 of 2) [15/03/2004 8:47:32 AM] .Java Quick Reference .

utils and q q q q q q q q q The fact that they share a common subpackage.1) ie There is no special relationship between the packages: com.....Package Declarations Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.acme. Unnamed packages (JLS §7.tools package would be in: directory.Package Declarations Syntax package packageName.2) q Feedback q q if no package declaration is found...2) if used.....lang Package The java.acme. has no meaning in terms of a types scope....io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Language Fundamentals ..acme...acme.tools // Acme company packages the package naming structure directly maps to a directory structure. acme. com subdirectory..... packages provide a naming context and an organizational structure for Java compilation units package names are hierarchical with component names separated by dots (JPL pg 25) the standard convention for package naming is to use the reversed internet domain name of whoever's creating the package.html [15/03/2004 8:47:33 AM] .2.. For example.sun.Language Fundamentals ..acme subdirectory... if you were developing the Acme company packages your compilation units for the com.Java Quick Reference .util Package The java.java. it does not confer a special relationship (JLS §7.awt Package The java.utils // IBM packages com......tools.ibm. it must be the first statement in the source code file you can not declare more than one the package naming structure is for ease of organization only. For example: com. com..tools the Java compiler uses a combination of the CLASSPATH and package name to locate the source file host systems may store packages in databases (JLS §7. the class or interface is made part of an unnamed package every implementation of Java must provide for at least one unnamed package most systems allow for one unnamed package per directory Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays Source Methods Primitives String Literals Class Literals http://www.4...awt // Sun packages com.ca/scjp/lang/pkg.janeg.

5. import Vector. Without the package import you'd need to code: q q q q q Tips & Traps Mock Exams q Case Studies q java.awt.Vector.Import Declarations Syntax import packageName.awt.5.InterfaceName. in Just Java 2. // single-type-import import packageName. he's a kernel programmer for Sun q http://www.ca/scjp/lang/import. You can create a Button by coding: Button myButton = new Button().util. 4th Edition says it ain't so and my guess is he knows . they can slow down the speed of the compile.ClassName. import java.5) it is legal to import a single-type and a package having the same names (JLS §7.Button myButton = new java.awt Package The java..Button().awt.4) i.lang package is automatically imported in every compilation unit.pest.janeg.html (1 of 2) [15/03/2004 8:47:34 AM] .Button class by using: import java.awt.Button. SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q import java. imported types are available to all classes and interfaces within the same compilation unit (JLS §7. . // no compile error Also see q Sun Tech Tip: Using Import Declarations Tips a single-type import will take precedence over an import-on-demand import-on-demand types do not increase the size of the compiled code ie only the types actually used are added to the code I've read that while import-on-demand adds no overhead to the compiled code.2) the java. it does not have to be specifically imported you can access classes and interfaces from other packages without first importing them but you must use their fully qualified names For example: If you import the java.Java Quick Reference .util Package The java.Import Declarations Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.e.or. // single-type-import the import statement is used to reference classes and interfaces declared in other packages the type-import-on-demand import statement will cause the package to be searched when a type is declared for a class which has not been declared within the source file duplicate type-import-on-demand statements are ignored (JLS §7.*.Language Fundamentals . // type-import-on-demand import packageName.io Package References Miscellaneous Notes Language Fundamentals . Peter van der Linden.lang Package The java. however.awt.*..

Java Quick Reference .janeg.Language Fundamentals .ca/scjp/lang/import.util.html (2 of 2) [15/03/2004 8:47:34 AM] .Import Declarations Traps q q q single-type imports for two classes in different packages but with the same simple name single-type import with the same simple name as a class defined in the source file attempting to import a package vs a type ie import java.* Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.util vs import java.

lang Package The java.1. { } a class must provide a method implementation (execution code) for every method declared in or inherited by the interface if an interface is not provided in the implements clause.Class Declarations Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. extendsClause and implementsClause are all optional.Language Fundamentals .Class Declarations Syntax (JJ pg 137) modifiers class ClassName extendsClause implementsClause { // Class body } The modifiers.ca/scjp/lang/class.2) an Anonymous class cannot have an extends clause (JPL pg74) implementsClause (JJ pg 137) q q identifies interfaces implemented by the class consists of the implements keyword followed by a comma seperated list of the names of the interfaces to be implemented class X implements interfaceA.1) no modifiers are allowed in Anonymous class declarations (JJ pg 147) A class may not be both final and abstract as an abstract class implies extension package access (no access modifier declared) is also referred to as friendly access a compile error occurs if the same modifier appears more than once in a declaration (JLS §8.. interfaceB. the class does not implement the interface even if it provides an implementation for every method declared in the interface q Feedback q Class body (JJ pg 138) q q the class body declares members (field variables and methods). Modifiers public protected private abstract static final strictfp if two or more modifiers are used in a declaration it is customary.Object class a compile error occurs if a final class appears in the extends clause (JLS §8.util Package The java. constructors and initializers class members may also be inner classes or interfaces http://www.lang.awt Package The java.1.1. the class automatically inherits from the java.1. to show them in the order given (JLS 8.1) q q q q q extendsClause (JJ pg 137) q q q q q q consists of the extends keyword followed by the name of the class being extended the extended class is referred to as the parent or superclass multiple extends are illegal ie a class may have only one superclass if no extends clause is used.. .janeg.Java Quick Reference .html (1 of 2) [15/03/2004 8:47:34 AM] . but not required.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Language Fundamentals .

Java Quick Reference .janeg.Language Fundamentals .html (2 of 2) [15/03/2004 8:47:34 AM] .ca/scjp/lang/class.Class Declarations Traps q q class attempting to extend more than one other class class declared both final and abstract Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.

1) public protected private abstract static strictfp Note q top-level interfaces may only be declared public private interface A {} protected interface B{} // compile error // compile error q inner interfaces may be declared private and protected BUT only if they are defined in a class public interface A { private interface B {} protected interface C {} } public class A { private interface B {} protected interface C {} // compile error // compile error // compiles OK // compile OK q q } a compile error occurs if the same modifier appears more than once in an interface declaration (JLS §9.1. Note http://www.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Language Fundamentals .1) extendsClause q consists of the extends keyword followed by a comma separated list of the interfaces being extended.1.html (1 of 2) [15/03/2004 8:47:34 AM] .janeg.Interface Declarations Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. A compile time error occurs if an interface has a simple name the same as any of it's enclosing classes or interfaces (JLS §9.1.1) Modifiers (JLS §9.1.1) every interface is implicitly abstract. the modifier is obsolete and should not be used in new programs (JLS §9.ca/scjp/lang/interface.Java Quick Reference .Interface Declarations Syntax (JJ pg142) modifiers interface InterfaceName extendsClause { // Interface body } The modifiers and extendsClause are optional.awt Package The java.Language Fundamentals .util Package The java.lang Package The java.

. interfaceY.Language Fundamentals . .4) methods cannot be declared strictfp.5) Also see q q Sun Tutorial: Interfaces and packages Tech Tip: Abstract classes vs interfaces Code Examples q q TestInterfaceModifiers. native or synchronized (JLS§9..ca/scjp/lang/interface.janeg.3) methods in an interface are implicitly abstract and public. they can extend more than one interface. they can only extend one class. inner classes and inner interfaces fields in an interface are implicitly static and final ie they MUST be constants (JLS§9. Interfaces are allowed multiple-inheritance.4) member classes declared in an interface are implicitly public and static (JLS§9.Java Quick Reference . {} Interface body q q q q q an interface body may contain constant declarations.Interface Declarations q q Classes are based on single-inheritance. interface InterfaceA extends interfaceX.java TestInterfaceInClass.html (2 of 2) [15/03/2004 8:47:34 AM] .java Traps q q an interface method declared as native or synchronized an interface method declared as static Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www. they CANNOT be static (JLS§9. abstract method declarations.

8. native.8) modifiers ClassName(arguments) throwsClause { // Constructor body } The modifers. arguments.Java Quick Reference .ca/scjp/lang/constructor. // not a constructor // constructor q q Also see Sun Tech Tip: Default Constructors Tips q a constructor body can include a return statement providing no value is returned Traps q subclass with default constructor when the superclass does not have a no-args constructor or it's no-arg constructor has a throws clause http://www. } the default constructor has the same access modifier as the class itself. [Note: all are optional in the sense that your class does NOT have to declare a constructor (see following on default constructors). they are not inherited q if a class constructor is not declared.however.janeg. if you do include a constructor modifiers. synchronized or strictfp (JLS §8. Note A method having the same name as the class is not treated as a constructor public void MyClassName() {} public MyClassName() {} A constructor cannot have a return type.awt Package The java. ClassName. a default constructor is supplied by the compiler modifiers ClassName() { super(). either: public. private or package (no modifier) to prevent a class from being instantiated outside the class declaration you can create a private constructor. final. and throwsClause are optional.html (1 of 2) [15/03/2004 8:47:36 AM] .Language Fundamentals .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Language Fundamentals .lang Package The java. protected. static.] q a constructor can use the access modifiers public.Constructor Declarations Syntax (JLS §8.3) q constructors are not considered class members.Constructor Declarations Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.util Package The java. protected or private or have no access modifier (package access) q a constructor can not use the modifiers abstract. arguments and the throws clause are optional.

ca/scjp/lang/constructor.janeg.Java Quick Reference .html (2 of 2) [15/03/2004 8:47:36 AM] .Constructor Declarations q constructor declared with a return type Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.Language Fundamentals .

(JLS §8.5) q q legal return types: void. return(x). public or protected returnValue (JLS §8. q // legal // illegal q q if a primitive data type is used. or synchronized a static method is referred to as a class method a non-static method is referred to as an instance method the access modifier of an overriding method must provide at least as much access as the method being overridden. any primitive data type. Modifiers q q q q q legal access modifiers: public.3) Original Method Access public protected package Overriding method must be public public or protected package. the method must return a value that is promotable to the declared type if an array type is used.Method Declarations Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. final. the method must return a value of the same array type. } } parameterList q consists of a comma-separated list of parameter declarations myMethod(int a.Language Fundamentals .awt Package The java. an Object reference or Array type if void is used. private or package (none declared) legal special modifiers: abstract. if the returnType is String[][] then the method must return a String[][] array a method can declare a return type without having a return statement in its body class DizzyDean { int pitch() { throw new RuntimeException("90 mph?!"). For example.janeg.ca/scjp/lang/method.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Language Fundamentals .4.Method Declarations Syntax (JJ pg88) modifiers returnValue methodName(parameterList) throwsClause { // Method body } The modifiers and throwsClause are optional. protected.util Package The java.lang Package The java. static.4. boolean flag){} a parameter may also be declared final q http://www.html (1 of 3) [15/03/2004 8:47:36 AM] .6. the method may not use a return statement with an expression return.Java Quick Reference . long c. native.

exY{ // method body } } class classB extends classA { void methodA() throws exX { // can throw less exceptions // method body } } class classC extends classA { void methodA() throws exX.html (2 of 3) [15/03/2004 8:47:36 AM] .4. versus non-native or abstract method declaration: public void close() throws IOException { // Method body } if a method is declared void then the body should not include a return statement that has an q http://www.) for a body.Java Quick Reference . exZ { // method body } } // illegal Method Signature q q A method signature is made up of the method name and parameter list (it does not include the return type) it is illegal for a class to declare two methods with the same signature Method body q q a static method cannot use this or super operators in it's body (static implies a class method unrelated to any specific instance) (JLS §8.5) Example of native and abstract method declarations: public native void close() throws IOException.Method Declarations myMethod(final int i){} throwsClause q q q q q consists of the keyword throws and a comma-separated list of the exceptions that may be thrown identifies all the checked exceptions that may be thrown but not caught by the method the throws clause must include exceptions that may be thrown by another method being invoked by the declared method it is not necessary to throw the predefined exceptions which are subclasses of the Error or RuntimeException classes (JLS §8. Do not use curly braces {}.4.2) a method declared native or abstract has a semi-colon (.(JLS § 8. (JLS §8.4.3.janeg.4.4) a method that overrides another method cannot be declared to throw more checked exceptions than the method being overidden.Language Fundamentals .ca/scjp/lang/method.4) class classA { void methodA() throws exX. public abstract void open() throws IOException. exY.

Language Fundamentals . synchronized.5) public void methodA() { return( 1 + 1 ). native.janeg.4.html (3 of 3) [15/03/2004 8:47:36 AM] . final.Method Declarations expression (JLS §8. } // illegal // legal Also see Understanding that parameters are passed by value and not by reference Code Examples q TestMethods. or strictfp an abstract method declared in a non-abstract class a native or abstract method with a method body method returning a type which is not convertible to the declared return type a void method returning a value a static method referencing this or super Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.java Tips q q any method can throw a Runtime or Error exception without declaring it in the throws clause methods having the same name and parameter types do not have the same signature unless the parameter types are listed in the same order Traps q q q q q q an abstract method also declared private.ca/scjp/lang/method.Java Quick Reference . } public void methodA() { return.

main() Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.java http://www. protected or has no access modifier.lang Package The java.ca/scjp/lang/main. however.main() Syntax public static void main(String[] args) { // method body } entry point for a Java application required by all Java applications (not required in Applets) must be declared public static void void must appear before main() Example: static public void main(String[] args){} // legal public static void main(String[] args){} // legal public void static main(String[] args){} // illegal can also be declared final main() has only one argument: a String array the argument can be declared in many ways and the variable name does not have to be args Example: q q q q q q q References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes q q main( String args[] ) main( String [] args ) main( String[] params ) main( String[] args ) // standard convention the args array is used to access command line arguments Example: java MyApp test this out the args array uses a zero based index therefore args[0] would return "test" in the above example an application can have more than one main() method as every class can have a main() method which main() is used by an application depends on the class started at runtime advantage is that each class can use it's own main() as a testing structure for the class main() is inherited and can be overridden if not declared final SCJD Notes q Projects q Favourite Links About Feedback q q Code compiled with JDK 1.Language Fundamentals .janeg.util Package The java.io Package Language Fundamentals .html (1 of 2) [15/03/2004 8:47:37 AM] . for the purpose of the certification exam the correct method declaration is public static void main(String[] varname) (see discussion at JavaRanch) Code Examples q TestMain.awt Package The java.3 will work ok even it is declared private.Java Quick Reference .

the variable name does not have to be args... can be anything as long as the type is String[] Traps q main() declared other than according to the standard convention Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.janeg.html (2 of 2) [15/03/2004 8:47:37 AM] .Java Quick Reference ..main() Tips q q q q q main() can be declared final main() is inherited and can be overridden if not declared as final args[0] references first command line argument after the application name ( arrays in Java are zero-based) main() can be declared public static void .Language Fundamentals . or static public void ..ca/scjp/lang/main.

4 recommends sticking to one language when writing identifiers as a number of characters look alike in various languages but have seperate Unicode values methods and variables can have the same names. protected.for.Language Fundamentals .firstWordLowercaseButInternalWordsCapitalized() Variable names . they are temporary placeholders which store values and references to data for objects being operated on by the method valid local modifiers: final q q q q q The java. Naming Conventions q q q q q Package names .8 recommends that the dollar sign only be used for identifiers that are mechanically generated (ie within IDE's) JPL pg 5. Example: public int i. volatile local or automatic variables are declared within methods.components Class and Interface names . they store information (data) relating to an object valid field modifiers: public.CaptializedWithInternalWordsCaptialized Method names .Java Quick Reference . final. private long myNumber. method identifiers always take the form methodName() the parantheses allow Java to recognize the identifier as a method vs a variable and therefore distinguish between the two.all.Variable declarations and Identifiers Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. boolean literal. static.awt Package The java.janeg.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q Identifiers q q q q q q an identifier is an unlimited-length sequence of Java letters and Java digits an identifier cannot have the same spelling as a Java keyword.firstWordLowercaseButInternalWordsCaptialized Constants .UPPER_CASE_WITH_UNDERSCORES http://www. protected myVar = 10. private.ca/scjp/lang/identifiers. variables provide named access to data stored in memory variables may be declared as a primitive type or a reference type Java supports two different kinds of variables: field or class variables and local or automatic variables field variables are declared as members of a class. transient.Variable declarations and Identifiers Syntax modifiers Type declarator. or null literal valid identifiers begin with one of the following: r a Unicode letter r the underscore character ( _ ) r a dollar sign ( $ ) JLS §3.lowercase.lang Package The java.util Package Language Fundamentals .html (1 of 2) [15/03/2004 8:47:38 AM] .

Variable declarations and Identifiers Tips q variables can have the same name as a method or a class Traps q q local (automatic) variables declared with a modifier other than final identifier names beginning with a number or # sign Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.html (2 of 2) [15/03/2004 8:47:38 AM] .ca/scjp/lang/identifiers.Java Quick Reference .Language Fundamentals .janeg.

particularly wrapper classes Integer. extends. They cannot be used as identifiers. Boolean. char.janeg. transient. null is a null Literal. Tips q Java keywords are always lowercase. this Exception handling catch. implements. int. try.Java Quick Reference . final.Keywords Keyword type Primitive types Access modifiers Special modifiers Keywords boolean. new. super. import. protected abstract. for. private. while. goto * Note q q const and goto are not used in Java however they are reserved as keywords. true and false are Boolean Literals. you can immeadiately eliminate any capitalized words appearing in a question listing possible keywords Traps q q q main listed as a possible keyword capitalized words listed as possible keywords. void Unused * const. else.Keywords Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. short public.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Language Fundamentals . finally. etc C/C++ keywords listed as possible Java keywords Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www. package. static.awt Package The java. volatile Control flow if. long. default.util Package The java. do. throws Method specific return. switch. case. instanceof. throw. strictfp.ca/scjp/lang/keywords. float. synchronized. byte. break.Language Fundamentals . double. native. continue OOP specific class.html [15/03/2004 8:47:38 AM] . interface.lang Package The java.

Java Quick Reference .0f 0. are automatically initialized to the default values of their declared type class CheckInit { Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback } // field variable static int i.Language Fundamentals .Default values Type boolean byte char short int long float double Object Array Default value false 0 '\u0000' 0 0 0l 0.out.Default Values Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. } Output of CheckInit: Field variable i: Field array ref: Local variable: Local array ref: 0 null 10 0 // // // // default value of int default value for String[] explicit value default value of int[] Timing and duration of variable initializations (JLS §4.println("Field variable i: " + i). whether field or local variables.janeg. static void myMethod(){ int j.lang Package The java.0d null based on Array type Automatic Initialization q q q Field variables (class members) are automatically initialized to default values Local variables (method or constructor variables) are not automatically initialized Arrays. System.println(" Field array ref: " + s[2]). } public static void main(String[] args) { System. System.io Package References Language Fundamentals .html (1 of 3) [15/03/2004 8:47:38 AM] .out. // local variable int[] a = new int[5].ca/scjp/lang/defaults.awt Package The java.println(" Local array ref: " + a[3]).out. // field array reference variable static String[] s = new String[10].3) Variable Type Definition Initialization http://www.out. myMethod(). // local variable array // causes compile error if not explicitly initialized j = 10. System.util Package The java.5.println(" Local variable: " + j).

not declared.janeg. local variables must be explicitly initialized arrays are initialized to the default value of their type when they are created.Language Fundamentals .html (2 of 3) [15/03/2004 8:47:38 AM] . class or interface Automatically initialized to the default value of its type Duration: as long as the class is loaded Instance (Field) Declared within a class Created when a new instance is without the keyword created static Automatically initialized to the default value of its type Duration: for the life of the instance object Array components unnamed variables intialized to the default value of the created when an array array type object is created not Duration: until the array is no longer when declared referenced Method parameters named argument values a new parameter variable is created passed to a method each time the method is invoked initialized with the corresponding argument value from the method call Duration: method execution Constructor parameters named argument values a new parameter variable is created passed to the each time a new instance is created or constructor the constructor is called initialized to the corresponding argument value Duration: construction execution a new exception-handling parameter Exception-handling parameter variables in a catch clause is created each time an exception is caught by a catch clause initialized with the actual object associated with the exception Duration: catch clause execution Local variables declared by local a new local variable is created variable declarations whenever flow of control enters a new block or for statement initialized to whatever value is explicitly set within the block or for statement Duration: execution of the block or for statement Class (Field) Tips q q only field variables are automatically initialized to their types default value. even if they are local variables Traps q an empty string vs null as the default value for a String object Source Methods Package main() Import Identifiers Class Keywords Interface Defaults Constructors Arrays http://www.Java Quick Reference .ca/scjp/lang/defaults.Default Values Declared with the Created when the class or interface is static keyword within a prepared.

janeg.ca/scjp/lang/defaults.Default Values Primitives # Literals char Literal String Literals Class Literals http://www.html (3 of 3) [15/03/2004 8:47:38 AM] .Language Fundamentals .Java Quick Reference .

String s[]. Two-dimensional arrays are arrays of arrays. // illegal declaration the standard convention for declaring arrays is: String[] s. String [] s.4) using a long index value to access an array causes a compile error attempting to access an array with an index less than 0 or greater than the length of the array causes an ArrayIndexOutOfBoundsException to be thrown at runtime (JLS §10.Language Fundamentals . // default values: 0 array references declared as members are initialized to null BUT array references declared in methods are not initialized { q class TestArray http://www.util Package The java. short or char values (as these can be promoted to int) (JLS §10. arrays are automatically initialized with the default value of their type String[] s = new String[100].io Package References Miscellaneous Notes Tips & Traps Mock Exams Language Fundamentals .awt Package The java.html (1 of 3) [15/03/2004 8:47:39 AM] . String[][]s. // default values: null boolean[] b = new boolean[4]. String s []. String [ ] s. String s [] [ ]. // extra white space ignored // extra white space ignored // extra white space ignored q String[] s[]. it creates a variable with a reference to an array array variable declarations must indicate a dimension by using [] Examples of valid array declarations: (JJ pg84) String[]s.ca/scjp/lang/arrays. String s [ ]. // one-dimensional array // two-dimensional array q Case Studies SCJA Notes SCJD Notes Projects Favourite Links q Initializing arrays q q About Feedback q q q all arrays are zero-based arrays must be indexed by int values or byte.Arrays Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. String[][] s.Arrays Array declarations q q q q arrays are Java objects all Java arrays are technically one-dimensional.lang Package The java.janeg. String[] s.4) since arrays are Objects they can be initialized using the new operator when created. // default values: false int[] i = new int[10][10]. String[ ] s.Java Quick Reference . String []s. // extra white space ignored declaring the size of the array with the following notation is illegal String[5] s. declaring an array does not create an array object or allocate space in memory.

i+3). String[] s. // illegal initialization s = { "abc".ca/scjp/lang/arrays.out. the columns curly braces {} may also be used to initialize two dimensional arrays.out. you can initialize the row dimension without initializing the columns but not vice versa int[][] myArray = new int[5][].5. myArray[1] = new int[4]. you can use a variable to set their dimension int arrSize = 100. the second dimension. String[] myArray = new String[arrSize]. // legal Initializing two-dimensional arrays q q the first dimension represents the rows.println("arr1: " + arr1). myArray[2] = new int[5]. for(int i=0. } } q as arrays are allocated at runtime. int[][] twoDimArray = { {1. // illegal initialization int[] array = new int[]. public static void main(String[] args) { myArray[0] = new int[3]. // compile error System. } // end main() private static void fillArray(int row.9} }.janeg. i<3.2.arr).3}. int col) { // initialize # of cols // in each row q q // fill and print the array http://www. {7. the length of the columns can vary class TestTwoDimArrays { // initialize # of rows static int [][] myArray = new int[3][].6}. initialized to 'null' public static void main(String[] args) { int[] arr1.out. // illegal int[][] myArray = new int[][5].8. // member declaration."xyz" }. Note q q Curly braces {} can only be used in array declaration statements.2. {4. "hij"). int[] arr = new int[] {1. you can use curly braces {} as part of an array declaration to initialize the array String[] oneDimArray = { "abc".html (2 of 3) [15/03/2004 8:47:39 AM] . // legal q you can assign an array a null value but you can't create an empty array by using a blank index int[] array = null. System.Java Quick Reference . // reference variable 'arr1' not initialized // compiles ok System. Again they are only valid in array declaration statements.Language Fundamentals .Arrays int[] arr. i++) fillArray(i. "def".3}."def".println().println("arr:" + new TestArray().

value }. i<col. for( int i=0.Language Fundamentals .java Tips q q array index operator [] has highest level of precedence integer variables can be used as array dimension values Traps q q q q q incorrect array declaration statements.out.html (3 of 3) [15/03/2004 8:47:39 AM] . particularly: arrayType[] varName = new arrayType[2].print(myArray[row][i]). i<col. negative values for array index long value for array index array declaration used as an array creation statement Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.Java Quick Reference . i++) myArray[row][i] = i. System. particularly: arrayType [#] varName.Arrays for( int i=0.ca/scjp/lang/arrays.println(). value.out. } } Output of TestTwoDimArrays: 012 0123 01234 Also see Sun Tech Tip: Manipulating Java Arrays Code Examples q TestTwoDimArrays.janeg. incorrect array initialization statements. i++) System. varName = { value.

or NaN are returned (BB pg 123) Variables declared as primitive types are not object references. instead one of the constant values: NEGATIVE_INFINITY. Float.awt Package The java.Java Quick Reference . You CANNOT say: Boolean b = true.223. !!! Warning .0 character signed 16-bit short integer signed 32-bit int integer long Range true or false -(27) to 27-1 0 to 216-1 -(215) to 215-1 -(231) to 231-1 n/a -128 to 127 0 to 65. POSITIVE_INFINITY.483. the wrapper classes have the same names as the primitive types except they begin with a Captial.648 to 0 2. You can say: boolean b = true.775.lang Package The java.ca/scjp/lang/primitives.775.372.0f NEGATIVE_INFINITY signed 32-bit Can also have the value to floating-point NaN (Not a number) POSITIVE_INFINITY NEGATIVE_INFINITY signed 64-bit Can also have the value double to floating-point NaN (Not a number) POSITIVE_INFINITY float q 0.036.223. etc. must use Boolean b = new Boolean(true). -> Boolean is a class.do NOT mix up the Types !!! boolean b. http://www.535 -32.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Language Fundamentals .807 0.html (1 of 2) [15/03/2004 8:47:40 AM] .854.Language Fundamentals .0d q q q q arithmetic with floating-point numbers will never throw an exception. IS NOT THE SAME AS Boolean b.467 -9. Boolean.808 0l to 9.768 to 32.util Package The java.483.036.854.767 Min/Max values Default false 0 \0000 0 signed 64-bit -(263) to 263-1 integer -2.147.Primitive Types Data Bit Size Type boolean n/a signed 8-bit byte integer 16-bit char Unicode 2.janeg.147.372.Primitive Types Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. They are placeholders for storing primitive values (JJ pg29) by default integer values are of type int and floating-point values are of type double float values are single-precision double values are double-precision Wrapper classes q q Favourite Links About Feedback all the primitive types have corresponding wrapper classes which allow you to create objects of type Integer.

Primitive Types Also see Differentiate between reference and primitive types Traps q variables of primitive types handled as Objects Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.ca/scjp/lang/primitives.janeg.Language Fundamentals .html (2 of 2) [15/03/2004 8:47:40 AM] .Java Quick Reference .

Numeric Literals Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.ca/scjp/lang/literals. . a double can be cast as a float double d = 3.html (1 of 2) [15/03/2004 8:47:40 AM] .5F // float value a double constant cannot be assigned to a float variable even if the double is within the float value range. the literal is assumed to be a short or a byte. b = i.213.Java Quick Reference . however.0001 1. byte b. decimal.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links Language Fundamentals . float f. // assumed to be a short short sh = 50000.8e1 // 'e' = exponential at least one digit must be present floating-point constants are double values unless they are suffixed with an f or F if a d or D suffix is used they are double values 10.lang Package The java.janeg.5 // assumed double value 10. // assumed to be a byte short s = 32500. // declared and initialized int // declared byte // causes compile error // compiles q Floating-point literals JPL pg 108 q floating-point numbers are expressed as decimal numbers with an optional decimal point Examples of valid floating-point numbers: 0. (JPL pg 108) int i = 5. or hexidecimal digits decimal base 10 10 octal base 8 010 (8) hex base 16 0xA (16) Integer constants are long if they end in l or L // preceded by a zero // preceded by 0x q q 32l or 32L // capital L recommended use if an int literal is assigned to a short or a byte and it's value is within legal range. // illegal In all other cases you must explicitly cast when assigning an int to a short or byte.Language Fundamentals .Numeric Literals q numeric constants are written using literals Integer literals q Integer constants are strings of octal. // double constant q About Feedback q q q http://www. byte b = 5. b = (byte)i.awt Package The java.10 1.util Package The java.

f = (float)d.Java Quick Reference .html (2 of 2) [15/03/2004 8:47:40 AM] .Language Fundamentals . short or character assigning a double literal to a float Source Methods Primitives Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays String Literals Class Literals http://www.janeg.ca/scjp/lang/literals.Numeric Literals f = d. // compile error // compiles Traps q q assigning a non-integer literal to a byte.

ca/scjp/lang/charLiteral.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes Esc Char q Octal character constants can have three digits or less (\000 through \377) !!! Warning !!! SCJD Notes Projects Favourite Links About Feedback The compiler translates Unicode characters at the beginning of the compile cycle. literally.lang Package The java. Always use the special characters '\n' or '\r' Traps q String literal "c" assigned to char type Package main() # Literals Import Identifiers char Literal Class Keywords Interface Defaults Constructors Arrays Source Methods Primitives String Literals Class Literals http://www.util Package Language Fundamentals .Character Literals q q q the char type represents 16-bit Unicode characters Unicode is a superset of the ASCII character set which allows non-English language characters any Unicode character can be written as a literal using the Escape character (backslash \) and it's hexadecimal representation '\udddd' // where 'dddd' = hex digit (0 .F) single characters are represented within single quotes 'a' // char literal '9' // char literal there are three exceptions that require the use of the Escape character single quote ' \' ' displays as ' double quote ' \" ' displays as " backslash ' \\ ' displays as \ there are certain special characters which can be represented by escape sequences Unicode Char \u000A \u0009 \u0008 \u000D \u000C Definition newline tab backspace return form feed octal value \n \t \b \r \f \ddd q q q The java.Character Literals Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.Java Quick Reference .janeg.html (1 of 2) [15/03/2004 8:47:41 AM] . as 'end-of-line'.awt Package The java. Using the Unicode escape characters \u000A for newline and \u000D for return in a String or comment produces a compile-error as they are interpreted.Language Fundamentals .

Character Literals http://www.html (2 of 2) [15/03/2004 8:47:41 AM] .ca/scjp/lang/charLiteral.Java Quick Reference .Language Fundamentals .janeg.

Java Quick Reference - Language Fundamentals - Class Literals

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

Language Fundamentals - Class Literals
q q

new in JDK 1.1 class literals are created by appending .class to the name of a primitive or reference type System.out.println(int.class); // output: int System.out.println(System.class); // output: java.lang.System you cannot use a variable with .class int i = 5; String s = "Hello"; System.out.println(i.class); System.out.println(s.class); // compile error // compile error

q

Also see
Sun Tech Tip: Using Class Literals

Source Methods Primitives

Package main() # Literals

Import Identifiers char Literal

Class Keywords

Interface Defaults

Constructors Arrays

String Literals Class Literals

http://www.janeg.ca/scjp/lang/classLiteral.html [15/03/2004 8:47:41 AM]

Java Quick Reference - java.lang Package - String Class

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes

The java.lang Package Certification - String Class
q

q q q q

q

q

Strings can be created implicitly by: 1. using a quoted string ie "Hello", or, 2. by using + or += on two String objects to create a new one strings can be created explicitly by using the new operator new String() creates an empty string new String(String value) creates a new string that is a copy of the string object value two basic String methods are r public int length() r public char charAt(int index). Index values range from 0 to length()-1 any String method requiring an index will throw an IndexOutOfBoundsException if 0 > index > length()-1 there are also a number of indexOf() methods which allow you to find the first and last position of a character or substring within a string indexOf(char ch) // first position of 'ch' indexOf(String str) // first position of 'str' lastIndexOf(char ch) // last position of 'ch' lastIndexOf(String str) // last position of 'str' each of the above methods also have overloads that allow a second int start argument which specifies the character position other than 0 from which to begin the search all the methods return -1 if the character or string is not found

q

q

Comparison
q q

q

SCJD Notes
q

Projects
q

characters in strings are compared numerically by their Unicode values equals() method returns true if both string objects are of the same length and have the same sequence of Unicode characters equalsIgnoreCase() can be used to compare strings, ignoring wether a character is lowercase or uppercase compareTo returns an int that is <, =, or > than 0 if one string, based on it's Unicode characters, is less-than, equal to or greater-than another string regions of strings can also be compared

Favourite Links About Feedback public boolean regionMatches(int start, String other, int ostart, int len) public boolean regionMatches(boolean ignoreCase, int start, String other, int ostart, int len) q an area of each string is compared for the number of characters specified by len q simple tests for the beginning and ending of strings can be done using public boolean startsWith(String prefix, int toOffset) public boolean startsWith(String prefix) public boolean endsWith(String suffix) Note

http://www.janeg.ca/scjp/pkglang/string.html (1 of 3) [15/03/2004 8:47:42 AM]

Java Quick Reference - java.lang Package - String Class
q

These methods return true if a comparison is done with an empty string "String".endsWith(""); "String".startsWith(""); // true // true

Comparisons using intern()
q q q

q

two utility methods hashCode() and intern() are available hashCode() returns the same hash value for any two strings having the same contents intern() returns a String that has the same contents as the one it is invoked on AND any two strings having the same content return the same String object allowing comparisons to be done using String references vs string contents using intern() for comparison purposes is equivalent to comparing contents but is much faster

Related strings
q

several methods return new strings that are like the original but with the specified modifications public public public public public public public String String String String String String String concat(String str) replace(char oldChar, char newChar) substring(int beginIndex) substring(int beginIndex, int endIndex) toLowerCase() toUpperCase() trim()

Because all of the above methods return new strings; comparisons such as String s = "String"; // in the pool

if(" String ".trim() == s) System.out.println("Equal"); else System.out.println("Not Equal"); OR if(" String ".trim() == "String") System.out.println("Equal"); else System.out.println("Not Equal"); q produce NOT EQUAL. The string pool is NOT checked for a matching string and as a result the string object references are always different or, not equal (refer to String Literals intern() for more info on the string pool)
q

HOWEVER, if the invoked method does not produce a different string ie the resulting string, after the method invocation, is the same as the original, THEN the original object reference is returned by the method and the results are EQUAL if("String".substring(0,6) == "String") System.out.println("Equal"); else System.out.println("Not Equal"); if("String".replace('t','t') == "String") System.out.println("Equal"); else

http://www.janeg.ca/scjp/pkglang/string.html (2 of 3) [15/03/2004 8:47:42 AM]

Java Quick Reference - java.lang Package - String Class

System.out.println("Not Equal");

Strings and Arrays
q

there are a number of constructors and methods that will convert a character array to a String and vice versa

public String(char[] value) public String(char[] value, int offset, int count) public static String copyValueOf(char[] data) public static String copyValueOf(char[] data, int offset, int count) public void getChars(int srcBegin, intSrcEnd, char[] dst, int dstBegin) public char[] toCharArray() q there are also a number of constructors and methods that convert 8-bit character arrays to and from 16-bit String objects public String(byte bytes[], int offset, int length) public String(byte bytes[]) public byte[] getBytes() public String(byte bytes[], int offset, int length, String enc) public String(byte, bytes[], String enc) public byte[] getBytes(String enc) q where enc is the standard name for the character language encoding ie UTF8 or ISO-Latin-1

Also see
Sun Tech Tip: Interning Strings

Example Code
q q q q q

TestStringOperations.java TestStringCompares.java TestStringModifications.java TestStringMethods.java TestParseLine.java Wrapper Classes Math Class String Immutability String Class StringBuffer Class

Main Classes

http://www.janeg.ca/scjp/pkglang/string.html (3 of 3) [15/03/2004 8:47:42 AM]

Java Quick Reference - java.lang Package - StringBuffer Class

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package

The java.lang Package Certification StringBuffer Class
q q

used to modify or manipulate the contents of a string StringBuffer objects are NOT implicitly created; the following will not compile

StringBuffer sb = "Hello"; StringBuffer sb = { "Hello" }; q you must use the new operator to invoke one of three constructors public StringBuffer() public StringBuffer(int length) public StringBuffer(String str) every StringBuffer has an initial capacity (length) of 16 characters if the internal buffer overflows it is automatically made larger however it is more efficient to specify the capacity only once, there are three methods available to manage capacity

q q

q

The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback String s = ""; s = s + "a" + "b"; q is treated, by the compiler, as something similar to String s = ""; s = new StringBuffer("").append("a").append("b").toString(); q the StringBuffer class does not inherit from String q to use a StringBuffer object as a parameter to a method requiring a String, use the StringBuffer toString() method. For example, to print the result of a StringBuffer object manipulation StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb.toString() ); q StringBuffer has overloaded append() and insert() methods to convert any type, including Object and character arrays, to a String; both methods return the original StringBuffer object q the reverse() method returns the original StringBuffer object with the characters in reverse order q you can access and modify specific characters or a range of characters public char charAt(int index) public void setCharAt(int index, char ch) public StringBuffer(int capacity) public synchronized void ensureCapacity(int minimum) public int capacity() public int length() public void setLength(int newLength) q the String methods which return a new object ie concat(), replace(), etc actually use StringBuffer behind the scenes to make the modifications and then returns the final String using toString(). For example, the following code (JJ pg 208)

http://www.janeg.ca/scjp/pkglang/stringBuffer.html (1 of 2) [15/03/2004 8:47:44 AM]

Java Quick Reference - java.lang Package - StringBuffer Class

public StringBuffer replace(int start, int end, String str) public StringBuffer deleteCharAt(int index) public StringBuffer delete(int start, int end) Note: the subString() method returns a String public String subString(int start) public String subString(int start, int end) there are no methods to remove part of a buffer; you need to create a character array and build a new buffer with the portion of the array you're interested in; this can be done using

q

public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

Example Code
q

TestStringBuffer.java Wrapper Classes Math Class String Immutability String Class StringBuffer Class

Main Classes

http://www.janeg.ca/scjp/pkglang/stringBuffer.html (2 of 2) [15/03/2004 8:47:44 AM]

Java Quick Reference - Threads - Thread Overview

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects

Threads - Overview
q q q q q q

q

q q

q q

q q

q

q q q

on an operating system a running program is known as a process a single process can have seperate runnable tasks called threads a thread is a single sequential flow of control within a process a thread is also referred to as a lightweight process with a single-processor CPU, only one thread is executing at any given time the CPU quickly switches between active threads giving the illusion that they are all executing at the same time (logical concurrency) on multi-processor systems several threads are actually executing at the same time (physical concurrency) multi-programming occurs when multiple programs or processes are executed multi-threading occurs when concurrency exists amoung threads running in a single process (also referred to as multi-tasking) Java provides support for multi-threading as a part of the language support centers on the: r java.lang.Thread class r java.lang.Runnable interface r java.lang.Object methods wait(), notify(), and notifyAll r synchronized keyword every Java program has at least one thread which is executed when main() is invoked all user-level threads are explicitly constructed and started from the main thread or by a thread originally started from main() when the last user thread completes any daemon threads are stopped and the application stops a thread's default daemon status is the same as that of thread creating it you can check the daemon status using isDaemon() you can set the daemon status using setDaemon(). You cannot change a thread's status after it has been started main() daemon status is false if you want all your threads to quit when main() completes you can set their status to daemon using setDaemon(true) there are two basic ways to create and run threads 1. by subclassing the Thread class 2. by implementing the Runnable interface

q q

q

Favourite Links About Feedback

Also see
q q q q q

Sun Tutorial on Threads IBM Redbook: Java Thin-Client Programming - Introduction to Threads SunTech Tip: Why Use Threads? Beware the daemons Exploring Java, Chapter 6, Threads

http://www.janeg.ca/scjp/threads/overview.html (1 of 2) [15/03/2004 8:47:46 AM]

Java Quick Reference - Threads - Thread Overview

Example Code
q

Source code to check daemon status of main() Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify(), notifyAll()

Overview Execution Thread Mechanics

http://www.janeg.ca/scjp/threads/overview.html (2 of 2) [15/03/2004 8:47:46 AM]

out.c = c.lang Package The java.janeg. i++) { System.lang. } q } to actually start the thread running you must invoke its start() method BasicThread bt = new BasicThread('!'). BasicThread(char c) { this. bt.html (1 of 3) [15/03/2004 8:47:47 AM] . i++) { http://www. } } if the above code is added and the threads started you see something like: q q q q q !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!* !*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!**** *********************************************** q the output is intermingled because the threads are running concurrently and are interleaved q you can alter thread processing with program control mechanisms q one way is to use the sleep() method which is defined in the Thread class q the sleep() method stops the execution of a thread for a given number of milliseconds q it also throws an InterruptedException so you need to wrap it in a try-catch block q adding sleep() to the run method can alter the threads execution Note q the sleep() method uses a timed wait() but does not tie up the current object's lock (for information on locks see Synchronization) New run() method: public void run() { for(int i=0.The Thread Class q the easiest way to create a thread is by subclassing java.ca/scjp/threads/threadClass. BasicThread bt1 = new BasicThread('*').start(). the start() method allocates system resources required for a thread.start(). i<100.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads .print(c).awt Package The java. bt1.Threads .Java Quick Reference . i<100. schedules the thread to run and invokes the run() method the above code will execute but nothing will happen if you want your thread to do something you need to override the run() method the run() method is actually defined in the Runnable interface which the class Thread implements public void run() { for(int i=0.The Thread Class Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.Thread class BasicThread extends Thread { char c.util Package The java.

html (2 of 3) [15/03/2004 8:47:47 AM] . if a thread is created without a name.janeg.Threads .random() * 10)).print(c).java http://www. 0 Thread-0 0 Thread-1 1 Thread-0 1 Thread-1 2 Thread-0 2 Thread-1 3 Thread-0 3 Thread-1 4 Thread-1 4 Thread-0 DONE! Thread-0 DONE! Thread-1 q q ThreadGroup q q q q you can group threads using the ThreadGroup class this allows multiple threads to be handled as one unit ie for setting priority.java Traffic Simulation: Traffic.The Thread Class System.Java Quick Reference .println("Interrupted"). etc threads in the same group can access information about other threads in the group but not about the parent thread or threads in other groups a ThreadGroup can have both daemon and nondaemon threads Example Code q q q q q BasicThread.java and SetOfLights. } } } Example output: *!*!!*!*!**!!!*!!*!***!*!!***!*!*!*!*!!!!***!!*!* !!*!**!*!!*!**!*!**!!*!**!!*!!*!*!**!*!***!!!!*!* !!*!**!*!*!*!*!*!*!*!!*!*!*!!!*!*!!!*!*!!*!*!*!*! !*!**!*!*!**!**!!*!***!!!****!*!!****!*!**!!**!!! **** q you can give a thread a name by creating it with a String argument Thread t = new Thread("Thread1").java Java Is Hot: Thread1.java PrimeNumbers Applet: Ex1.out. where n is an integer the following is output from TwoThreadsTest which creates two SimpleThread's and displays their automatically generated names using the getName() method of the Thread class.out. try{ sleep((int)(Math.java Bouncing Ball Applet: UpDown. one is automatically generated in the form Thread-n. destroying.ca/scjp/threads/threadClass. } catch( InterruptedException e ) { System.

janeg.Java Quick Reference .html (3 of 3) [15/03/2004 8:47:47 AM] . notifyAll() http://www.ca/scjp/threads/threadClass.Threads .The Thread Class Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify().

not on a per-invocation basis Java uses re-entrant locks ie a thread cannot lock on itself class Reentrant { http://www.this) { // body } q q q q q q Locking Feedback q q q q q locking follows a built-in acquire-release protocol controlled by the synchronized keyword a lock is acquired on entry to a synchronized method or block and released on exit.awt Package The java.Thread Synchronization q q q q Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About q every instance of class Object and its subclass's has a lock primitive data type fields (Scalar fields) can only be locked via their enclosing class fields cannot be marked as synchronized however they can be declared volatile which orders the way they can be used or you can write synchronized accessor methods array objects can be synchronized BUT their elements cannot.Threads .util Package The java.janeg. even if the exit is the result of an exception you cannot forget to release a lock locks operate on a per thread basis. IT IS NOT AUTOMATICALLY INHERITED when subclasses override superclass methods methods in Interfaces CANNOT be declared synchronized constructors CANNOT be declared synchronized however they can contain synchronized blocks synchronized methods in subclasses use the same locks as their superclasses synchronization of an Inner Class is independent on it's outer class a non-static inner class method can lock it's containing class by using a synchronized block synchronized(OuterClass.Thread Synchronization Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Threads .ca/scjp/threads/synchronization.Java Quick Reference . nor can their elements be declared volatile Class instances are Objects and can be synchronized via static synchronized methods Synchronized blocks q allow you to execute synchronized code that locks an object without requiring you to invoke a synchronized method synchronized( expr ) { // 'expr' must evaluate to an Object } Synchronized methods q declaring a method as synchronized ie synchronized void f() is equivalent to void f() { synchronized(this) { // body of method } } the synchronized keyword is NOT considered part of a method's signature.lang Package The java.html (1 of 2) [15/03/2004 8:47:47 AM] .

in a()"). notifyAll() Overview Execution Thread Mechanics http://www. System.class) { // body } the static lock on a class is not related to any other class including it's superclasses a lock on a static method has no effect on any instances of that class (JPL pg 185) you cannot effectively protect static fields in a superclass by adding a new static synchronized method in a subclass.println("here } } q { I am.out.out.janeg. { I am. another thread may acquire it BUT there is no guarantee as to WHICH thread will acquire the lock next Class fields and methods q q q q locking an object does not automatically protect access to static fields protecting static fields requires a synchronized static block or method static synchronized statements obtain a lock on the Class vs an instance of the class a synchronized instance method can obtain a lock on the class synchronized(ClassName. Result: deadlock as Java does allow reentrant locks. q q q q in the above code. It then calls synchronized method b() which also needs to acquire a lock on it's own object if Java did not allow a thread to reacquire it's own lock method b() would be unable to proceed until method a() completed and released the lock. it DOES NOT prevent unsynchronized methods from accessing the object once a thread releases a lock.println("here } public synchronized void b() System. an explicit block synchronization is the preferred way nor should you use synchronized(getClass()). and method a() would be unable to complete until method b() completed. when executed.Thread Synchronization public synchronized void a() b().html (2 of 2) [15/03/2004 8:47:47 AM] . this locks the actual Class which might be different from the class in which the static fields are declared q q q q Example Code q Source code for reentrant example Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify(). in b()"). the synchronized method a().Java Quick Reference . obtains a lock on it's own object.ca/scjp/threads/synchronization. the code compiles and runs without a problem the locking protocol is only followed for synchronized methods.Threads .

// start RunBasicThread objects as threads new Thread(bt).c = c.ca/scjp/threads/runnable.awt Package The java. RunBasicThread(char c) { this.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads . use Runnable. try{ Thread.start() the Clock applet is an example of an Applet (based on the Sun Thread tutorial) using the Runnable interface: When to implement Runnable vs subclassing Thread q Whenever your class has to extend another class. } catch( InterruptedException e ) { System.out.lang Package The java. new Thread(bt1).random() * 10)).html (1 of 2) [15/03/2004 8:47:48 AM] .sleep() and you have to pass your runnable object to the thread when it is created ie new Thread(bt).Threads . i<100.util Package The java. } } } public static void main(String[] args) { RunBasicThread bt = new RunBasicThread('!').Java Quick Reference .out.The Runnable Interface q q q the Runnable interface declares a single method: run() you can execute a Runnable object in its own thread by passing it to a Thread constructor here's the BasicThread class modified to use the Runnable interface class RunBasicThread implements Runnable{ char c. } } q q q the most significant code revisions are shown in red note that you can still make use of the methods declared in the Thread class but you now have to use a qualified name ie Thread. i++) { System.janeg.The Runnable Interface Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.start().println("Interrupted Exception caught"). } // override run() method in interface public void run() { for(int i=0. RunBasicThread bt1 = new RunBasicThread('*').sleep((int)(Math.print(c).start(). This is particularly true when using Applets Example Code q q Click Applet Bouncing Ball applet: UpDown_1 http://www.

ca/scjp/threads/runnable.Java Quick Reference .The Runnable Interface q q PrimeNumbers applet: Ex1_a Java Is Hot: Thread2 Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify().html (2 of 2) [15/03/2004 8:47:48 AM] .janeg.Threads . notifyAll() Overview Execution Thread Mechanics http://www.

When the thread actually runs is determined by the scheduler Not Runnable a thread is not runnable when r it's sleep() method is invoked r it's wait() method is invoked r it is blocked on I/O ie waiting on system resources to perform an input or output operation the thread becomes runnable again when a specific condition has been met based on the action which put it in the not runnable state r when the number of milliseconds called in sleep() have elapsed r when the condition it is waiting on has changed and it receives a notify() or notifyAll() message r when the required system resources are made available and the I/O completes Dead a thread enters the dead state when it's run() method completes. The start() method allocates system resources.Thread States q q each thread has a life-cycle all it's own during it's life-cycle it can exist in a number of states r New r Runnable r Not Runnable r Dead Note q These states are those used in the Sun Java Thread tutorial. New a new thread is an empty Thread object.Threads . Other references may use 'ready'. 'waiting' or other terminology to describe the Runnable and Non-runnable states. and calls the threads's run() method.janeg. no system resources have been allocated as yet.ca/scjp/threads/state.util Package The java. schedules the thread. an interrupt does not kill a thread the destroy() method kills a thread dead but does not release any of it's object locks Life Cycle of a Thread from Sun Thread Tutorial q a thread can bounce between runnable and not runnable states as a result of either http://www.Java Quick Reference .html (1 of 2) [15/03/2004 8:47:50 AM] .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads . Calling any thread method other than start() causes an IllegalThreadStateException Runnable a thread enters the Runnable state after the start() method is invoked.awt Package The java.lang Package The java.Thread States Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.

Java Quick Reference .Thread States 1. or 2.ca/scjp/threads/state.Threads . notifyAll() http://www.html (2 of 2) [15/03/2004 8:47:50 AM] .janeg. programmer control Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify(). scheduling.

[ 1] MIN_PRIORITY 2. Time slicing In preemptive scheduling the highest priority thread continues to run until it dies. it may stop executing as there may be another thread with a higher-priority (BB pg 259) Actual Scheduling depends on the OS q Mock Exams Case Studies SCJA Notes q q SCJD Notes q Projects Favourite Links About Feedback q q q the above act as a guide to scheduling however the actual implementation depends on the Operating System most operating systems use one of two scheduling methods 1. it takes the priority of the thread which created it you can check a threads priority using getPriority() you can change a threads priority using setPriority() if you change the priority on an executing thread to a lesser priority.Thread Scheduling q q q q q execution of multiple threads in some order on a single CPU system is called scheduling Java uses fixed-priority scheduling algorithms to decide which thread to execute the thread with the highest priority runs first if another thread with a higher priority is started. Preemptive scheduling 2.html (1 of 2) [15/03/2004 8:47:51 AM] . at which point the scheduler decides wether to return to the thread or schedule a different thread (method used by Win95/NT) DO NOT rely on thread priority as a guarantee that the highest priority thread will always be running. event-driven http://www. or is preempted by a thread of higher priority In time slicing a thread runs for a specific time and then enters the runnable state.janeg.Thread Scheduling Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. Java makes the lower priority thread wait if more than one thread exists with the same priority. [10] MAX_PRIORITY the default thread priority is NORM_PRIORITY when a thread is created.awt Package The java. the operating system has the final say priorities are used as guides to efficiency priority manipulations CANNOT be used as a substitute for locking (see synchronization) General Conventions for setting priorities (CPJ pg 16) q following represent the general conventions for setting thread priorities based on the type of activity the thread is involved in Range ----10 7-9 Use ---------------------------Crisis management Interactive. waits.util Package The java. Java quickly switches between them in round-robin fashion BUT only if the operating system uses time-slicing (see below) Priorities q q q q q q q it's possible to assign a thread priority the Thread class contains three integer priority constants 1.lang Package The java. [ 5] NORM_PRIORITY 3.io Package References Miscellaneous Notes Tips & Traps Threads .ca/scjp/threads/scheduling.Java Quick Reference .Threads .

ca/scjp/threads/scheduling.Threads .html (2 of 2) [15/03/2004 8:47:51 AM] .janeg.Java Quick Reference .Thread Scheduling 4-6 2-3 1 Overview Execution Thread Mechanics IO Background computation Run only if nothing else can Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify(). notifyAll() http://www.

Ending a Thread q q a thread normally ends when it's execution completes there are other methods of stopping it.janeg.lang Package The java. the methods wait() and sleep() will throw an InterruptedException join() q q q one thread can wait for another to complete using the join() method invoking join() guarantees that the method will not return until the threads run() method has completed join() will also take a milliseconds argument which will cause it to wait until the thread completes for the designated time period destroy() q q destroy() kills a thread dead without releasing any of it's locks which could leave other threads blocked forever it's use should be avoided stop() q q q q you can force a thread to end by calling stop() which in turn throws the Error ThreadDeath you can also throw ThreadDeath yourself ThreadDeath SHOULD NOT BE CAUGHT! NOTE: stop() is a deprecated method and should not be used!!! suspend() and resume() q both methods are deprecated and should not be used!! setDaemon(true) q if you want your thread to stop executing when main() completes. some of which should not be used interrupt() q q q q q interrupting a thread tells it that you want it to pay attention it does not force the thread to halt although it will wake up a sleeping thread isInterrupted checks to see if a thread is in an interrupted state the static method interrupted can be used to clear a thread's interrupted state if a thread is waiting or sleeping and the thread is interrupted.ca/scjp/threads/ending.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads .Threads .awt Package The java.util Package The java.Ending a Thread Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. set it's daemon status to true using setDaemon(true) yeild() q q q Java does not time-slice ie it will not preempt a currently executing thread to allow another thread of the same priority to run the operating system may use time-slicing but you should not rely on time-slicing when creating threads a well behaved thread will use the yield() method to voluntarily yield to the CPU. giving it a http://www.Java Quick Reference .html (1 of 2) [15/03/2004 8:47:51 AM] .

janeg. notifyAll() http://www. if no threads of the same priority are available. Note: lower priority threads are ignored.ca/scjp/threads/ending.Threads .html (2 of 2) [15/03/2004 8:47:51 AM] . the yield() method only hints to the JVM that if there are other runnable threads the scheduler should run one in place of the current thread. execution of the yielding thread continues. The JVM may interpret this hint any way it likes ie how the yield is handled is dependent on the JVM implementation for the operating system Also see Sun Tech Tip: Handling Interrupted Exceptions Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify().Java Quick Reference .Ending a Thread q q q chance to run another thread of the same priority.

Thread Execution Alive or Dead? q q q q q q the Thread class includes an isAlive() method which returns true if a thread has been started and not stopped a thread stops when its run() method finishes executing the isAlive() method returns false if the thread is new or dead there is no way to detect if a thread is not alive because it was never started or because it is dead there is also no way to detect if a live thread is Runnable or Not Runnable neither can a thread identify which thread started it Why a thread might not be executing (BB pg 270) q the thread does not have the highest priority and can't get CPU time Example: LowPriority the thread has been put to sleep via sleep() method Example: Sleeping there is more than one thread with the same priority and the JVM is switching between the threads Example: SamePriority the thread's wait() method has been invoked Example: Waiting the thread's yield() method has been invoked Example: Yielding the suspend() method has been invoked (this is a deprecated method and should no longer be used) q q q q q Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify().awt Package The java.ca/scjp/threads/execute.lang Package The java.Java Quick Reference .janeg.util Package The java.Thread Execution Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.html (1 of 2) [15/03/2004 8:47:52 AM] .Threads .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads . notifyAll() http://www.

Thread Execution http://www.html (2 of 2) [15/03/2004 8:47:52 AM] .janeg.Java Quick Reference .ca/scjp/threads/execute.Threads .

a thread may obtain multiple locks which must be paired with matching unlocks only one thread at a time can hold a lock on an object a thread is not permitted to unlock a lock it doesn't own a thread can only release it's lock after it has performed a store q q q q q q q q q q q q q q q q q q q Special case: double and long variables q q double and long variables are handled as two 32-bit variables if the variables are not declared volatile and if they are being used by two or more threads the http://www. guaranteeing the shared value will be loaded from main memory as a thread executes. the thread obtains a lock on the object and flushes its working copy of the object 2.html (1 of 2) [15/03/2004 8:47:54 AM] .util Package The java. a thread obtains a lock and flushes its working memory. actions by the thread and main memory must occur in a specific order 1. main memory writes the value passed by the threads store action back to the master copy 4.ca/scjp/threads/locking.awt Package The java. passing it to it's excuatable engine 3. the thread stores the new value.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads .janeg.Thread Locking Protocols Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. each program has an area of main memory where it stores it's classes. passing it back to main memory 3. the thread assigns the resulting value back to it's working copy 4. the thread releases it's lock on the object every read action by main memory must be followed by a load action in the thread every store action in the thread must be followed by a write action in main memory the read and write actions in main must be executed in the order they were performed in the thread every use action in a thread must be followed by an assign action however an assign does not necessarily have to be proceeded by a use all use and assign actions must occur in the order dictated by the threads executable code assign must follow a load before a store can occur or another load can occur every lock action by a thread MUST be paired with an unlock as Java allows re-entrant locks.Threads .Java Quick Reference .lang Package The java. I've included it because I found it useful in helping me to understand how thread locks or monitors actually worked. main memory reads the objects value from it's master copy 1. arrays and variables the main memory has a master copy of every variable and contains one lock for each object this main memory area is accessible by all the programs threads threads can only communicate thru the shared main memory each thread has a working memory where it keeps copies of the values of variables it uses or assigns to access a shared variable. it operates on its working copies when a synchronized block or method is entered. the thread uses it's working copy of the object.Thread Locking Protocols Note q This information is not required for the Certification exam. the thread loads the value passed by the main memorys read operation 2.

value is assigned a literal..showValue(value).janeg. assuming value will not be changed while the method is running q however. if you have other threads that can change value then you should declare it as volatile q this will stop the compiler from in-lining the code and force the value to be reread each time the loop iterates Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify().showValue() does not make any changes to value the compiler would in-line the code. if display. under normal conditions.Threads .) { display.ca/scjp/threads/locking. forcing the thread to reread the value every time the variable is accessed int value = 5.Java Quick Reference .html (2 of 2) [15/03/2004 8:47:54 AM] . for(.Thread Locking Protocols final result may be a combination of both thread actions volatile q declaring a thread volatile prevents the compiler from optimizing and in-lining the code. // wait one second } q in the above example. Thread.sleep(1000). notifyAll() http://www.

with one thread reading from the file while another thread writes to the file this is an example of a producer/consumer relationship Race conditions q q q race conditions occur when multiple.html (1 of 3) [15/03/2004 8:47:55 AM] . as in the following code: public class CubbyHole { private int contents.synchronized keyword Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java. public int get() { return contents. If the CubbyHole class is unsynchronized.janeg.ca/scjp/threads/synchronized.util Package The java. } public synchronized void put(int value) { contents = value. and a Consumer class which respectively write and read integers from a CubbyHole class.synchronized kewyord q q threads often need to share a common resource ie a file.Threads . } } Example output from an unsynchronized Producer/Consumer Consumer #1 got: 0 Producer #1 put: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Producer #1 put: 1 Producer #1 put: 2 Producer #1 put: 3 Producer #1 put: 4 Producer #1 put: 5 Producer #1 put: 6 Producer #1 put: 7 Producer #1 put: 8 Producer #1 put: 9 q results are unpredictable. a number may be read before a number has been produced or multiple numbers may be produced with only one or two being read q adding synchronization ensures that a number is first produced. then read in the correct order http://www.Java Quick Reference . asynchronously executing threads access the same object returning unexpected (wrong) results they can be avoided by synchronizing the methods which access the shared resource the Sun Thread tutorial has an example which uses a Producer class.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads .awt Package The java.

return contents.janeg. notifyAll(). available = true. } } q q the keyword synchronized is added to the method declarations the Object methods wait() and notifyAll() are used to communicate between executing threads Output after code is synchronized Producer Consumer Producer Consumer 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 #1 #1 #1 #1 put: got: put: got: put: got: put: got: put: got: put: got: put: got: put: got: put: got: put: got: 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 Source for synchronized version Other examples using synchronized q An example of using synchronized methods and object locks Thread3 http://www. private boolean available = false.Java Quick Reference .Threads .ca/scjp/threads/synchronized. public synchronized int get() { while (available == false) { try { wait(). } catch (InterruptedException e) { } } contents = value. } public synchronized void put(int value) { while (available == true) { try { wait(). } catch (InterruptedException e) { } } available = false. notifyAll().html (2 of 3) [15/03/2004 8:47:55 AM] .synchronized keyword public class CubbyHole { private int contents.

notifyAll() http://www.ca/scjp/threads/synchronized. Also see Sun Tech Tip: Using Synchronized Statements Acquire multiple locks in a fixed.Java Quick Reference . global order to avoid deadlock Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify(). Counter.synchronized keyword q q q An example using a synchronized statement on a common object Thread4 An example of synchronizing access to variables Account An example of a museum which uses Walkmen radios for tours: WalkmanHire uses Museum.html (3 of 3) [15/03/2004 8:47:55 AM] .Threads .janeg. and Visitors classes.

IllegalMonitorStateException .lang Package The java. The interrupted status of the current thread is cleared Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify(). int nanos) the timeout is measured in milliseconds nanos is measured in nanoseconds wait() can only invoked by the thread that own's the lock on the object when wait() is called.ca/scjp/threads/wait.util Package The java. the thread becomes re-available to the Thread scheduler and competes for a lock on the object once it regains the lock on the object.awt Package The java. the thread becomes disabled for scheduling and lies dormant until one of four things occur: 1. allowing another thread to run the wait() method is defined in the Object class wait() can only be invoked from within synchronized code it should always be wrapped in a try block as it throws IOExceptions there are actually three wait() methods 1. wait() 2. another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread 2. another thread interrupts this thread 4.if the current thread does not own the object's lock 3.janeg.Threads .if the timeout value passed is invalid 2.io Package References Threads . wait(long timeout.html (1 of 2) [15/03/2004 8:47:58 AM] . InterruptedException . another thread invokes the notifyAll() method for this object 3. everything resumes as if no suspension had occurred if the thread was interrupted by another thread. wait(long timeout) 3.wait() method q q q q q q q q q q Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q the wait() method causes a thread to release the lock it is holding on an object.Java Quick Reference .if another thread interrupts the current thread.wait() method Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. IllegalArgumentException . the specified wait() time elapses when one of the above occurs. notifyAll() http://www. an InterruptedException is thrown BUT not until after the thread regains it's lock on the object Throws q the wait() method throws three exceptions 1.

Threads .Java Quick Reference .ca/scjp/threads/wait.html (2 of 2) [15/03/2004 8:47:58 AM] .wait() method http://www.janeg.

notify() and notifyAll() methods q q q q q q q the notify() and notifyAll() methods are defined in the Object class they can only be used within synchronized code notify() wakes up a single thread which is waiting on the object's lock if there is more than one thread waiting.ca/scjp/threads/notify. earlier notifies are irrelevant Overview Execution Thread Mechanics Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify().Java Quick Reference .awt Package The java. the scheduler decides which one will run if there are no waiting threads.notify() and notifyAll() methods Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. the notifys are forgotten only notifications that occur after a thread has moved to wait state will effect it.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Threads . the choice is arbitrary ie there is no way to specify which waiting thread should be re-awakened notifyAll() wakes up ALL waiting threads.lang Package The java.html (1 of 2) [15/03/2004 8:47:59 AM] .util Package The java.Threads . notifyAll() http://www.janeg.

janeg.notify() and notifyAll() methods http://www.html (2 of 2) [15/03/2004 8:47:59 AM] .Threads .Java Quick Reference .ca/scjp/threads/notify.

awt Package The java. A full release occurs even if the lock is re-entrantly held due to the thread having nested synchronized calls r when the thread resumes (ie wait state ends) the lock status is fully restored timed waits() r r r Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q if a timed wait() has not been notified before it's time is up.Thread mechanics Wait Sets (CPJ pg 184) q q q q q just as every object has a lock it also has a wait set that is manipulated using wait(). otherwise. the thread is blocked r the JVM places the thread in the wait set associated with the target object r the lock for the target is released but all other locks held by the thread are retained. notify(). the thread resumes from the point of it's wait notifyAll() works the same as notify() except all waiting threads are removed from the target wait set and allowed to compete for the lock only one thread can obtain the lock so they continue one at a time q Thread. notifyAll() and Thread.Threads .lang Package The java. scheduling and timer granularities notify() the following happens when notify() is invoked q the JVM arbitrarily chooses a thread.Java Quick Reference .interrupt objects having locks and wait sets are referred to as monitors any object can act as a monitor each object's wait set is maintained internally by the JVM and holds threads blocked by wait until a corresponding notify is received or the waits are otherwise released the methods wait(). from the target's wait set q the thread must re-obtain it's synchronized lock on the target object. the method exits immeadiately and throws an InterruptedException.Thread mechanics Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.html (1 of 2) [15/03/2004 8:47:59 AM] .interrupt q q if a thread suspended in wait is invoked. It will always be blocked at least until the thread calling notify() releases it's lock or if some other thread obtains the lock first q once the lock is obtained. if one exists.util Package The java.io Package References Miscellaneous Notes Tips & Traps Threads . an InterruptedException is thrown if an interrupt and notify occur together there is NO guarantee as to which will take http://www. the same notify mechanics apply except that after re-acquiring the lock. it releases automatically there is no way to tell if a wait has returned due to notification or timeout the thread may resume at any arbitrary time after it has timed out based on thread contention. notify() and notifyAll() can only be invoked when the synchronized lock is held on their target wait() the following happens when wait() is invoked r if the current thread has been interrupted.ca/scjp/threads/mechanics.janeg.

janeg.Threads .Java Quick Reference .ca/scjp/threads/mechanics.html (2 of 2) [15/03/2004 8:47:59 AM] .Thread mechanics precedence Example Code q Using wait() and notify() to control access to a shared resource Thread5 Thread Class Synchronization Runnable Interface Locking Protocols Thread States synchronized keyword Scheduling wait() Ending a Thread notify(). notifyAll() Overview Execution Thread Mechanics http://www.

Encapsulation Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading.getTitle() ). Runtime Types and Object Orientation .ca/scjp/overload/encapsulation.println(" Title: " + b1. } } q q In the example code. its behaviour.println(b1).out. they can only be accessed by their gettor and settor methods any attempt to directly set or get the variables produces a compile error http://www. its interface q a tightly encapsulated object hides all it's variables and provides public accessor methods ie the only way you can use the object is by invoking it's public methods "Hiding data behind methods so that it is inaccessible to other objects is the fundamental basis of data encapsulation. b1.lang Package The java.html (1 of 2) [15/03/2004 8:48:03 AM] . maintainablity q q Modularity q because the object encapsulates all it's variables and the methods needed to make it work. it is a self-contained entity that can be maintained independently of other objects Maintainability q because the object hides it's implementation details behind a well-defined interface.println(b1. Runtime Types and Object Orientation . b1. Overriding.util Package The java. b1.setTitle("The Java Programming Language: Second Edition"). the instance variables title and author are private.title = "Java Programming Language".title.out.author = "Ken Arnold and James Gosling"." (JPL pg. // must use accessor methods b1. Overriding.12) q encapsulation has two main benefits: (VA pg44) 1. // // b1.author). an object is encapsulated when its variables and methods are combined into a single component q encapsulation also involves access to an object. System.awt Package The java.setAuthor("Ken Arnold and James Gosling").out.Encapsulation objects have both state (details about itself) and behaviour (what it can do) a software object maintains information about its state in variables q what an object can do. // System.Overloading. System.Java Quick Reference .getAuthor() ).out. System.janeg. is implemented with methods q in Object-oriented programming (OOPs). the details can be changed without affecting other parts of the program Example class TestBook{ public static void main(String[] args) { Book b1 = new Book().println("Author: " + b1. modularity 2.

Overloading.java isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Encapsulation Polymorphism Initialization Top-level Classes Static Nested Local Classes Classes http://www.Java Quick Reference .html (2 of 2) [15/03/2004 8:48:03 AM] . Runtime Types and Object Orientation .janeg.ca/scjp/overload/encapsulation.Encapsulation Example Code q TestBook. Overriding.

have the same return type as as a superclass method 5. 4.PrintStream class public void print(boolean b) public void print(char c) public void print(char[] s) public void print(float f) public void print(double d) public void print(int i) public void print(long l) public void print(Object obj) public void print(String s) q the actual method called depends on the object being passed to the method q Java uses late-binding to support polymorphism. and. which means the decision as to which of the many methods should be used is deferred until runtime Overriding methods q q q late-binding also supports overriding overriding allows a subclass to re-define a method it inherits from it's superclass overriding methods: 1.Java Quick Reference . 3. it is not inherited and overriding is not an issue http://www.Polymorphism q q q polymorphism translates from Greek as many forms ( poly . Overriding.lang Package The java. appear in the same class or a subclass 2. protected.many morph . Overriding.janeg. appear in subclasses 2. can have different return types an example of an overloaded method is print() in the java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading.awt Package The java.Polymorphism Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. or public s if the superclass methods is private. Runtime Types and Object Orientation .util Package The java. have the same parameter list as a superclass method 4.Overloading.ca/scjp/overload/poly. the overriding method may be protected or public s if the superclass method is package.forms) in OOP's it refers to the propensity of objects to react differently to the same method (VA pg 110) method overloading is the primary way polymorphism is implemented in Java Overloading methods q q overloaded methods: 1. have different parameter lists. the access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method s if the superclass method is public. have the same name as a superclass method 3. Runtime Types and Object Orientation .io. the overriding method must be public s if the superclass method is protected.html (1 of 3) [15/03/2004 8:48:04 AM] . the overriding method may be packagage. have the same name but.

LB_1 lb3 = lb2. } } q q if you create an LB_2 object and assign it to an LB_1 object reference.java isA/hasA Overloading Overriding Field Variables Encapsulation Polymorphism http://www.ca/scjp/overload/poly. the LB_2 retValue(String s) method is used.Java Quick Reference . // compiles ok System. } overriding is allowed as LBException1 thrown in the subclass is itself a subclass of the exception LBException thrown in the superclass method q Side effect of late-binding q it is Java's use of late-binding which allows you to declare an object as one type at compile-time but executes based on the actual type at runtime class LB_1 { public String retValue(String s) { return "In LB_1 with " + s.retValue("Today")). not the LB_1 method LB_2 lb2 = new LB_2(). } } class LB_2 extends LB_1 { public String retValue(String s) { return "In LB_2 with " + s.janeg. Output: In LB_2 with Today Example Code q TestLateBinding. Runtime Types and Object Orientation .html (2 of 3) [15/03/2004 8:48:04 AM] .Overloading.out. the throws clause of the overriding method may only include exceptions that can be thrown by the superclass method. if you invoke the retValue(String s) method on the LB_1 reference. } In subclass: public void testEx() throws LBException1 { throw new LBException1().Polymorphism 6. it will compile ok at runtime. Overriding. including it's subclasses class LBException extends Exception {} class LBException1 extends LBException {} In superclass: public void testEx() throws LBException { throw new LBException().println(lb3.

ca/scjp/overload/poly.Overloading. Overriding.Polymorphism Initialization Top-level Classes Inner Classes Static Nested Local Classes Classes Anonymous Classes http://www.janeg.Java Quick Reference .html (3 of 3) [15/03/2004 8:48:04 AM] . Runtime Types and Object Orientation .

Square and Point. (JJ pg 138) public class Circle extends Shape { // a circle is a shape Point center.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading.html (1 of 2) [15/03/2004 8:48:05 AM] . Circle. 2. Points have an (x. // a circle has a radius } Define a class hierarchy for the following classes (BB pg14): 1. } // an employee // has an id. Overriding.0.y) location and a radius. } } // retired is a status class Retired extends EmployeeStatus { int years.is A vs Has A Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.ca/scjp/overload/isAhasA. (BB pg17) class Point { int x. and // a status q abstract class EmployeeStatus extends Employee { abstract double salary(). Circles have an (x. A Retired employee class that maintains an employee number. Runtime Types and Object Orientation . public class Employee { long id. String status. Overriding. 3. Runtime Types and Object Orientation .Overloading. int y.y) location and a length. and // a y-location q http://www. double salary(){ return hrs * 60.lang Package The java. double salary() { return 0. the number of years worked.Java Quick Reference . } // fulltime is a status class FullTime extends EmployeeStatus { double hrs. Squares have an (x. // a circle has a point double radius.util Package The java.janeg.is A vs Has A q q is a defines a direct relationship between a superclass and a subclass has a identifies a relationship in which one object contains another object (defined by field variables) Examples q A circle is a shape that has a center point and a radius.awt Package The java. } } Create classes for 2DShape. // a point // has an x-location. and calculates it's own pay using a salary() method. hours worked per week and calculates it's own pay using a salary() method. An Employee class that maintains an employee number. A Full-time employee class that maintains an employee number.y) location.

} // all 2DShapes // have a point class Circle extends 2DShape { double radius.Java Quick Reference .html (2 of 2) [15/03/2004 8:48:05 AM] . } class Square extends 2DShape { double length. } Encapsulation Polymorphism Initialization Top-level Classes isA/hasA Inner Classes // a circle is a 2DShape // and has a radius // a circle is a 2DShape // and has length Overloading Overriding Field Variables Anonymous Classes Static Nested Local Classes Classes http://www.ca/scjp/overload/isAhasA.Overloading.janeg. Overriding.is A vs Has A } class 2DShape { Point p. Runtime Types and Object Orientation .

ca/scjp/overload/overloadingMethods. int i). Overriding.html (1 of 2) [15/03/2004 8:48:05 AM] .test(100. q this code will compile fine if any variables passed to the methods are easily recognizable as either an int or a long Sub sb = new Sub(). 3000). Sub class test(long j.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading. long j) in Super class q however.Overloading Methods q q q overloaded methods can have the same name but must have different parameter lists parameter lists are considered different if the order of the arguments are different a subclass method can overload a superclass method Examples (based on BB pg 194-5) q the following code shows the method test(int i. // second arg is defined as L(ong). Overriding. watch for ambiguous references that can cause compile errors.Overloading Methods Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. Output: uses test(int i. 3000 can also be an int sb. Ouput: compile-error: reference to test() is ambiguous !!! Warning !!! q When analyzing code.test(100.lang Package The java. long j) in a Super class. long j). int i) in a Sub class Super class: test(int i.janeg. if the compiler cannot differentiate between a long and an int a compiler error will occur Sub sb = new Sub(). 3000L). Overloading constructors q you can overload constructors within the same class class SuperCtor { SuperCtor(){} SuperCtor(int i) {} // compiles ok } you can't overload them in subclasses as they must have the same name as the class (ie they would have to have the superclass name and would therefore not be constructors in the subclass) q http://www. no ambiguity sb. Runtime Types and Object Orientation .util Package The java.Java Quick Reference .Overloading. Runtime Types and Object Orientation .awt Package The java. // causes compile-error. and method test(long j.

janeg.java TestOverloadCtor.java isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Encapsulation Polymorphism Initialization Top-level Classes Static Nested Local Classes Classes http://www.Overloading.Java Quick Reference . Overriding.ca/scjp/overload/overloadingMethods.html (2 of 2) [15/03/2004 8:48:05 AM] . Runtime Types and Object Orientation .Overloading Methods class SuperCtor { SuperCtor(){} } class SubCtor() { SuperCtor(){} } // compile-error Also see q q Polymorphism Sun Tech Tip: Overload Resolution Example Code q q TestOverload.

Overriding.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading.awt Package The java. turning a concrete method into an abstract one at that point in the type tree. Runtime Types and Object Orientation .janeg.util Package The java.test()").println("In Super. name.out.Overriding Methods Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. and parameter list and can only throw exceptions of the same class/subclass as those declared in the original method class Super { void test() { System.html (1 of 2) [15/03/2004 8:48:07 AM] . overloads test() q Only accessible non-static methods can be overridden q static methods can be hidden ie you can declare a static method in the subclass with the same signature as a static method in the superclass. the superclass field can only be accessed using super or the superclasses type a subclass can override methods in it's superclass and change it's implementation it must have the same return type. The superclass method will not be accessible from a subclass reference q any class can override methods from its superclass to declare them abstract. the Subclass method will called from the superclass http://www. Useful when a class's default implementation is invalid for part of the class hierarchy (JPL pg 77) Overriding with constructors q q q you cannot override a constructor in a superclass as they are not inherited you cannot override a constructor in the same class as they would both have the same signatures. original has package access private void test() {} protected void test() {} // compiles ok public void test() {} // compiles ok q you can have multiple overloaded methods in a class but only one overriding method In Sub class: void test() {} public void test() {} // overrides test() in Super // compile-error: test() already declared // different access modifiers not part of // method signature for naming purposes void test(String str) {}// compiles ok.Overriding Methods q q q fields cannot be overridden but they can be hidden ie if you declare a field in a subclass with the same name as one in the superclass. get an 'already declared' compile-error if you're instantiating a Subclass object and if the Superclass constructor calls a method that is overridden in the Subclass. Overriding.ca/scjp/overload/overridingMethods.Overloading.test()").out.Java Quick Reference . Runtime Types and Object Orientation .println("In Sub.lang Package The java. } } q cannot have weaker access rights than the original method In Sub class: // compile-error. } } class Sub extends Super { void test() { // overrides test() in Super System.

Overriding Methods constructor -.Java Quick Reference .println("In Sub constructor").out.java isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Encapsulation Polymorphism Initialization Top-level Classes Static Nested Local Classes Classes http://www. } void test() { // overrides test() in Super System.test() Sub Constructor Also see q Polymorphism Example Code q TestOverride. } } Output In In In if Sub sb = new Sub() is invoked: Super Constructor Sub.ca/scjp/overload/overridingMethods. Overriding. Runtime Types and Object Orientation .janeg. } void test() { System.test()").out.test()").println("In Super. test().println("In Sub. } } class Sub extends Super { Sub() { System.println("In Super constructor").Overloading.out.out.html (2 of 2) [15/03/2004 8:48:07 AM] .NOT the one in the superclass class Super { Super(){ System.

awt Package The java.Overloading.io Package References Miscellaneous Notes Overloading.lang Package The java. Sub is a subclass of Super with it's own field 'i' and method test() 3. Overriding.Field Variables Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.i 10 Example Code q TestFields. q q q q Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q Creating a Super objref and pointing it to Sub obj // subclass obj stored in super reference Super sp1 = sb. Super has a field 'i' and a method test() which displays 'i' 2. BUT if you access the field variable directly.janeg.Field Variables q q q q consider the following scenario: 1. The actual object type is used at runtime. // field variable in Sub object test() in Sub uses i: 20. Runtime Types and Object Orientation .0 // field variable in Super object sp1.java Encapsulation Polymorphism Initialization Top-level Classes isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Static Nested Local Classes Classes http://www.util Package The java.Java Quick Reference . the variable for the declared type is returned. the default value of it's field variable is displayed the Subclass variables are initialized the Subclass constructor is called When an overridden method is called from a superclass constructor both the Subclass method and field variables are used Which methods and variables are used when an object reference for a Superclass is created and the assigned object is a Subclass type? Answer: both the Subclass methods and variables are used. Runtime Types and Object Orientation . The declared type is only valid at compile-time. Overriding.ca/scjp/overload/fields. ie not through a method. Super calls the test() method in it's constructor Which value for 'i' will be displayed when a Sub object is instantiated? Answer: the default value of the field 'i' in Sub the subclass object is instantiated as follows: the Superclass constructor is called the Subclass method test() is used as the Subclass has not been fully initialized.html [15/03/2004 8:48:07 AM] .

Java Quick Reference . if the constructor begins with this().lang Package The java. y' in Point 2.println(cp. memory is allocated for all the instance variables in the class and instance variables in all of it's superclasses 2. the instance variables are set to their default values 3. invoke the constructor recursively following the same five steps 3. first memory is allocated for the fields 'color' in ColoredPoint and then for the fields 'x.html (1 of 3) [15/03/2004 8:48:08 AM] . arguments for the constructor are assigned to newly created parameter variables 2. execute the instance initializers and instance variables for this class 5. explicitly or implicitly.awt Package The java.Initialization Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. next. 7. } class Test { public static void main(String[] args) { ColoredPoint cp = new ColoredPoint().color). if the constructor does not begin with this(). the no-arg ColoredPoint constructor is invoked.Overloading. } } class ColoredPoint extends Point { int color = 0xFF00FF.out. Runtime Types and Object Orientation .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading. initializer for instance variables of ColoredPoint http://www.ca/scjp/overload/initialization. the constructor used in the creation expression is called according to the following: 1. the Point ctor does not begin with this() so an invocation is made to the no-arg ctor for Object (Point's superclass) 5. As none exists. This is done implicitly ie the compiler added the default no-arg ctor at compile time 4. Overriding.5) 1. all the instance initializers for Point's instance variables are invoked and the body of the Point constructor is executed. Overriding.Initialization Steps that occur when a new instance is created (JLS§12. y. execute the remainder of the constructor body Example: class Point { int x. the fields are initialized to their default values 3. } } When the new instance of ColoredPoint is created: 1.janeg. System. y = 1. These are processed recursively following the same 5 steps. any instance variable initializers of Object are invoked and the body of the no-arg ctor is executed 6. Runtime Types and Object Orientation . the corresponding superclass constructor using super(). the superclasses no-arg constructor is invoked. Point() { x = 1. then invoke.util Package The java. 4.

ca/scjp/overload/initialization.5.janeg. Runtime Types and Object Orientation . has a no-arg ctor New ClassF instance with no-args ClassA() ctor ClassE() ctor ClassF() ctor // ClassF extends ClassE // which extends ClassA // invoked with different ctor New ClassF instance with parameter ClassA() ctor // no-arg ctor's of superclasses implicitly ClassE() ctor // called ClassF(String name) ctor q if the constructor being invoked explicitly calls a superclass constructor then the superclass no-arg constructor is not implicitly invoked ClassC extends ClassB which extends ClassA // (no call to super(str) in ClassC(String str)) New ClassC instance created ClassA() ctor // implicitly called ClassB() ctor // implicitly called Hello // (ClassC(String str) explicitly calls super(str)) New ClassC instance created ClassA() ctor // implicitly called In ClassB // explicit call. not 'Sub' the initialization of an Interface does not implicitly cause initialization of it's SuperInterfaces JLS §8. JLS §12. Overriding.Overloading.1 q q q before a class is initialized it's direct superclass must be initialized but interfaces implemented by the class need not be initialized a reference to a class field only causes the initialization of it's class even if it is referred to by a subclass ie if 'taxi' is a static field in 'Super' class and is referenced by 'Sub.1 q a constructor beginning with this() or super() can not use any class or superclass instance variables as an argument to a parameter No argument constructor q ONLY the no-arg constructor is called implicitly when new instances are created // extends ClassA. only 'Super' is initialized.8.Initialization are invoked and the body of the ctor is executed.taxi'.html (2 of 3) [15/03/2004 8:48:08 AM] . // NO implicit call to ClassB() Hello !!! Remember !!! http://www.Java Quick Reference . has no ctor New ClassB instance ClassA() ctor New ClassD instance ClassA() ctor ClassD() ctor // extends ClassA.4.

There are NO IMPLICIT invocations to any other constructors Also see Sun Tech Tip: Constructor and Initialization Ordering Example Code q q TestCtor. If NO constructor exists.Initialization 1.ca/scjp/overload/initialization. The no-arg constructor of all superclasses in the hierarchy will be invoked and executed BEFORE the type constructor is executed UNLESS the type constructor explicitly calls another superclass constructor 3.janeg.java isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Encapsulation Polymorphism Initialization Top-level Classes Static Nested Local Classes Classes http://www. Overriding.Java Quick Reference . Runtime Types and Object Orientation .java TestCtor_1. the compiler will add a default no-arg constructor 2.Overloading.html (3 of 3) [15/03/2004 8:48:08 AM] .

Runtime Types and Object Orientation .Java Quick Reference .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading.java Encapsulation Polymorphism Initialization Top-level Classes isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Static Nested Local Classes Classes http://www. Overriding.html [15/03/2004 8:48:09 AM] .Top-level Classes Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.awt Package The java. final or abstract or it can have no access modifier which defaults to package or friendly access public class TestTopLevel {} final class FinalClass {} abstract class AbstractClass {} class PackageClass {} you can have more than one top-level class in a source code file.ca/scjp/overload/top. you can have only one public class in a source code file q Example Code q TestTopLevel. Runtime Types and Object Orientation . Overriding.Top-level Classes q q a top-level class can be declared public.util Package The java.janeg.lang Package The java.Overloading. however.

class and Outer$Inner.janeg.Java Quick Reference . inner classes may be declared public. (JLS§8. defaulting the class access to package q or.fldname http://www.1.1. create one from within the outer class constructor class Outer { Outer() { new Inner().2) inner classes may inherit static members (JLS§8. interfaces are never inner (JLS§8. See Static Inner Classes q q q q q inner classes may not declare static initializers or static members unless they are compile time constants ie static final var = value.Inner Classes q Inner classes are non-static classes defined within other classes (JLS§8.Inner i2 = new Outer().awt Package The java.1.Overloading.this. create the inner class directly: Outer. Or. use Outer. protected.new Inner().class the Inner class type is: Outer. Overriding.Inner i1 = o1.util Package The java. } } q inner classes may have no declared access modifier. Runtime Types and Object Orientation .new Inner(). abstract. Overriding. Runtime Types and Object Orientation . Or. static or final class Outer { public class PublicInner{} protected class ProtectedInner {} private class PrivateInner{} abstract class AbstractInner {} final class FinalInner {} static class StaticInner {} } q each instance of a non-static inner class is associated with an instance of their outer class q static inner classes are a special case.Inner Classes Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.1.2) you cannot declare an interface as a member of an inner class. Then create an Inner class object: Outer. private.lang Package The java.2) class Outer { class Inner {} // class definition within the // the body of class Outer q q q } the compiled class files for the above are: Outer.ca/scjp/overload/inner.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading.Inner instances of inner classes can be created in a number of ways Create an Outer class object: Outer o1 = new Outer().html (1 of 2) [15/03/2004 8:48:11 AM] .2) the inner class can access the variables and methods declared in the outer class to refer to a field or method in the outer class instance from within the inner class.

Inner Classes Example Code q TestInner. Overriding.janeg.ca/scjp/overload/inner.java isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Encapsulation Polymorphism Initialization Top-level Classes Static Nested Local Classes Classes http://www.Overloading.html (2 of 2) [15/03/2004 8:48:11 AM] .Java Quick Reference . Runtime Types and Object Orientation .

Overriding. } } q q they are not associated with an instance of their outer class ie you can create an Inner class object from within the Outer class using new Inner(). } static class Inner { static int value = 100.Static Nested Classes q q a static inner class behaves like any top-level class except that its name and accessibility are defined by its enclosing class (JPL pg 50) ie use new Outer. you do not need to create an Outer class object first as is required with non-static inner classes static inner classes can directly access static fields of the outer class but must use an instance of the outer class to access the outer classes instance fields Example Code q TestStaticInnerClass.janeg. Overriding.Overloading.Inner() when calling from another class formally called top-level nested classes (JPL pg 50) Note There is alot of confusion over the terminology involving 'static nested classes'.awt Package The java.java Favourite Links About Feedback Encapsulation Polymorphism Initialization Top-level Classes isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Static Nested Local Classes Classes http://www.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Overloading.Static Nested Classes Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. Second Edition by Ken Arnold and James Gosling.value.lang Package The java. Runtime Types and Object Orientation . They are not inner classes! While the formal name. is 'top-level nested'.Java Quick Reference . Joshua Bloch. Runtime Types and Object Orientation . it is a bit of an oxymoron.ca/scjp/overload/static.util Package The java.html [15/03/2004 8:48:11 AM] . prefers the term 'static member class' which provides a clearer sense of how such classes are utilized. author of Effective Java. as stated in the Java Programming Language. class Outer { public static void main(String[] args) { int x = Inner.

Local Classes Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads Overloading. May be declared final they may access static and non-static members of the enclosing class they may only access final variables or parameters of the enclosing code block q q q The java.java Encapsulation Polymorphism Initialization Top-level Classes isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Static Nested Local Classes Classes http://www.new Local(). won't work they may not be declared private. Runtime Types and Object Orientation .Overloading. Runtime Types and Object Orientation .ca/scjp/overload/local. Overriding.Local Classes q may be declared within a block of code class Outer { void display() { class Local { // body of Local class } } } the compiled name of the above Local class is: Outer$1$Local. public.awt Package The java. they cannot be instantiated outside of the code block in which they are declared by using the class as a reference ie new Outer. or static.Java Quick Reference . protected.class local inner classes are not class members and are not tied to an instance of the enclosing class as they are not class members. Overriding.janeg.lang Package The java.html [15/03/2004 8:48:12 AM] .util Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q q Example Code q TestLocalInner.

lang Package The java. Overriding.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Overloading. Runtime Types and Object Orientation .Anonymous Classes Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. Runtime Types and Object Orientation . extends or implements are allowed if any parameters are passed the superclass must have a corresponding constructor Anonymous classes do not have constructors of their own as constructors always take the name of the class and Anonymous classes have no name even though you cannot use an extends clause.awt Package The java. Overriding. that method is used until the class is unloaded they are most often used to implement an event listener interface or extend an adapter class Example Code q q TestAnonymous.Anonymous Classes q q q q q q anonymous classes are classes which have no name they are declared and defined using the name of the class or interface they extend ie new Enumeration() no modifiers.java TestAnonymousClass.ca/scjp/overload/anonymous.Overloading.Java Quick Reference .html [15/03/2004 8:48:13 AM] .java Encapsulation Polymorphism Initialization Top-level Classes isA/hasA Inner Classes Overloading Overriding Field Variables Anonymous Classes Static Nested Local Classes Classes http://www.janeg. See example code q q Once you create an anonymous class and override a method.util Package The java. you can extend the superclass by overriding methods you cannot 'overload' or 'add' new methods.

util Package The java.janeg.lang Package Garbage Collection Certification . informs selected objects that they should release any non-memory resources 3. you can only tell when an object becomes eligible for garbage collection you can request garbage collection by calling one of Runtime.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q the Java garbage collector consists of three basic activities: 1.gc() // no guarantee gc will run System.runFinalization() Also see q q q Garbage Collection in Java Sun Tech Tip: Reference Objects Sun Tech Tip: Performance tip: Garbage Collection and setting to null Traps q q a question that targets a specific object for garbage collection (can't be done) a question that presumes to force the gc to run (can only suggest it run) Behaviour Eligibility finalize() http://www.Behaviour q q q q q q q q The java.Behaviour Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.ca/scjp/gc/behaviour. monitors program objects to determine when they are no longer required 2. destroys objects and reclaims their memory resources the gc operates as a seperate asynchronous background thread that tracks all program objects an object ceases to be needed by a program when it is no longer reachable an object is reachable if a reference to the object exists in any variables of any executing code an object is subject to garbage collection when it can no longer be reached but it is not necessarily garbage collected immeadiately there are no guarantees as to when the gc will reclaim an object or the order in which objects are reclaimed there is no way to tell if and when an object will be collected.html [15/03/2004 8:48:15 AM] .runFinalization() System.Garbage Collection .getRuntime().Java Quick Reference .gc() // no guarantee gc will run you can also request that the finalize() method be run for objects deemed eligible for collection but which have not yet had their finalization code run Runtime.

Java Quick Reference - Garbage Collection - Eligibility

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

Garbage Collection Certification - Eligibility
q q

variables and objects are eligible for garbage collection when they become unreachable following summarizes the normal duration of a declared object or variable Duration as long as the class is loaded for the life of the instance as long as the array is referenced until method execution ends until the constructor execution ends until the catch clause completes execution in a for-loop, until the loop completes in a code-block, until the code block completes

Declaration static field instance field Array components Method parameters Constructor parameters Exception handling parameters Local variables
q

any variable set to null automatically becomes eligible for garbage collection gc and the String pool

You may run across mock exam questions or discussions that state Strings created as part of the String pool are never garbage collected. This may well be true as garbage collection is implementation dependent. The certification exam will not contain questions that rely on specific implementations of any JVM; for exam purposes it is unlikely you will see any gc questions involving pooled Strings. Just remember once an Object reference has been set to null it is eligible for garbage collection.

Behaviour

Eligibility

finalize()

http://www.janeg.ca/scjp/gc/eligible.html [15/03/2004 8:48:15 AM]

Java Quick Reference - Garbage Collection - finalize()

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes

Garbage Collection Certification - finalize()
Syntax (JDK 1.3)
protected void finalize() throws Throwable {} every class inherits the finalize() method from java.lang.Object the method is called by the garbage collector when it determines no more references to the object exist the Object finalize method performs no actions but it may be overridden by any class normally it should be overridden to clean-up non-Java resources ie closing a file if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize() (JPL pg 47-48). This is a saftey measure to ensure you do not inadvertently miss closing a resource used by the objects calling class

q q

q q q

protected void finalize() throws Throwable { try { close(); // close open files } finally { super.finalize(); } } q any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored q finalize() is never run more than once on any object

Also see
q q

Object finalization and cleanup - JavaWorld, June 1998 Sun Tech Tip: Using finally versus finalize to guarantee quick resource cleanup

Example Code
q

TestGC.java

Projects Favourite Links About Feedback

Behaviour

Eligibility

finalize()

http://www.janeg.ca/scjp/gc/finalize.html [15/03/2004 8:48:16 AM]

Java Quick Reference - Declarations and Access Control - Access Modifiers

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

Declarations and Access Control - Access Modifiers
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 Field variables Description A Class or Interface may be accessed from outside its package. Constructors, Inner Classes, Methods and Field variables may be accessed from wherever their class is accessed.

protected

May be accessed by other classes in the same package or from any subclasses of the class in which they are declared.

private

May be accessed only from within the class in which they are declared.

no modifier

May only be accessed from within the package in which they are declared.

Access Modifiers

Special Modifiers

this and super

Scope

Inheritance

Access Control

http://www.janeg.ca/scjp/declarations/access.html [15/03/2004 8:48:17 AM]

Java Quick Reference - Declarations and Access Control - Special Modifiers

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

Declarations and Access Control - Special Modifiers
Modifier abstract Used with Classes Interfaces Methods Description Declares a Class or Method that is incomplete. All Interfaces are implicitly abstract so the modifier is redundant. A Class which has an abstract Method must be declared abstract. Classes Indicates a definition is complete and cannot be changed. Field variables Classes may not be extended. Methods Field variables may not be modified once a value is assigned. Method Methods cannot be overridden. parameters Required for Method parameters and Local variables if they Local variables are to be used by an Inner Class. Note: A Class may not be both final and abstract. Methods Indicates a platform-specific method written in another language. Note: a method cannot be both native and abstract Initializers Indicates an initializer, method or variable belongs to a class Methods vs an instance (object) of the class. Variables Static initializers are processed once, when the class is loaded. Static methods are used to access static variables. They may not be used to access non-static variables unless they specify an instance of the class. Methods Indicates a method acquires a lock on an object before it executes. Used to control access to objects shared by multiple threads. Variables Indicates the variable is not part of the permanent state of an object and may not be serialized (written to a stream). Variables Indicates a variable may be changed by more than one thread. Each thread has it's own copy of a working variable. Volatile ensures the variable is compared to the master copy each time it is accessed.

final

native

static

synchronized

transient volatile

Access Modifiers

Special Modifiers

this and super

Scope

Inheritance

Access Control

http://www.janeg.ca/scjp/declarations/special.html [15/03/2004 8:48:17 AM]

Java Quick Reference - Declarations and Access Control - this and super

Declarations and Access Control - this and super
this (JLS §15.8.3)
q q q q q q q q

this is an Object-Oriented Programming (OOP) operator it is used to refer to the current instance of an object it can be used in the body of a class constructor to refer to the object being created it can be used in the body of an instance method or initializer to refer to the object whose method is being executed it cannot be used in a static method or initializer most commonly appears in constructors can be used to explicitly call another constructor when used in a constructor it must be the first statment in the constructors body

class Super { int x; int y; Super(){ System.out.println("Super object being created."); } Super( int x, int y ) { this(); // call no-arg constructor this.x = x; this.y = y; } }

super
q q q q

super is an Object-Oriented Programming (OOP) operator used to call a constructor declared in a classes superclass commonly used in constructors and to access hidden fields or invoke overridden methods in the superclass if used in a constructor, must be the first statment in constructor body Remember
q

Constructors are not inherited!

class Subclass extends Super { int w; Subclass(){ this(0,0,0); }

// call 3-param constructor

Subclass( int x, int y ) { this(x,y,0); // call 3-param constructor

http://www.janeg.ca/scjp/declarations/this.html (1 of 3) [15/03/2004 8:48:18 AM]

Java Quick Reference - Declarations and Access Control - this and super

} Subclass( int x, int y, int w ) { super(x,y); // call superclass constructor this.w = w; } } Remember You cannot use this() and super() in the same constructor. Subclass( int x, int y, int w) { this(); super(x,y); // compile-error }

q

Example Code
q

TestThisAndSuper.java

TestThisAndSuper.java class TestThisAndSuper { public static void main(String[] args) { Super sup = new Super(10,15); System.out.println("Super x: " + sup.x + " y: " + sup.y); Subclass sub = new Subclass(20,25,30); System.out.println("Sub x: " + sub.x + " y: " + sub.y + " w: " + sub.w); } } class Super { int x; int y; Super(){ System.out.println("Super object being created."); } Super( int x, int y ) { this(); // call no-arg constructor this.x = x; this.y = y; } }
http://www.janeg.ca/scjp/declarations/this.html (2 of 3) [15/03/2004 8:48:18 AM]

Java Quick Reference - Declarations and Access Control - this and super

class Subclass extends Super { int w; Subclass(){ this(0,0,0); }

// call 3-param constructor

Subclass( int x, int y ) { this(x,y,0); // call 3-param constructor } Subclass( int x, int y, int w ) { super(x,y); // call superclass constructor this.w = w; } } TestThisAndSuper.java

http://www.janeg.ca/scjp/declarations/this.html (3 of 3) [15/03/2004 8:48:18 AM]

Java Quick Reference - Declarations and Access Control - Scope

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback

Declarations and Access Control - Scope
q q q

names are used to identify entities declared in a program ie classes, methods, variables, parameters, etc each name or identifier occupies a particular namespace every declaration has a scope; the areas of a program from which it can be accessed by its simple name Scope (accessible from) all compilation units within the package all the classes and interfaces within the compilation unit (source code file) all other declarations within the same file the statements immeadiately enclosed by the labeled statement ie if a loop is labelled, everything declared within the loop-construct has access to the label the body of the class and anything declared within the class the body of the method or constructor the code block in which the declaration occurs the enclosing block including the local class body the body of the for-loop the body of the catch clause

Declaration package import class or interface label

member parameter local variable local class local variable in a for-loop initializer parameter in a catch clause

Order of searching for an identifier (JPL pg 113 and JLS §6.5)
q

1. 2. 3. 4. 5. 6. 7. 8.

when a name (identifier) is used; the meaning, or scope, of it's name is searched for based on where it appears in the code starting with: if used in a code block, for-loop, or in a catch clause, search is for a local variable within the enclosing construct if in a method or constructor, searches for a matching parameter search continues for a class or interface member, including inherited members if its a nested type, searches enclosing block or class. If its a static type, only static members of enclosing blocks or classes are searched. explicitly named imported types other types declared in the same package implicitly named imported types packages on the host system

Shadowing (JLS §6.3.1)
q q

Because of the way identifiers are looked up; shadowing declarations can occur For example, a field declaration can be shadowed by a local variable declaration

class TestShadowing { static int x = 1;

// field variable

public static void main(String[] args) { int x = 0; // local variable

http://www.janeg.ca/scjp/declarations/scope.html (1 of 3) [15/03/2004 8:48:19 AM]

As one is found.out.4.Java Quick Reference . // hides x in superclass } q a method can hide a method in the superclass by overriding it static Methods cannot be overridden q a method cannot override a static method in the superclass.1.2) http://www. the simple identifier name x is assumed to be within scope as a local variable q to access the field variable x. a static method in a subclass cannot hide an instance method in the superclass (JLS §8.out.x = 1 q 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(). System.println("TestShadowing.x Note q it was not necessary to instantiate an instance of the TestShadowing object to access the static field variable.x) } } Output: x = 0 TestShadowing.html (2 of 3) [15/03/2004 8:48:19 AM] . you must use its fully-qualified name TestShadowing.x = " + TestShadowing.6.ca/scjp/declarations/scope. } class SubA extends SuperA { int x = 20.println("x = " + x).Scope System. it can hide it by using the same declaration class SuperA { static void method2() { } } class SubA extends SuperA() { void method2() { // declaration causes a compile-error } static void method2() { // compiles ok } } q q static methods are hidden vs overridden as the JLS states they "cannot be overridden" so the compiler never compares subclass method declarations to static superclass method declarations.3) class SuperA { int x = 10.janeg. int x = 0.Declarations and Access Control . however. If x had been an instance variable it would have been necessary to create a new instance of TestShadowing and use it's reference to access x Hiding q q Shadowing is not the same as hiding hiding applies to members that would normally be inherited but are not because of a declaration of the same identifier in a subclass (JLS § 6.

and a type before a package in such situations a declaration is said to be obscured following naming conventions helps to avoid obscuring (see Naming conventions).janeg.java TestHiding.Scope class SuperA { void method1() { } } class SubA extends SuperA() { static void method1() { // compile-error } } q a hidden method can be accessed by using super().Java Quick Reference . Also See Tech Tip on Sun Site re: Shadowing. etc Example Code q q TestShadowing.2) ((SuperA)y). hiding.6.3.html (3 of 3) [15/03/2004 8:48:19 AM] .ca/scjp/declarations/scope.java Access Modifiers Special Modifiers this and super Scope Inheritance Access Control http://www. a variable will be chosen before a type.4.4. a type or a package based on the rules.Declarations and Access Control .method2().2) q q q q there may be times when a simple name could be interpreted as a variable.6.1) q Obscuring (JLS §6. casting to the superclass or using the methods fully qualified name (JLS §8. // cast to access hidden method instance variables can hide static and non-static variables in the superclass (JLS §8.

Inheritance Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Declarations and Access Control .awt Package The java.4.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q q q q class members are fields.Declarations and Access Control .4. methods. classes or interfaces declared within the body of the class or inherited by the class constructors are not members a field or method can have the same simple name a member class or interface can have the same name as a field or method a class can have two different field variables with the same simple name if they are declared in different interfaces and are inherited but they can only be accessed using their fully-qualified names (compile-error: ambiguous results if simple names are used) a class can have two or more methods with the same simple-name if their signatures are different (overloading) a class may have a method with the same simple-name and signature as an inherited method. the java package always includes the subpackages lang and io and may include others no two distinct members of a package may have the same simple name Class and Interface members (JLS §6.4. if the original was abstract or override it Array members (JLS §6.Java Quick Reference . and all top-level class and interface types declared in the package source files subpackages are determined by the host system.lang Package The java.janeg.Inheritance Package members (JLS §6.1) q q q q package members include all subpackages.util Package The java.4.ca/scjp/declarations/inheritance.html [15/03/2004 8:48:20 AM] .4) q q q the public final field length which contains the number of components in the array (may be zero or any positive number) the public method clone which overrides the method clone in Object and throws no checked exceptions all members inherited from class Object Access Modifiers Special Modifiers this and super Scope Inheritance Access Control http://www.3) q q Threads The java. The original method is not inherited and the new member is said to implement it.2 & §6.

janeg. an array is accessible if and only if it's element type is accessible 4.x. To the compiler. it cannot access the protected fields in Point. field or method of an object reference) or a class constructor is accessible only if the member was declared to allow access r declared public.html (1 of 2) [15/03/2004 8:48:20 AM] . class Point { protected int x.Declarations and Access Control .Access Control q q q accessibility is a static that can be determined at compile time it depends only on types and declaration modifiers accessibility effects inheritance of class members including hiding and overriding Determining accessibility (JLS §6. accessible from other code within the same package or from subclasses in other packages if the outside code is involved in the implementation of the class. all code can access the member r declared protected. the following produces a compile-error package point. If the parameter is changed to ThreePoints p the code will compile as the type ThreePoints inherits the protected fields x and y from Point. Point is a type reference and p.lang Package The java.x and p.y += this.y are declared protected in the type Point. // compile-error: cannot access p.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Declarations and Access Control . a public class or interface is accessible from any code as long as it's compilation unit is reachable by the code 3.y. private members are not inherited http://www. The fact that the code is within the body of a subclass is irrelevant.Java Quick Reference .util Package The java. For example.x += this.Point. The subclass must be involved in the implementation of Point. // compile-error: cannot access p. a member of a reference type (ie a class.awt Package The java. public void delta(Point p) { p.Access Control Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.1) 1.6. y. q declared private. a package is always accessible 2. } package threepoint.x p. class ThreePoints extends Point { protected int z. accessible only from within the body of the enclosing class. interface.ca/scjp/declarations/control.y } } Favourite Links About Feedback Even though ThreePoints is a subclass of Point. import point.

} } class Private2 extends Private1 { Private2() { // compile-error System.Declarations and Access Control .println("Private1 state: " + state).out.Access Control class Private1 { private boolean state.janeg.out.java Access Modifiers Special Modifiers this and super Scope Inheritance Access Control http://www.ca/scjp/declarations/control.Java Quick Reference . default access applies ie accesible only from code within the same package Example Code q q q Point.println("Private1 state: " + state). } } q if no access was declared.java TestPrivateAccess.java ThreePoint. Private1() { System.html (2 of 2) [15/03/2004 8:48:20 AM] .

. selects between two alternatives if( a==b ) // do this else // do this switch selects from various alternatives switch( a ) { case 1: case 2: case 3: default: for executes a set of statements for a defined number of iterations for( int i=0. calls an object method: s.else evaluates an expression and assigns the result to a variable: x = y + z. and performs no operation group of statements enclosed in {}. creates a new instance of a given class: String s = new String("abc").Flow Control .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Flow Control and Exception Handling Statements Java Statements (JJ pg108) Statement empty block Description consists of . i++ ) { // do this } http://www. Treated as a single statement when used with other statements { x +=y.util Package The java.janeg.Statements Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.Java Quick Reference .ca/scjp/flow/statements. ){} assignment invocation return Object creation if. i<10. returns a value from a method call: return x. any statment may be labled using identifier: startLoop: for( .lang Package The java.html (1 of 2) [15/03/2004 8:48:23 AM] .. if( x < 10 ) return y.awt Package The java.toString(). } declaration labeled declares a variable with a particular type and optionally assigns a value: int x = 10.

Flow Control .html (2 of 2) [15/03/2004 8:48:23 AM] .Statements while executes a block of statements while a condition is true while( !done ) { // do this } do executes a block of statments while a condition is false do { // this }while( !done ).ca/scjp/flow/statements. } Statements Labels if Exceptions switch Handling Exceptions for try-catch-finally while do http://www. break continue try-catch-finally transfers the flow of control to a labeled block or out of an enclosing statement forces a loop to start the next iteration catches and processes exception errors that occur during the execution of a given block of code try { // some operation } catch (Exception e) { // handle the exception } finally { // do this } throw synchronized throw an exception gets a lock on an object and executes a statement block synchronized(obj){ obj.setProperty(x).janeg.Java Quick Reference .

} if( boolean expression ) { statement1.if.if.. statementn.. ..lang Package The java.Flow Control .Java Quick Reference ...else Statement Syntax if( boolean expression ) { statement1. otherwise. the statements are only executed if the boolean expression evaluates to true in the second form. statementn. } the expression must be a boolean type curly braces are only required if there is more than one execution statement in the first form.java About Feedback Traps q q a non-boolean value used in the if( ) using the assignment operator '=' vs '==' if Exceptions switch Handling Exceptions for try-catch-finally while do Statements Labels http://www.io Package References Miscellaneous Notes Tips & Traps Flow Control and Exception Handling . the statements following else are executed may be nested if( x == y ) { // do this } else if( x > y ) { // do this } else { // do this } q q q q q Mock Exams Case Studies SCJA Notes SCJD Notes Projects // nested 'if' Example Code Favourite Links q TestIf.awt Package The java. statementz.ca/scjp/flow/if. the first set of statements are executed if the boolean expression evaluates to true.... ..else Statement Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. ..janeg.html [15/03/2004 8:48:23 AM] .util Package The java. } else { statementa.

html (1 of 2) [15/03/2004 8:48:24 AM] .Flow Control .util Package The java. default: statements.awt Package The java.10) switch( expression ) { case value1: statement1..lang Package The java. the default case will be executed if break is omitted between case blocks the code will fallthrough.switch Statement Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. case value3: statement3. q q q SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q q q switch( c ) { case 'a': case 'b': case "c": case 'd': } // String..switch Statement Syntax (JLS §14. char. break. short or int case labels must be constant expressions capable of being represented by the switch expression type Watch for mismatching case constants! char c.ca/scjp/flow/switch.janeg. not character! no two case constant expressions may be the same the default case does not have to be at the end of the code block if no case matches the expression. continuing to execute statements until a break statement or the end of the switch block is encountered Example Code q TestSwitch. break.Java Quick Reference . case valuen: statement n. .java http://www. break. case value2: statement2. break.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies Flow Control and Exception Handling . } transfers control depending on the value of an expression the type of the expression must be byte.

Java Quick Reference .Flow Control .ca/scjp/flow/switch.switch Statement Tips q q you do not have to have a default statement the default statement can appear anywhere in the construct. does not have to be last Traps q q q q using an expression vs a value promotable to int duplicate case values case statements with wrong type missing break statements Statements Labels if Exceptions switch Handling Exceptions for try-catch-finally while do http://www.html (2 of 2) [15/03/2004 8:48:24 AM] .janeg.

i<10 . In the following code. . cannot resolve symbol: x System.util Package The java. x<10 .out.out.Flow Control . x++ ) { // do something } // compile-error.println("value of i: " + i ). } Following produces compile error int x.awt Package The java. expression. x--.for Statement Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. ) . they are discarded after the loop completes For example.println( x + "\t" + y). so it's value is still available once the loop completes int i.lang Package The java. y++){ System. boolean expression. } q q executes some initialization code.for Statement Syntax (JLS §14. http://www. in the following code the initialization variable i is declared outside the for loop. ) // endless loop Initialization q q q initializes variables used within the loop if variables are declared within the loop. . . can be more than one initialization statement but the variables must either be declared outside the for-loop or the type for the variables must be declared at the beginning q q Following compiles and runs ok: for( int x=10. x is declared and initialized inside the for-loop and is therefore only accessible within the loop for ( int x=0. y=0.out.println("value of i: " + x ).ca/scjp/flow/for. then repeatedly executes a boolean expression and some iteration code until the expression is false all three parts are optional ie the following examples are legal for( for( for( for( intialization. iteration ) { statement(s).13) for( initialization.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Flow Control and Exception Handling .html (1 of 3) [15/03/2004 8:48:25 AM] . for ( i=0.janeg. iteration) . x>y.Java Quick Reference . i++ ) { // do something } System. iteration ) .

for Statement for( x=10.ca/scjp/flow/for. Chapter 5 Jaworski Exam Question 8. i++ ){ if( i==5 ) break.janeg. x--. } Example Code q q q TestFor.out.html (2 of 3) [15/03/2004 8:48:25 AM] . int y=0. } Boolean expression q if the expression evaluates to true the loop continues. // skip printing 5 else System. iteration does not occur Break statement q q you can use a break statement to exit a for-loop at any time the break forces processing to the line following the for-loop statement block for( i=0. y++){ System.java Jaworski Exam Question 7. the block statements are executed and then the iteration occurs if the expression evaluates to false. Chapter 5 Tips q all sections of the for() loop are optional Traps q q q attempting to access a variable declared in the initialization outside of the for-loop incorrect initialization expression non-boolean expression Statements if switch for while do http://www.Java Quick Reference .Flow Control .println( x + "\t" + y). i<10. } // process continues here after the break Continue statement q you can use continue to force processing to the next loop iteration for( i=0. the loop is exited and execution continues after the loop statment block Iteration q q if the expression evaluates to true. x>y.println(i). i<10.out. otherwise. i++){ if( i==5) continue.

Java Quick Reference .janeg.Flow Control .html (3 of 3) [15/03/2004 8:48:25 AM] .ca/scjp/flow/for.for Statement Labels Exceptions Handling Exceptions try-catch-finally http://www.

janeg.ca/scjp/flow/while.Flow Control . the statements will never execute int i = 1. } while( i < 10 ){ if( i==5 ) { i++.awt Package The java. } // break out of loop // force next loop System. i++.println("This shouldn't print"). } q both the break and continue statements can be used to alter the processing of a while loop while( i < 10 ){ if( i == 5 ) break.while Statement Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.out.lang Package The java. } q q executes statement(s) repeatedly until the value of expression is false if the expression is false the first time. } Example Code q TestWhile.java Traps q q non-boolean expression using '=' instead of '==' for boolean expression Statements Labels if Exceptions switch Handling Exceptions for try-catch-finally while do http://www.out.println(i).html (1 of 2) [15/03/2004 8:48:26 AM] .while Statement Syntax (JLS §14.util Package The java. continue.out.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Flow Control and Exception Handling . while( i>3 ) { System. i++. System.11) while( boolean expression ) { statement(s).println(i).Java Quick Reference .

janeg.Java Quick Reference .while Statement http://www.ca/scjp/flow/while.Flow Control .html (2 of 2) [15/03/2004 8:48:26 AM] .

i--. }while( i < 10 ). i++.ca/scjp/flow/do.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback if( i==6 ) { i--.java Statements Labels if Exceptions switch Handling Exceptions for try-catch-finally while do http://www.while Statement Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Flow Control and Exception Handling .Java Quick Reference .janeg. break can be used to alter do-loop processing do { if( i==6 ) break.out.out. continue. } while(boolean expression).util Package The java.out..12) do { statement(s). q Example Code q TestDo.println(i).println("Always executed at least once"). } while( false ). // exit loop System.while Statement Syntax (JLS §14.Flow Control .println(i). // skip 6 } else { System.html [15/03/2004 8:48:31 AM] . executes statement(s) until expression is false statement(s) are always executed at least once do { q q Overloading and Overriding Threads q System. continue can be used to alter do-loop processing do { The java.awt Package The java.do. } } while ( i >= 0).lang Package The java.

html [15/03/2004 8:48:31 AM] . j>0. } } } Output: 0 5 outer: for( i=0. Chapter 5 Statements Labels if Exceptions switch Handling Exceptions for try-catch-finally while do http://www. i<10.Java Quick Reference .janeg. i++ ){ for( j=10. Chapter 5 Jaworski Exam. Question 10.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Flow Control and Exception Handling .util Package The java.Flow Control .lang Package The java.awt Package The java. i<10. j--) { if( j== 5 ) { continue outer. i++ ){ for( j=10.ca/scjp/flow/labels. j--){ if( j == 5 ) { break outer.Label Statements Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.java Jaworski Exam Question 9. } } } Output: 10 5 Note q // exit entire loop // next iteration of i two or more statements can have the same name as long as one is not enclosed within the other Example Code q q q TestLabels. j>0.Label Statements Syntax identifier: can be used with loops or statement blocks must precede the statement useful with break or continue which normally terminate or continue the innermost block q q q outer: for( i=0.

lang Package The java.Exception which implements the interface java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Flow Control and Exception Handling Exceptions Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.RuntimeException.html [15/03/2004 8:48:33 AM] .awt Package The java. (Sun tutorial: Handling Errors with Exceptions) q exceptions provide a clean way to check for errors q they are an explicit part of a methods contract q exceptions are thrown at runtime if errors occur when a class is loaded or during method execution q runtime exceptions are objects of the classes java.lang.Error or their subclasses q runtime exceptions are also called unchecked exceptions q code may also throw an exception using the throw statement q these are non-runtime or checked exceptions q any exceptions you create in your code should extend java.lang.lang.Throwable q you create your own exceptions to add useful data to an error message or.ca/scjp/flow/exceptions. java.Exceptions Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.Java Quick Reference . if you are interested in a particular error q both forms of exceptions (checked and unchecked) may be caught and handled in exception-handling code q an uncaught exception is caught by a default handler which halts execution and displays an error message q exception handling is done using the try-catch-finally statment Statements Labels if Exceptions switch Handling Exceptions for try-catch-finally while do http://www.util Package The java.lang.janeg.Flow Control .

declare the exception in your throws clause q a method which does not have a throws clause may still throw unchecked exceptions or errors q these exceptions and errors can occur at any time. throw new ExampleException(). catch and handle the exception 2.Java Quick Reference .() q you do not have to include any checked exception which will be caught and handled within the method q a method can throw multiple exceptions q a method can only throw exceptions that have been declared in the throws clause q an overriding method cannot throw any checked exceptions which are not part of the original methods throws clause q the throws clause must also include any possible exceptions that can be thrown by the method q if you invoke a method that has a checked exception in its throws clause you can 1.janeg. and class or variable initializers must not produce any checked exceptions q exceptions are thrown using the throw statement throw Expression.ca/scjp/flow/methodThrows. instance initializers.Flow Control . in any code Standard Unchecked Exceptions: ArithmeticException IllegalTrheadStateException ArrayStoreException IndexOutOfBoundsException ClassCastException MissingResourceException EmptyStackException NegativeArraySizeException IllegalArgumentException NoSuchElementException IllegalMonitorStateException NullPointerException IllegalStateException NumberFormatException SecurityException Standard Unchecked Errors: AbstractMethodError NoSuchFieldError ClassFormatError NoSuchMethodError ExceptionInInitializerError OutOfMemoryError IllegalAccessError StackOverflowError IncompatibleClassChangeError ThreadDeath InstantiationError UnknownError InternalError UnsatisfiedLinkError LinkageError VerifyError NoClassDefFoundError VirtualMachineError q Static initializers. http://www. catch it and throw one of the exceptions listed in the method throws clause 3.lang Package The java.html (1 of 2) [15/03/2004 8:48:33 AM] .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Flow Control and Exception Handling Exception Handling q methods must declare which checked exceptions they may throw in their throws clause public void methodName throws Exception1.Exception Handling Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.awt Package The java. Exception2.util Package The java.

janeg.html (2 of 2) [15/03/2004 8:48:33 AM] .Java Quick Reference .Flow Control .ca/scjp/flow/methodThrows.Exception Handling q q or by invoking a method that throws an exception the expression must be an instance of a Throwable object ie the exception class must implement Throwable Statements Labels if Exceptions switch Handling Exceptions for try-catch-finally while do http://www.

exit() the finally clause WILL NOT execute. the exception object is assigned to the identifier and the catch statements are executed q if no matching catch clause is found.. } finally { // one or none statements.try-catch-finally Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. be sure to order them from most specific to least specific q when a match is found.Flow Control . } catch (exceptionType2 identifier2) { statements. } .janeg.html (1 of 2) [15/03/2004 8:48:34 AM] .lang Package The java. } catch (exceptionType1 identifier1) { // one or multiple statements. each catch clause is inspected in turn for a type to which the exception can be assigned. Favourite Links Also see About q Sun Tutorial on Handling Errors with Exceptions Sun Tech Tip: Finally Clause Feedback q Example Code q q q q Example code from Java 2 Certification Some other exception handling code Jaworski Exam Question 14.awt Package The java. } q must include either one catch clause or a finally clause q can be multiple catch clauses but only one finally clause q the try statements are executed until an exception is thrown or it completes successfully q a compile-error occurs if the code included in the try statement will never throw one of the caught checked exceptions (runtime exceptions never need to be caught) q if an exception is thrown. it's statements are executed after all other try-catch processing is complete q the finally clause executes wether or not an exception is thrown or a break or continue are encountered Note q If a catch clause invokes System..util Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Flow Control and Exception Handling try-catch-finally Syntax (JPL pg155) try { statements. Chapter 5 http://www.ca/scjp/flow/try.Java Quick Reference . the exception percolates up to any outer try block that may handle it q a catch clause may throw another exception q if a finally clause is included. Chapter 5 Jaworski Exam Question 15.

Flow Control .ca/scjp/flow/try.janeg.try-catch-finally Statements Labels if Exceptions switch Handling Exceptions for try-catch-finally while do http://www.Java Quick Reference .html (2 of 2) [15/03/2004 8:48:34 AM] .

Java Quick Reference - Operators - Conversions

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding

Conversions
Implicit conversions (JPL pg 121)
q q

q q

q

conversions which happen automatically any primitive type value can be converted to a type which supports a larger value (widening primitive conversion) implicit conversion occurs from integer to floating point values but not vice versa you can use an object of one type wherever a reference to one of it's supertypes is required ie you can reference up the class hierarchy but not down you can assign a null object reference to any object reference

Explicit conversion (JPL pg 122)
q

Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback
q q q

when one type cannot be assigned to another type through implicit conversion you can use the cast operator

Identity Conversion (JLS §5.1.1)
any type can be converted to it's own type only conversion allowed for boolean primitive type

Widening Primitive Conversion (JLS §5.1.2)
byte -> short -> int -> long -> float -> double char -> int -> long -> float -> double q widening conversions of integer types preserve the exact original value of the number q runtime errors never occur as a result of widening conversion q which is why widening conversion does not allow byte and short values to be converted to char as the char type is unsigned while byte and short are signed; the byte and short would lose information byte b = 126; short s = 1000; char c; c = b; // compile error: possible loss of precision c = s; // compile error: possible loss of precision widening conversion of an int or long to a float may result in loss of precision however the new float value will be the correctly rounded equivalent of the original number the same applies when a long is widened to a double

q

Narrowing Primitive Converson (JLS §5.1.3)
double -> float -> long -> int > char -> short > byte q narrowing primitive conversion may lose information about the overall magnitude of the number and may also lose precision q runtime errors never occur as a result of narrowing conversion because compile time errors occur if you try it; need to use cast operator

http://www.janeg.ca/scjp/oper/conversions.html (1 of 3) [15/03/2004 8:48:36 AM]

Java Quick Reference - Operators - Conversions
q

narrowing conversion loses all but the lowest bits (see Working with Binary, Octal and Hex numbers) narrowing from floating-point numbers to integer numbers occurs within the following minimum and maximum values (values are rounded-toward-zero)

q

long: -9223372036854775808..9223372036854775807 int: -2147483648..2147483647 short: 0..-1 char: 0..65535 byte: 0..-1 q if the floating-point value is NaN the result is an int or long value of zero

Widening Reference Conversion (JLS §5.1.4)
q q q q q q q

convert from any class, interface or array reference to an Object reference convert from any class to any interface that it implements convert from any class, interface or array type to a null reference convert from any subinterface to any interface it extends from any array to type Cloneable or type java.io.Serializable from any array of references to an array of compatible reference types the above conversions never produce a runtime error or require special action

You can't instantiate an interface reference as interfaces are always abstract SuperInterface si = new SuperInterface(); // compile-error

Narrowing Reference Conversion (JLS §5.1.5)
q q q

q q q

q

from Object to any other class, interface or array type from any superclass to a subclass from any non-final class to any interface as long as the class does not implement the interface from any interface to any non-final class from any interface to any final class providing the final class implements the interface from any interface to any other non-superinterface and providing neither interface contains methods with the same signature from any array of reference types to any other array of reference types as long as the types of each array are compatible under the Narrowing Reference rules

The above will be allowed at compile time but may throw a runtime ClassCastException if the types are not compatible Summary
q

q

widening conversions do not require casts and will not produce compile or runtime errors narrowing conversions require explicit casts. Will compile ok but may result in runtime ClassCastException errors

String Conversions
q

every other type, including null, can be converted to String

Method Conversion
q q

each argument is converted to the type of the method parameters widening conversion is implicit

http://www.janeg.ca/scjp/oper/conversions.html (2 of 3) [15/03/2004 8:48:36 AM]

Java Quick Reference - Operators - Conversions
q

narrowing conversion is not implicit (values must be cast)

Forbidden Conversions (JLS §5.1.7)
q q q q q q q q q q q

reference to primitive primitive to reference (excepting String) null to primitive reference or primitive to boolean boolean to reference (excepting String) or primitive one class to another unless they have a superclass/subclass relationship (excepting String) final class to interface unless the final class implements the interface class to array unless the class is Object array to any class other than Object or String array to any interface other than java.io.Serializable or Cloneable interface to interface if they contain methods with the same signature

Also see
Sun Tech Tip: Narrowing and Widening Conversions

Example Code
q

TestConversions.java

Traps
q q

variables requiring narrowing conversion being passed to methods without using a cast assigning a typed byte or short variable to a char variable

Conversions Bin/Hex/Octal Cast Method Invocation

Promotion Bitwise Ternary

Overflow Shift String

Unary Comparison equals()

Prefix Logical Precedence

Arithmetic Assignment Bit vs Logic

http://www.janeg.ca/scjp/oper/conversions.html (3 of 3) [15/03/2004 8:48:36 AM]

Java Quick Reference - Operators and Assignments - Cast Operator

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes

Operators and Assignments - Cast Operator
q q

the cast operator (type) is used to convert numeric values from one numeric type to another or to change an object reference to a compatible type used to enable conversions that would normally be disallowed by the compiler byte a = 1; byte b = 2; byte c = a + b; // a and b are promoted to int byte c = (byte)(a + b); // compiles ok

Casting with Object references (JLS §5.5, JJ pg 67)
q q

q

a reference of any object can be cast to a reference of type Object a reference to an object can be cast into a reference of type ClassName if the actual class of the object, when it was created, is a subclass of ClassName a reference to an object can be cast into a reference of type InterfaceName if the class of the object implements Interface, if the object is a subinterface of InterfaceName or if the object is an array type and InterfaceName is the Cloneable interface

If you cast up the class hierarchy you do not have to use the cast operator; if you are cast down the class hierarchy you must use the cast operator (BB pg 41) However, the compiler uses the declared type to verify the correctness of each method call; which means you cannot invoke a subclass method from a superclass reference. (See post by Michael Ernest at JavaRanch)
q

q q

a cast may work at compile-time but fail at runtime if the actual class of the object cannot be converted legally while you can cast up and down the class hierarchy, you cannot cast sideways you can cast an object reference using String Example from Java 2 Certification by Jamie Jaworski, pg 69

SCJD Notes Projects Favourite Links About Feedback

String s1 = "abc"; String s2 = "def"; Vector v = new Vector(); v.add(s1); s2 = (String) v.elementAt(0); // cast allowed System.out.println(); System.out.println("Value of s2: \t\t" + s2); output: abc Note: if the String cast is omitted, the type of v.elementAt(0) is an Object and a compile error (incompatible types) results. you cannot use String as a cast type for a primitive type String s = (String)x is invalid you can use String s = new Byte(x).toString();

q

X x = new X(); Y y = new Y(); Z z = new Z();

http://www.janeg.ca/scjp/oper/cast.html (1 of 3) [15/03/2004 8:48:37 AM]

Java Quick Reference - Operators and Assignments - Cast Operator

X xy = new Y(); X xz = new Z(); Y yz = new Z(); Y y1 = new X(); Z z1 = new X(); X x1 = X x2 = Y Z Y Z Y Z y1 z1 y2 z2 y3 z3 = = = = = = y; z; (Y) (Z) (Y) (Z) (Y) (Z) x; x; x1; x2; z; y;

// compiles ok (up the hierarchy) // compiles ok (up the hierarchy) // incompatible type // X is not a Y // X is not a Z // compiles ok (y is subclass) // compiles ok (z is subclass) // // // // // // compiles ok but produces runtime error compiles ok but produces runtime error compiles and runs ok (x1 is type Y) compiles and runs ok (x2 is type Z) inconvertible types (casts sideways) inconvertible types (casts sideways)

Object o = z; Object o1 = (Y)o; // compiles ok but produces runtime error The casts work at compile time since the cast variable could conceivably be of a compatible type; however, at runtime the type of the variable is known and if it cannot guarantee to implement the contract of the cast type a java.lang.CastClassException will be thrown.

Casting with arrays
q

to cast an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference

double arr[] = {1.5, 2.256, 3.59}; int arr1[] = (int) arr; // compile-error X[] arrX = { new X(), new X(), new X() }; Y[] arrY = { new Y(), new Y(), new Y() }; arrX = arrY; // compiles ok

Also see:
q

Conversions

Example Code
q

TestCast.java

Tips
q q

you cannot cast a primitive type to an object reference, or vice versa you cannot cast a boolean type to another primitive type

Traps
q

result of an integer operation on byte or short types being assigned to a byte or short without an explicit cast

http://www.janeg.ca/scjp/oper/cast.html (2 of 3) [15/03/2004 8:48:37 AM]

Java Quick Reference - Operators and Assignments - Cast Operator

Conversions Bin/Hex/Octal Cast Method Invocation

Promotion Bitwise Ternary

Overflow Shift String

Unary Comparison equals()

Prefix Logical Precedence

Arithmetic Assignment Bit vs Logic

http://www.janeg.ca/scjp/oper/cast.html (3 of 3) [15/03/2004 8:48:37 AM]

Java Quick Reference - Operators - Promotions

Java Quick Reference

Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package

Operators and Assignments - Numeric Promotion
Unary Numeric Promotion
q

the Unary operators + and - when applied to byte, char or short numeric types result in the operand being automatically promoted to an int.(JLS §5.6.1) Example producing compile error: byte b = 5; // assign byte value byte b1 = +b; // found int, required byte unary promotion also applies for all shift operators. A long operator does not force the conversion of a left-hand int operator to long(JLS§5.6.1)

q

Binary Numeric Promotion
q

The java.util Package The java.awt Package The java.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects
q q

when operands are of different types, automatic binary numeric promotion occurs with the smaller operand type being converted to the larger. the following rules are applied in the order given. (JLS §5.6.2) r if either operand is a double, the other operand is converted to double r otherwise, if one of the operands is a float, the other operand is converted to a float r otherwise, if one of the operands is a long, the other operand is converted to a long r otherwise, both operands are converted to int

Examples producing compile-errors: byte = byte + byte; int = float + int; long = float + long; float = double + float; // // // // found found found found int, required byte float, required int float, required long double, required float

Remember to check the type of the variable to which results are assigned

Rules apply to following operators:
Favourite Links About Feedback
q q q q

Additive: + and Multiplicative: *, /, and % Comparison: <, <=, >, and >= Equality: = and != Bitwise: &, ^, and |

Special case for Ternary conditional operator (JLS §15.25)
q

if one of the operands is byte and the other is short then the type of the expression is short byte = true ? byte : short // found short, required byte if one of the operands is a constant of type int and the other operand has a type of byte, short, or char and the value of the int operand is within the other type range, the type of the expression will be the type of the non-int operand.

q

http://www.janeg.ca/scjp/oper/promotions.html (1 of 2) [15/03/2004 8:48:38 AM]

Java Quick Reference - Operators - Promotions

short = true ? short : 1000; // compiles and runs OK short = false ? short : 1000; // compiles and runs OK

Example Code
q

TestNumericPromotion.java

Traps
q

expression assigning byte or short operations to a byte or short variable

Conversions Bin/Hex/Octal Cast Method Invocation

Promotion Bitwise Ternary

Overflow Shift String

Unary Comparison equals()

Prefix Logical Precedence

Arithmetic Assignment Bit vs Logic

http://www.janeg.ca/scjp/oper/promotions.html (2 of 2) [15/03/2004 8:48:38 AM]

instead the sign of the result may not be the same as that expected in the mathematical result You probably won't need to calculate overflows or underflows on the exam but should understand how they work.low order bytes ----------10011101 10010000 00000000 00000000 because an 32-bit cannot retain the number.Java Quick Reference . the 4 high-order bytes are dropped leaving the four low-order bytes: 10011101 10010000 00000000 00000000 which represent 1651507200 and since the right most bit is a 1 the sign value is negative q SCJD Notes Projects Favourite Links About Feedback overflow or underflow conditions never throw a runtime exception.html (1 of 2) [15/03/2004 8:48:39 AM] .util Package The java.println(n * n). (also see Working with Hex.Overflow and Underflow q q q an overflow results when a calculated value is larger than the number of bytes allowed for its type a underflow results when a calculated value is smaller than the number of bytes assigned to its type Java handles overflows by discarding the high-order-bytes that won't fit into the number of bytes allowed by its type (JJ pg 52) int n = 2000000000.ca/scjp/oper/overflow.000.000 which needs 64-bits which in binary is: ---------.awt Package The java.high-order bytes ------00110111 10000010 11011010 11001110 ------.lang Package The java.Operators .000.out.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes Operators and Assignments .000.000. Octal and Binary numbers) Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.Overflow and Underflow Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. // output: -1651507200 An int is 32-bits.janeg.000. the result of n*n is 4. System.

Operators .html (2 of 2) [15/03/2004 8:48:39 AM] .ca/scjp/oper/overflow.Overflow and Underflow http://www.Java Quick Reference .janeg.

each position corresponds to a power of 2 = 0 = 64 = 0 = 0 = 8 = 0 = 0 = 1 -73 the largest number which can be represented by a byte is 255 or 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 or the bit pattern: 1111 1111 the smallest number is 0 represented by the bit pattern: 0000 0000 0 to 255 gives 256 possible values x x x x x x x x 27 26 25 24 23 22 21 20 -> -> -> -> -> -> -> -> 0 1 0 0 1 0 0 1 x 128 x 64 x 32 x 16 x 8 x 4 x 2 x 1 01001001 = 0 1 0 0 1 0 0 1 q q Two's-complement q the two's complement method allows us to represent negative and positive values within the http://www.util Package The java. the low-order bit in the decimal system.Operators and Assignments .awt Package The java. in the binary system. This makes it easier to represent computer memory using a base 2 number system rather than the base 10 decimal system. the binary system represents numbers by a series of 1's and 0's which correspond to 'on' and 'off' values a 1 represents an 'on' position.janeg.html (1 of 4) [15/03/2004 8:48:40 AM] . a 0. Decimal system q q q the decimal number system we use every day is built on base ten 1010 it is based on 10 positions numbered 0 thru 9 each position corresponds to a power of 10 1024 = 1 0 2 4 x x x x 103 102 101 100 -> -> -> -> 1 0 2 4 x 1000 x 100 x 10 x 1 = 1000 = 000 = 20 = 4 ---1024 Binary system q q q Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q q q q computer memory is based on the electrical representation of data each memory position is represented by a bit which can be either 'on' or 'off'.Binary/Octal/Hex and Decimal Number Systems Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. the right most bit.io Package References Miscellaneous Notes Operators and Assignments . an 'off' position a byte is represented by 8 bits numbered 0 to 7 from left to right the leftmost bit is called the high-order bit.lang Package The java.Binary/Octal/Hex and Decimal Number Systems Probably not directly required on exam but helpful when using bitwise and logical operators.Java Quick Reference . each position corresponds to a power of 10.ca/scjp/oper/binhex.

232-1.1 = -127 q larger numbers are represented by increasing the number of bits in a memory block q this is done in multiples of 8 hence 16-bit.B. 0 to 4.295 (232 1) using two's-complement arithmetic with 32-bit memory. 32-bit and 64-bit memory q q q 16-bit memory can store numbers up to 216-1.32 .1 = 255.ca/scjp/oper/binhex. 253 = -3.50 = 206 the high-order bit (the 7th position) is reserved for the sign value of a number a 0 in the high order bit means 'the sign value is set to positive' a 1 in the high-order bit means 'the sign value is set to negative' 01111111 = 0 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 127 10000000 = 128 or set sign negative 11111111 = 0 .64 . 64-bit.294.Binary/Octal/Hex and Decimal Number Systems q q q q q 0 to 256 bit positions in this system the numbers 0 thru 127 represent themselves and the numbers 128 to 256 represent negative numbers where 255 = -1.html (2 of 4) [15/03/2004 8:48:40 AM] . 254 = -2.F one hexidecimal digit corresponds to a four-digit binary number http://www.536 to find it's positive complement ie -336 would be represented by 65536 .Operators and Assignments .C. 264-1 if signed numbers are being used.2 .D. 16-bits allows us to store 0 to 65.967... 32-bits.janeg. 32-bit.1).535 positions (216 .16 .Java Quick Reference . . -1 is represented by 256 . and -50 would be represented by 256 .4 .336 = 65200 q Octal system q q q q q uses base 8 octal digits are represented by 0 thru 7 each position is a power of 8 each octal number can be represented by 3 binary digits 22+21+20 = 4+2+1 = 7 Octal 0 1 2 3 4 5 6 7 Binary 000 001 010 011 100 101 110 111 Decimal 0 1 2 3 4 5 6 7 q to convert from Octal to Binary just replace the octal digit with the corresponding binary pattern Octal: 17 Binary: 001 111 to convert from Binary to Octal just replace the binary pattern with the corresponding octal digit Binary: 111 010 Octal: 72 q Hexidecimal system q q q the hexidecimal system uses a base of 16 hexidecimal digits are represented by 0 thru 9 and the letters A.8 .E. subtract the negative number from 65. the left-most bit still represents the sign so. -127 is represented by 256-127 = 129.

2*24 = 49 .ca/scjp/oper/binhex.48 = 1) ( 6 .Java Quick Reference .16*0 = 3 . so 3116 would be written as 0x0031 when converting large decimal numbers to binary. in reverse order represent the required value Convert Decimal 49 to Binary 49: 49 24 12 6 3 1 / / / / / / 2 2 2 2 2 2 = 24 = 12 = 6 = 3 = 1 = 0 remainder: remainder: remainder: remainder: remainder: remainder: 1 0 0 0 1 1 ( 49 .html (3 of 4) [15/03/2004 8:48:40 AM] .Operators and Assignments . the simplest method is to convert to Hex and then to binary http://www.0 = 6) Proof: 618 = (6 * 81) + (1 * 80) = 48 + 1 = 4910 Convert Decimal 49 to Hexidecimal 49: 49 / 16 = 3 3 / 16 = 0 remainder: remainder: 1 3 ( 49 .8*0 = 6 .2*12 = 24 .2* 6 = 12 .0 = 1) Proof: 110001 = 32+16+0+0+0+0+1 = 4910 Convert Decimal 49 to Octal 49: 49 / 8 = 6 6 / 8 = 0 remainder: remainder: 1 6 ( 49 .janeg.16*3 = 49 .Binary/Octal/Hex and Decimal Number Systems q 23+22+21+20 = 8 + 4 + 2 + 1 = 15 Hex 0 1 2 3 4 5 6 7 Binary Decimal 0000 8 0001 0010 0011 0100 0101 0110 0111 9 10 11 12 13 14 15 Hex 8 9 A B C D E F Binary 1000 1001 1010 1011 1100 1101 1110 1111 Decimal 0 1 2 3 4 5 6 7 q this makes it easy to convert a number from binary to hex (just replace the binary pattern with the hex digits) or from hex to binary (replace the hex digit with the binary pattern) -> Hex: -> Hex: -> Binary: -> Binary: 0x0F 0xB302 1010 0000 1111 1111 1111 0000 0111 0101 Binary: 0000 1111 Binary: 1011 0011 0000 0010 Hex: Hex: 0xA0FF 0xF075 Converting between number systems q to convert a decimal number to a Hex.12 = 0) ( 6 .24 = 0) ( 12 .48 = 1) ( 3 .0 = 3) Proof: 3116 = (3*161) + (1*160) = 48 + 1 = 4910 q q q in Java octal numbers are represented by 3 digits beginning with a zero.8*6 = 49 .48 = 1) ( 24 .2* 3 = 6 . Octal or Binary number divide by the required base.6 = 0) ( 3 .2* 0 = 1 .2 = 1) ( 1 . the resulting remainders. so 618 would be written as 061 Hex numbers are always represented by 4 digits preceeded by 0x.2* 1 = 3 .

toBinaryString(-29)). hex and octal strings.com/applets/BitShift/BitShiftAr.Binary/Octal/Hex and Decimal Number Systems Convert 4823 to Hex: 4823 301 18 1 / / / / 16 16 16 16 = 301 remainder: 7 = 18 remainder: 13 = 1 remainder: 2 = 0 remainder: 1 (4823 ( 301 ( 18 ( 1 16*301 16* 18 16* 1 16* 0 = 4823 . You can also use the Java Integer wrapper class to output binary.out.288 = 13) = 18 16 = 2) = 1 0 = 1) Hex value: 0x12D7 Hex value converted to binary: 0001 0010 1101 0111 q when converting large binary numbers.Operators and Assignments .html (4 of 4) [15/03/2004 8:48:40 AM] .software. and octal conversions. the simplest method is to convert to Hex and then to decimal Convert Binary 0001 0010 1101 0111 to decimal 0001 0010 1101 0111 1 2 D 7 1 2 13 7 * * * * 163 162 161 160 = 4096 = 512 = 208 = 7 ---4823 Study aids q q q If you have Windows 95 you can use the Calculator in the Scientific mode (Start->Programs->Accessories->Calculator) to check results of decimal to hex.janeg.html References: q q C: Step-by-Step by Mitchell Waite and Stephen Prata.Java Quick Reference . Example: System.4816 = 7) = 301 .println(Integer.u-net. SAMS.ca/scjp/oper/binhex. 1991 Hexidecimal and Octal Notation Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www. Marcus Greene has a great applet that lets you play around with bit-shifting at http://www. binary.

janeg.lang Package The java.Unary Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. ~7 = -7 -1 ~3578 = -3578-1 ~-1234 = -(-1234)-1 // binary: 0000 0111 // binary: 1111 1000 ( -8 ) = -8 = -3579 = 1233 Unary ! Logical complement (JLS §15.5) q q q only used with integer values inverts the bits ie a 0-bit becomes 1-bit and vice versa in all cases ~x equals (-x)-1 byte b0 = 7.ca/scjp/oper/unary.Unary Operators q q q q operate on a single operand the unary ~ . // result: -2147483648 http://www. i = -(-2147483648). b = (~5) + 1.Java Quick Reference .15.0.4) q About Feedback q for integers negation effect is the same as subtraction from zero two's complement is used for integers so for all values of x.3) q the result of the unary + operator is a value not a variable byte b = +5.15. -x equals (~x)+1 byte b. (JPL pg 128) Unary .operator (JLS §15. An overflow occurs but no exception is thrown. it is included for symmetry only and to allow the declaration of constants ie MIN_VALUE = +2. + and .15. int i.operators can only be applied to numeric primitive types the unary ! (logical complement) can only be applied to a boolean type rules of unary numeric promotion apply Unary ~ Bitwise complement (inversion) (JLS §15. long l = 0L. !(true) = false.Operators .io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links Operators and Assignments . // result: -5 // result: -5 q negation of the maximum negative int or long value results in the same number.awt Package The java.html (1 of 2) [15/03/2004 8:48:40 AM] . byte b1 = ~b0.6) q returns the logical complement of a boolean type !(false) = true.util Package The java.15. // result: 5 The unary plus (+) operator has no effect on the sign of a value. b = -5. // complement of 'false' is 'true' // complement of 'true' is 'false' Unary + operator (JLS §15.

ca/scjp/oper/unary. for floating-point negation is not the same as subtraction from zero the unary (-) operator merely negates the sign of the value double d = 0D.63).janeg.Java Quick Reference .63 // result: 15.java Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www. d = -(-15.html (2 of 2) [15/03/2004 8:48:40 AM] .63 Example Code q TestUnaryQuestions. d = -(15. // result: -15.Unary Operators q q l = -(-9223372036854775808L) // result: -9223372036854775808.Operators .63).

1 int x. // result: -128 (no error as fits within byte type) q the expression has the same type as the variable q they can appear before a variable (prefix) or after a variable (postfix) q cannot be used with final variables Prefix (++x) and Postfix (x++) increment operators q q 1 is added to the value of the variable and the result is stored back in the variable both operators have the same effect as x = x + 1.ca/scjp/oper/prefix.awt Package The java.lang Package The java. // no error although promotion occurs b = 127. b1 = ++b. // result: -1 // result: -1 Using prefix and postfix operators in expressions q when a prefix expression (++x or --x) is used as part of an expression. the value returned is the value calculated after the prefix operator is applied http://www. --x. b1 = ++b. x++.are used to increment or decrement a variable value by 1 binary numeric promotion is applied on both the 1 and the variable value before the addition or subtraction occurs (ie at a minimum both values are promoted to an int) BUT the type of the expression is the type of the variable so narrowing conversion is applied if necessary ie if the original variable is a byte.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links Operators and Assignments . or char the result is narrowed to the corresponding type byte b = 2. x = 0.Operators and Assignments . // result: 1 // result: 1 Prefix (--x) and Postfix (x--) decrement operators q q 1 is subtracted from the value of the variable and the result is stored back in the variable both operators have the same effect as x = x .util Package The java. short.html (1 of 2) [15/03/2004 8:48:42 AM] .janeg. byte b1. x = 0. int x.Prefix Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. x = 0. About Feedback x = 0. ++x.Java Quick Reference .Prefix and Postfix Operators q q the operators ++ and -. x--.

y = x++. // result: a the type of the variable does not change q Example Code q TestPrefixAndPostfix.Java Quick Reference . // result: y=1. the current value of the variable is used Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.ca/scjp/oper/prefix.Prefix Operators int x = 0. the value returned is the value calculated before the postfix operator is applied int x = 0. // result: 0. x is not incremented original value of x is saved (x0rig) x is incremented x0rig is assigned to x therefore. x is incremented. c++.Operators and Assignments .janeg. x = x++.java Tips q q postfix/prefix operators have the highest level of precedence remember that when the postfix operator is used in an expression. original value of x is assigned to y when using the postfix form of the operators do not try constructs like int x = 0. // result: y=0. int y = 0. y = ++x. // result: b --c.html (2 of 2) [15/03/2004 8:48:42 AM] . x will always equal original value Effect on 'char' type q both the prefix and postfix forms may be used on char types char c = 'a'. int y = 0. x=1 q x is incremented by 1 and the result is assigned to y when a postfix expression (x++ or x--) is used as part of an expression. x=1 q original value of x is stored.

3) q Feedback q q the modulo operator % is also called the remainder operator as it returns the remainder.((int) (x/y) * y) can be used with both integer and floating-point numbers following rules apply as to the sign of the result: r result is negative if the divdend is negative r result is positive if the divdend is positive r if the divisor is zero. JLS §15.janeg.2) q integer division rounds towards 0.html (1 of 2) [15/03/2004 8:48:43 AM] . ie result is truncated 10 / 3 = 3. // truncated result if the value of the divisor in integer division is 0 an ArithmeticException is thrown 10 / 0 // runtime error: ArithmeticException if the value of the divisor in floating-point division is 0 no exception is thrown.ca/scjp/oper/arithmetic. /.io Package q References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About q q 10. no exception is thrown and the result is NaN 5 % 3 = 2 http://www.lang Package The java.34 -10. the value of the results are as follows: r division of a positive floating-point value: POSITIVE_INFINITY r division of a negative floating-point value: NEGATIVE_INFINITY r division of a floating-point value by -0: POSITIVE_INFINITY / 0 / 0 / -0 / 0 // // // // result: Infinity result: -Infinity result: Infinity result: NaN (Not a number) The java. of a division operation x % y is equivalent to x .awt Package The java.Arithmetic Operators Additive operators (JLS §15.Java Quick Reference .17.34 0 Modulo operations (JLS §15.17) q q q Overloading and Overriding Threads The java.18) q q q + and have the same precedence and are left-associative operands must be primitive numeric types (see exception for String and +) or compile error occurs Multiplicative operators (JLS §15.Arithmetic Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Operators and Assignments . Integer Division and Division by Zero (JJ pg 50.Operators and Assignments .17. a runtime ArithmeticException is thrown r if the dividend is a floating-point value and the divisor is zero.34 10. % have the same precedence and are left-associative operands must be primitive numeric types or compile error occurs. or fractional part.util Package *.

0 5.java Traps q floating point operation throwing an ArithmeticException Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.Arithmetic Operators -5 5.0 = NaN // not a number Also see: q q q Binary numeric promotion Overflow and underflow Sun Tech Tip: Division by Zero Example Code TestArithmetic.Operators and Assignments .janeg.html (2 of 2) [15/03/2004 8:48:43 AM] .ca/scjp/oper/arithmetic.0 % % % % 3 3 3 0 = -2 = 2.0 = -2.Java Quick Reference .0 -5.

Instead the variable is assigned a reference to the existing pooled string. not primitive types. // += only works with an initialized var String str4 = str2. String str2 = str + str1.equals(str2).html (1 of 2) [15/03/2004 8:48:43 AM] . String str5 = "Hello Universe!". String str1 = "Universe!". str5 == str2 // false (str2 is not part of the pool. the contents never change String variables store references to a string object NOT the string itself String str = "Hello".String Operator Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. and are read-only and immutable. // created in the string pool String str6 = "Hello Universe!".lang Package The java. // true (both objects hold the same string // characters) http://www.String Operators q q q q q the + and += operators both work on Strings operators actually signfy concatenation the result of the operation is a new string Strings are objects.util Package The java.janeg. q in the above code a reference to the string "Hello" is stored in the variable str q a reference to the string "Universe!" is stored in the variable str1 q a reference to a new string "Hello Universe!" is stored in the variable str2 q the reference for a new string "Hello" is stored in variable str3 str3 == str // false (ref to different String objects) q the reference for str2 is stored in variable str4 str4 == str2 // true (references are the same) Where it can get confusing q q q the String class creates a pool of Strings when you create a String by using the new operator or by using the + and += operators (the string is computed at runtime) you are implicitly telling the compiler to create a new String object when you create a String by assigning a string literal the compiler searches the existing string pool for an exact match.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Operators and Assignments .Operators and Assignments . a new string is NOT created. str3 += str.Java Quick Reference .awt Package The java. // join the two strings together String str3 = "". created // using '+' operator) str5 == str6 // true (matched an existing string found // in the pool) q to actually compare the contents of String objects use the String method equals() str5. If it finds one.ca/scjp/oper/string.

conversion occurs by the compiler calling Type. is the same as System.janeg. int x = 10.java Tips q q String operations whose result does not alter the original string (ie calling toUpperCase() on a String that is already in uppercase) return the original string reference. the original String value can never be changed Traps q using == to compare the contents of two different String objects Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic Conversions Bin/Hex/Octal Cast Method Invocation http://www. otherwise they return a reference to a new String Strings are immutable.toString(x) behind the scenes.Java Quick Reference . Also see: q q String literals Sun Tech Tip: Interning Strings Example Code q TestStringOperators.html (2 of 2) [15/03/2004 8:48:43 AM] .out.Operators and Assignments .toString(x)) ).out.String Operator Strings and primitive types q q q by the rules of String Conversion (see Conversion) any type can be converted to a string this includes the primitive types for primitive types.ca/scjp/oper/string.println("Result: " + x).println("Result: " + (Integer. System.

^. otherwise returns a 1 Also see q q Unary bitwise complement operator ~ Logical (boolean) bitwise operators Example Code q TestBitwise.Java Quick Reference .ca/scjp/oper/bitwise.Bitwise Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.awt Package Operators and Assignments . | & AND operator q returns a 1 if corresponding bits in both operands have a 1.lang Package The java.Bitwise Operators q q q q q q & AND.Operators and Assignments . | OR. otherwise returns a 0 = 00000000 00000000 00000000 00111111 = 00000000 00000000 00000000 11111100 ----------------------------------00000000 00000000 00000000 00111100 -> 60 63 252 | OR operator q returns a 0 if corresponding bits in both operands are 0.jsva Tips q precdence order is: & ^ | http://www. ^ exclusive OR used for operations on integer and boolean values (see logical bitwise operators) results are calculated bit-by-bit binary numeric promotion rules apply left associative order of precedence: &. otherwise returns a 1 = 00000000 00000000 00000000 00111111 = 00000000 00000000 00000000 11111100 ----------------------------------00000000 00000000 00000000 11111111 -> 255 The java.html (1 of 2) [15/03/2004 8:48:44 AM] .janeg.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback 63 252 = 00000000 00000000 00000000 00111111 = 00000000 00000000 00000000 11111100 ----------------------------------00000000 00000000 00000000 11000011 -> 195 63 252 ^ exclusive OR q returns a 0 if the corresponding bits of both operands are both 0 or both 1.util Package The java.

janeg.Operators and Assignments .Bitwise Operators Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.html (2 of 2) [15/03/2004 8:48:44 AM] .ca/scjp/oper/bitwise.Java Quick Reference .

Conditional AND Operator && q q q q both operands must be boolean result is a boolean returns true if both operands are true.false if both operands are false. // both operands evaluated // only lef-operand evaluated The conditional operators are also referred to as short-circuit operators. // both operands true // one operand is false // both operands are different // both operands are the same // one operand is true // both operands are false true | false = true.Logical Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. false. true true & true true & false true ^ false true ^ true = true.html (1 of 2) [15/03/2004 8:48:44 AM] . true. otherwise false ^ . otherwise false | . = false. = true.janeg. otherwise false evaluates the right-hand operand only if the left-hand operand is true true && true = true.Logical Operators Boolean logical operators & | and ^ q q q q when both operands are boolean the result of the bitwise operators & | and ^ is a boolean & .ca/scjp/oper/logical. = false.awt Package The java. true.true if both operands are true. false | false = false. otherwise. // both operands evaluated // only left-operand evaluated Conditional OR Operator || q q q q both operands must be boolean result is a boolean returns true if one of the operands is true evaluates the right-hand operand only if the left-hand operands is false false false true true || || || || true false false true = = = = true.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Operators and Assignments .Java Quick Reference .util Package The java. false && true = false.Operators and Assignments .true if both operands are different. Also see q Integer Bitwise operators http://www.lang Package The java.

Operators and Assignments .ca/scjp/oper/logical.Java Quick Reference .janeg.Logical Operators Example Code q TestLogical.java Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.html (2 of 2) [15/03/2004 8:48:44 AM] .

Shift Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Operators and Assignments .janeg.19) q q q bits are shifted to the left based on the value of the right-operand new right hand bits are zero filled equivalent to left-operand times two to the power of the right-operand For example.1) left-associative left-hand operator represents the number to be shifted right-hand operator specifies the shift distance value << 2 // 2 is the distance to be shifted when the value to be shifted (left-operand) is an int. instead unary promotion is performed on each operand separately (JLS §15.Java Quick Reference . so it can be dropped off or a different sign can replace it Right-shift >> (JLS §15.awt Package The java.ca/scjp/oper/shift.6.19) both operands are individually promoted to int if their type is byte. The actual size of the shift is the value of the right-hand operand masked by 63 (0x3D) ie the shift distance is always between 0 and 63 (if shift value is greater than 64 shift is 64%value) q the shift occurs at runtime on a bit-by-bit basis Left-shift << (JLS §15. short or char a long shift operator does not force a left-hand int value promotion to long (JLS§5. only the last 5 digits of the right-hand operand are used to perform the shift. >>> unsigned right-shift only used on integer values binary numeric promotion is not performed on the operands. The actual size of the shift is the value of the right-hand operand masked by 31 (0x1f).lang Package The java. only the last 6 digits of the right-hand operand are used to perform the shift.19) q bits are shifted to the right based on value of right-operand http://www.html (1 of 3) [15/03/2004 8:48:45 AM] .Shift Operators q q q q Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding q q q q << left-shift.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback 35 31 -> 0x1f & Shift value -> 3 -29 11111111 11111111 11111111 11100011 31 -> 0x1f 00000000 00000000 00000000 00011111 & ----------------------------------Shift value 00000000 00000000 00000000 00000011 -> 3 q when the value to be shifted (left-operand) is a long.Operators and Assignments . >> right-shift.util Package The java. 16 << 5 = 16 * 25 = 512 00000000000000000000000000010000 Decimal 16 Left-shift 5 00000000000000000000000000010000 fill right 0000000000000000000000000001000000000 discard left 00000000000000000000001000000000 q the sign-bit is shifted to the left as well. ie the shift distance is always between 0 and 31 (if shift value is > 32 shift is 32%value) 00000000 00000000 00000000 00100011 00000000 00000000 00000000 00011111 ----------------------------------00000000 00000000 00000000 00000011 q Threads The java.

java Conversions Bin/Hex/Octal Cast Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.073. and Octal numbers Example Code q TestShift. a right-shift is equivalent to dividing the left-hand operator by two to the power of the right-hand operator For example: 16 >> 2 = 16 / 22 = 4 00000000000000000000000000010000 00000000000000000000000000010000 00000000000000000000000000000100 00000000000000000000000000000100 -> Decimal 4 11111111111111111111111111110000 11111111111111111111111111110000 1111111111111111111111111111110000 11111111111111111111111111111100 -> Decimal -4 Decimal 16 Right-shift 2 fill left discard right Decimal -16 Right-shift 2 fill left discard right Unsigned right-shift >>> (JLS §15. You probably won't get more than one or two questions and they'll likely involve numbers under 20.janeg. the result is equivalent to the left-hand operand right-shifted by the number indicated by the right-hand operand plus two left-shifted by the inverted value of the right-hand operand For example: -16 >>> 2 = (-16 >> 2 ) + ( 2 << ~2 ) = 1.Shift Operators q q new left hand bits are filled with the value of the left-operand high-order bit therefore the sign of the left-hand operator is always retained for non-negative integers.Operators and Assignments . Hex.html (2 of 3) [15/03/2004 8:48:45 AM] .820 00000000000000000000000000010000 00000000000000000000000000010000 00000000000000000000000000000100 00000000000000000000000000000100 -> Decimal 4 11111111111111111111111111110000 11111111111111111111111111110000 0011111111111111111111111111110000 00111111111111111111111111111100 Decimal 16 Right-shift 2 fill left discard right Decimal -16 >>> 2 fill left discard right Don't panic that it will take you forever to convert a shift question on the exam.ca/scjp/oper/shift. the sign value can change if the left-hand operand is positive.741. Also see q Working with Binary.19) q q q q identical to the right-shift operator only the left-bits are zero filled because the left-operand high-order bit is not retained. the result is the same as a right-shift if the left-hand operand is negative.Java Quick Reference .

html (3 of 3) [15/03/2004 8:48:45 AM] .janeg.Java Quick Reference .Operators and Assignments .Shift Operators Method Invocation http://www.ca/scjp/oper/shift.

0 Less than or equal to: -0.awt Package The java.1) q q q q q produce a boolean result work with integers and floating-point numbers binary numeric promotion rules apply for numeric types any relational expression with NaN is false positive and negative zero are considered equal therefore -0. including boolean. the result is false unless they refer to the same String object. are the same as their mathematical equivalents Less than: Less than or equal to: Greater than: Greater than or equal to: 5 5 5 5 < <= > >= 6 5 6 5 true true false true false true false Less than: -0.0 < 0.0 is true This is not true for Math.max().0 arr1 == arr2 arr1 == arr3 arr1 != arr2 arr1 != arr3 s1 == s2 s1 == s3 true false false [different array objects] true [ref to same array object] true false true [same literal] true [same object reference] q Equals: Not Equal: Equals: Equals: Not Equal: Not Equal: Equals: Equals: http://www.0 <= 0.janeg.0 q results. and object references binary numeric promotion rules apply for numeric types if either operand is a Nan the result is false for == but true for != -0.min() and Math.0 Greater than: 5 > NaN Equality operators (== != ) (JLS § 15.Comparison Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.21) q q q q q q q produce a boolean result lower precedence than the relational operators are used to compare primitive types.Operators and Assignments .html (1 of 2) [15/03/2004 8:48:47 AM] . otherwise.0 and 0.0 <= 0.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Operators and Assignments . which treats -0.0 5 != 5. equality and the instanceof operator Relational operators ( < <= > >= ) (JLS §15.Comparison Operators q q used to compare primitive types and object references organized into three subgroups: relational. the result is true if both refer to the same object or array or if both are null if the operands are String objects.0 is false and -0.equals() method) (see String Literals) 5 == 5.0 < 0.lang Package The java. even if the two objects contain the same characters (to compare the characters in a String object use the String.0 are considered equal if the operands are object references.util Package The java.Java Quick Reference .ca/scjp/oper/comparison.20.0 as being strictly smaller than 0.

java Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www. interface or array type specified by the right-operand returns the boolean value true if: r left-operand is a class or subclass of the right-operand r left-operand is an interface or subinterface of the right-operand r left-operand is an array of the same class.2.html (2 of 2) [15/03/2004 8:48:47 AM] .janeg.ca/scjp/oper/comparison. Interface name or Array type determines if the left-operand is an instance of the class. subinterface of the right-operand array type -> true -> false -> true // arr = array of Strings // null is not an object // arr1 is an arry of int arr instanceof String[] myNull instanceof Object arr1 instanceof int[] Example Code q TestComparison. JJ pg 60) q q q q left-operand must be a reference object or null.20.Comparison Operators Equals: s1 == s4 false [s4 is new object] instanceof Type Comparison Operator (JLS §15. cannot use primitive types right-operand must be a Class.Java Quick Reference .Operators and Assignments . subclass or interface.

ca/scjp/oper/assignment.janeg.html (1 of 3) [15/03/2004 8:48:48 AM] .io Package q x += y x %= y x |= y is equivalent to is equivalent to is equivalent to x = x + y x = x % y x = x | y Rules for Simple Assignment and Object references if the left-hand operand is a class.Operators and Assignments . class C implements InA. // B is a subclass of A = new A(). is ok as class D is guaranteed to implement everything in interface A through it's implementation of InB which extends InA class A{} class B extends A{} interface InA {} interface InB extends InA {} class C implements InA {} class D implements InB {} References Miscellaneous Notes Tips & Traps Mock Exams Case Studies q SCJA Notes SCJD Notes Projects Favourite Links About Feedback // A a1 B b1 = new B(). the right-operand must be either a null. is not ok as the new C is not guaranteed to implement everything in interface InB r InA inA1 = new D(). // incompatible types http://www.lang Package The java. x oper= y is equivalent to x = x oper y For Example: Threads The java. and class D implements InB InA inA = new C(). or. is ok as class C guarantees to implement everything in interface InA InB inB = new C(). a class that implements the interface or it's superinterface r if interface InB extends InA.Assignment Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Operators and Assignments .Java Quick Reference . or of the same class or subclass type as the class of the left-operand r if class B extends class A.awt Package The java. A a = new B() is ok as class B is guaranteed to fully implement class A r B b = new A() is not ok as there is no guarantee that the new A object will implement everything in class B if the left-hand operand is an interface.util Package The java. the right-operand must be either a null.Assignment Operators q q q q q q 12 assignment operators: = *= /= %= += -= <<= >>= >>>= &= ^= |= all are right-associative ie a=b=c groups as a=(b=c) vs (a=b)=c except the simple assignment operator = which is left-associative eg a+b+c = (a+b)+c all are used with primitive data types except = and += which can be used with Strings all operators of the form op = cast their result to the type of the left-operand there is no implicit cast with the simple assignment operator = in all cases. or of the same interface or superinterface of the left-operand.

then the assignment will work.2) q an array can only be assigned to a variable of the same array type. // String arr[] = new A(). // incompatible types = null. as long as it implements what the left-operand type contract guarantees.io.3 }. C(). D(). // an Object type can take any reference = inB. of type Object. or of interface java. !!! Warning !!! q The compiler treats the object on the right-side of the assignment as if it was the same type as the object on the left-side of the assignment. // compiles ok // incompatible types // incompatible types // // // // compiles ok incompatible types compiles ok compiles ok Also see q q Conversions Sun Tech Tip: Definite Assignment http://www. intArr.2. intArr. = null. // String arr[] = inA. // // // // C implements D implements D implements incompatible InA InB InA as a superinterface types // = inB. // InA is a superinterface of InB // compile-error: incompatible types Object o1 Object o2 Object o3 C B InA c b2 inA3 = inA.html (2 of 3) [15/03/2004 8:48:48 AM] . = new Object().Assignment Operators // InA InB InA InB inA inB inA inB inA2 inB2 = = = = new new new new C(). Object // Serializable Cloneable obj inA inS inC = = = = intArr. D(). the real class of the object is always used. intArr. = new C().Operators and Assignments . of of of of object object object object a1 o1 o2 o3 -> -> -> -> Class Class Class Class B D D C // // // // declared declared declared declared type type type type was was was was Class A Object Object Object Class Class Class Class Array assignments (JLS §5. // any object reference can take a null Summary q If everything in the left-operands type contract can be met through the contract of the right-operand type.Java Quick Reference .ca/scjp/oper/assignment. At runtime. = inA. of interface Cloneable.Serializable int intArr[] = { 1. int intArr1[] = intArr.janeg. It doesn't matter if the right-operand type implements more than the left-operand type.

Operators and Assignments .Java Quick Reference .ca/scjp/oper/assignment.java Tips q a class may be assigned to an Interface type if the class implements the interface or one of it's sub-interfaces Traps q q assigning subclasses with the same parent to each other assigning a parent class to a subclass without a cast Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic Conversions Bin/Hex/Octal Cast Method Invocation http://www.janeg.html (3 of 3) [15/03/2004 8:48:48 AM] .Assignment Operators Example Code q TestAssignment.

normal binary numeric promotion applies if one of operand2 or operand3 is a null.html (1 of 2) [15/03/2004 8:48:49 AM] . one of them must be compatible (castable) to the other type a = new Class_A(). required byte if one of operand2 or operand3 is a byte.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes q q q q q SCJD Notes Projects Favourite Links About Feedback Class_A Class_B Class_C Class_A Class_C // subclass of Class_A c1 = false ? a : c. operand2 is returned.lang Package The java. // compile-error: incompatible types // returns class type of Class_B Example Code q TestTernary. c = new Class_C().janeg.util Package The java. short or char and the other is a constant int value which will fit within the other operands range. a1 = true ? b : a. the type of the return will be the type of the other operand if both operand2 and operand3 are different types. b = new Class_B(). else operand3 is returned true ? op2 : op3 // op2 returned false ? op2 : op3 // op3 returned operand1 must be a boolean type operand1 can be an expression that evaluates to a boolean type (5 == 5) ? "yes" : "no" // output: yes operand1 and operand2 must be promotable numeric types or castable object references.Ternary Operator Syntax operand1 ? operand2 : operand3 also referred to as the conditional operator if operand1 is true. the type of the returned value will be a short byte = true ? byte : short // found short. the type of the returned value will be the type of the other operand short = true ? short : 1000 // compiles and runs ok short = false ? short : 1000 // compiles and runs ok otherwise. c1. or null if one of operand2 or operand3 is a byte and the other a short.Java Quick Reference .Operators and Assignments .java http://www.ca/scjp/oper/ternary. q q q q q The java. a1 = b.Ternary Operator Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads Operators and Assignments .awt Package The java.

janeg.Java Quick Reference .ca/scjp/oper/ternary.Ternary Operator Traps q a non-boolean value or expression used for operand1 Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.Operators and Assignments .html (2 of 2) [15/03/2004 8:48:49 AM] .

b3 = true.Operators and Assignments . same chars) // true (same chars. String s0 = "Hello". // false (different boolean values) // true (same boolean values) // true (same boolean values) FYI Boolean Boolean Boolean Boolean b0.equals(s2) q // force new string object // true (diff objects.Java Quick Reference . new Boolean(true).equals(b2) b1.equals(b1) b0.util Package The java.lang.equals(b) a. new Class_B(). s0.Object therefore inherited by all classes returns true if and only if the two variables being compared hold a reference to the same object To check if objects are of the same class use the Comparison operator: instanceof Class_A Class_B Class_C Class_B Class_A a b c d e = = = = = new Class_A().Object equals() method. // compile-error: incompatible types // compile-error: incompatible types http://www. String s1 = new String("Hello").io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Operators and Assignments .equals(b3) You cannot assign values to Boolean types with either of the following constructs: Boolean b3 = new Boolean(). new Class_A().janeg.Object equals() method to return true if and only if the objects being compared contain the same sequence of characters.String overrides the java.ca/scjp/oper/equals. b1.Boolean overrides the java. b3 = b4.awt Package The java.html (1 of 2) [15/03/2004 8:48:49 AM] .equals(e) q // false (different obj refs) // false (different obj refs) // true (same object refs) // false (always returned when // compared to a null) java.lang.equals(d) a.lang.equals(s1) s0.Boolean equals() q q defined in java. b. coincidence // they are same objects) java. boolean b4 = true.lang Package The java. a. new Boolean(false).lang. returning true if and only if the Boolean objects represent the same boolean value b0 b1 b2 b3 = = = = new Boolean(true).equals(c) b.lang.Boolean equals() Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. null. String s2 = s0.

ca/scjp/oper/equals.html (2 of 2) [15/03/2004 8:48:49 AM] .janeg.equals() checks if the variables reference the same object Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic Conversions Bin/Hex/Octal Cast Method Invocation http://www.Java Quick Reference .Boolean equals() Example Code q TestBooleanEquals. the default Object.equals() method to compare the value of the objects.java Tips q all the primitive type wrapper classes override the Object.Operators and Assignments .

Java Quick Reference .next() != null ) processValue(v).Precedence Operator precdence (JPL pg 378) Operator type Postfix Unary Creation or Cast Multiplicative Additive Shift Relational Equality Bitwise AND Bitwise exclusive OR Bitwise inclusive OR Logical AND Logical OR Ternary Assignment q Operators [] . a = b = c.b) + c 5 . a = (b = c) // Result: 1 Possible problem areas q where boolean expressions are used to control loops while( v = stream.io Package References Operators and Assignments .util Package The java. int b = 5.ca/scjp/oper/precedence.Precedence Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java.lang Package The java. not 2 Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback q q q a = b = c is evaluated as int a.html (1 of 2) [15/03/2004 8:48:50 AM] .2 + 1 // Result: 4. (params) expr++ expr-++expr --expr +expr -expr ~ ! new (type)expr */% +<< >> >>> < > >= <= instanceof == != & ^ | && || ?: = += -= *= /= %= >>= <<= >>>= &= ^= |= Precedence can be overridden using parantheses 5 + 3 * 2 // Result: 11 (5 + 3) * 2 // Result: 16 when two operators of the same precedence are next to each other. associativity rules apply all binary operators (except assignment operators) are left-associative assignment is right-associative a .b + c is evaluated as (a . according to precedence rules. int c = 1.awt Package The java. evaluates as http://www.Operators and Assignments .janeg.

janeg.next() != null ) not the intended (v = stream.ca/scjp/oper/precedence.java Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.Precedence v = (stream.html (2 of 2) [15/03/2004 8:48:50 AM] .Operators and Assignments .next()) != null Example Code q TestPrecedence.Java Quick Reference .

html (1 of 2) [15/03/2004 8:48:51 AM] . there is no need to check the other operand as ¦¦ returns true if either of the operands are true q with && (i>j) evaluates to false.janeg.util Package The java.lang Package The java.Bitwise vs Logical Operators Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. the following code illustrates what can occur if you try to set the value of a variable in an if condition and you always expect the new value to be available: int i = 10.Java Quick Reference . there is no need to check the other operand as && returns true only if both operands are true.Bitwise vs Logical Operators q q the operand of every expression is evaluated before the operation is performed except for the short-circuit operators (&&. ¦¦) and ternary operator behaviour can produce unexpected results if you're not careful. if( (i<j) ¦ (i=3) > 5 ) if( (i<j) ¦¦ (i=3) > 5 ) // value of i after oper: 3 // value of i after oper: 10 if( (i>j) & (i=3) > 5 ) // value of i after oper: 3 if( (i>j) && (i=3) > 5 ) // value of i after oper: 10 q with & and ¦ both operands are always evaluated q with && and ¦¦ the second operand is only evaluated when it is necessary q with ¦¦ (i<j) evaluates to true.ca/scjp/oper/bitwiseAndLogical.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies SCJA Notes SCJD Notes Projects Favourite Links About Feedback Operators and Assignments . For example.awt Package The java. In this case one is false so there is no need to check the other operand Also see Bitwise operators Logical operators Example Code q TestBitwiseAndLogical. int j = 12.java Traps q using a new value based on a short-circuit operation that was never evaluated Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.Operators and Assignments .

Java Quick Reference .ca/scjp/oper/bitwiseAndLogical.Operators and Assignments .html (2 of 2) [15/03/2004 8:48:51 AM] .Bitwise vs Logical Operators http://www.janeg.

10. 20.Method Invocation Java Quick Reference Home SCJP2 Study Notes Language Fundamentals Operators and Assignments Flow Control and Exceptions Declarations and Access Control Garbage Collection Overloading and Overriding Threads The java. 10 20 10 10 Method invocation conversion (JLS §5.Java Quick Reference .janeg.java Traps q q q code that results in a primitive value being changed in a method (can't happen) code that results in an unchanged object value when it was changed in a method failing to cast a value to match a method parameter type ie assuming narrowing conversion http://www.awt Package The java. // where method multiplies i by 3 Output: Original value of i: Value of i in the method: Value of i after method invocation: -> 50 -> 150 -> 50 Passing object references q when you pass an object reference to a method.io Package References Miscellaneous Notes Tips & Traps Mock Exams Case Studies Operators and Assignments .lang Package The java. however.util Package The java.Operators and Assignments . a copy of the reference is passed.10.ca/scjp/oper/methods. a copy of the value is made available to the method. 10.3) SCJA Notes q SCJD Notes Projects Favourite Links About Feedback q q each argument is converted to the type of the method parameters widening conversion is implicit narrowing conversion is not implicit (values must be cast) Also see: q q Conversion Understanding that parameters are passed by value and not by reference Example Code q TestMethodInvocation. not the value itself any changes made to the value in the method do not affect the original value int i = 50. 10.html (1 of 2) [15/03/2004 8:48:52 AM] .10 } // original array changeObjectReference(array) // set the reference to a new array changeActualObject(array) // set the 2nd element of the array Output: Original array values: Array in the method: After Object reference changed in method: After object changed in method: 10. Operations in the method which change the object reference do not affect the original. changes to the object itself within the method affect the original object int[] array = { 10. 20. 20.Method Invocation q q when you pass a primitive value to a method. changeValue(i). 10.

html (2 of 2) [15/03/2004 8:48:52 AM] .ca/scjp/oper/methods.Method Invocation on a method call Conversions Bin/Hex/Octal Cast Method Invocation Promotion Bitwise Ternary Overflow Shift String Unary Comparison equals() Prefix Logical Precedence Arithmetic Assignment Bit vs Logic http://www.Operators and Assignments .janeg.Java Quick Reference .

Sign up to vote on this title
UsefulNot useful