[ANU] [DCS] [COMP2100/2500] [Description] [Schedule] [Lectures] [Labs] [Homework] [Assignments] [COMP2500] [Assessment] [PSP] [Java] [Reading] [Help]
COMP2100/2500
Lecture 6: More about JavaSummary
Some more about programming in Java, including Javadoc documentation, finding information in the API docs, some of the new features in Java 1.5, exceptions and exception handling with try and catch, the meaning of static (and the trick of including a main() in components for self-testing).
Javadoc
Javadoc is a way to write internal documentation in your Java code. The javadoc tool
can then read through your code and build HTML documentation just like the documentation for the standard libraries.Here's how you do it:
All Javadoc documentation is in comments that start with /** (note the second star) and end with */.
You can document classes, fields and methods. The Javadoc comment must be placed immediately above (Eiffel programmers take note) the thing it documents.
Javadoc comments contain introductory text followed by tagged documentation.
Introductory text should start with a summary sentence, which will be extracted and used in the summary section of the documentation. It can be as long as you like. You can use HTML tags in the text, such as <em> for emphasis, <ul> and <li> for bulleted lists, <code> for code fragments and so on. You can even include hyperlinks with the <a> tag.
Tagged documentation starts with a tag like
¶m. Here is the list of the most common tags:
Tag Description Example @paramparameter explanationThis is for documenting the parameters of a method. Use a separate tag for each parameter. For parameter substitute the name of the parameter. For explanation substitute an explanation. @param pattern a string specifying the pattern to scan@returnexplanationDocumenting the return value of a method. @return The next token.@throwsexceptionType explanationDocuments an exception that a method may throw. Use a separate tag for each exception. @throws IllegalStateException if this scanner is closed@authorNameThe author of this class. Use a separate tag for each author. @author Ian Barnes@versionVersionThe version of this class. @version 1.7The simplest way to run Javadoc is from within DrJava. You can also run it from the command line. (Demo?)
API documentation
Not much to say here. Follow the link to the Sun Java 1.5 API documentation. Notice that the whole site was created automatically from the code using Javadoc.
The meaning of “static”
First a little about the usual (non-static) context.
An ordinary method or field is associated with an instance of the class.
This is the usual way things work in object-oriented programming. All data is stored in objects, and all methods are called with a particular object as the target. We think of a method call as sending a message to that target object.
Some Java books talk about the target of a method call as the implicit parameter.
In the method call a.b(), a is the target or implicit parameter. It is the object on which the method is called.
Similarly with fields. An ordinary field is an item of data that is associated with each instance of the class. Each object has its own value for the field. For example, name might be a field for the Person class. Each Person object has its own name.
OK, so now what does static mean?
A static method or field is not associated with an instance of the class. Indeed there may not be any instances in existence. Static members are associated with the class itself.
For example, class Integer has a static method parseInt(). If you have a string like "17" (consisting of two characters, the digits '1' and '7') and you want to convert that to an integer (the number 17), you can use the expression Integer.parseInt("17"). This returns an int. There is no Integer object involved.
A frequent example is public static void main(String[] args). When you run a Java program, you tell the JVM the name of the starting class and it looks for a main() method in that class. It starts running main() without creating an instance of that class. (Eiffel people take note.) If you want an instance of the class, you have to create it with a call to a constructor.
Static fields are also associated with the class rather than an instance. This effectively makes them class-wide variables. All instances have access to them. This is useful in some circumstances, but I doubt that we'll be needing them this semester.
I'm new to Java, and from an Eiffel programmer's point of view, static fields and methods seem a bit strange. At the moment I think of it as basically being a way to do procedural programming in Java. Grouping related static methods and fields into a class that never has any instances (like the Math class in Java) is a bit like procedural programming in a modular language. (See Lecture 29 for what this means.)
This procedural style can be very convenient for small programs. I ended up using it for several of the homework exercises. (But not the last two, where you need more than one class, and many instances.) For larger Java programs I think it has a danger of making things even more confusing than they need to be. Don't over-use this feature.
By the way, the use of the word “static” in this context is a carry-over from C++, where it is a carry-over from C.
Exceptions
An exception occurs when your program encounters something unforseen. For example, a function that expects a positive number gets passed a negative argument; a method that expects a reference to a particular class of object gets a reference to some other sort of object; a Scanner is asked for its next token, but it's already at the end of the input stream.
Up to now, when this sort of thing has happened, our programs have simply crashed. For high-quality software we need a better response than that.
One problem is that when a problem is detected, the part of the code that detects it cannot know what to do about it. Should that function assume that the input was zero? Should it take the absolute value? Should it return a zero? It doesn't know, because it doesn't know what the caller plans to do with the result.
The Java exception handling mechanism allows the part of the code that detects a problem, it can throw an exception.
This passes control back to the caller, so that it can decide what to do, how to recover from the error. The exception is passed up the activation stack until it encounters an exception handler that can catch it.
Exceptions are classes in Java. For example, the static method Integer.parseInt() throws a NumberFormatException if the string it is passed does not represent an integer.
Syntax of exception handling in Java.
Throwing an exception:
if (n < 0) { IllegalArgumentException e = new IllegalArgumentException("Negative argument"); throw e; }or saving a line of code:
throw new IllegalArgumentException("Negative argument");When you throw an exception, execution of that method stops immediately, and control is returned to the caller.
There are actually two different kinds of exceptions: checked and unchecked exceptions. Don't worry too much about the difference for now. You are required to handle all checked exceptions.
Passing the buck: There are two ways to handle an exception that your code might get thrown. One is to pass the buck to the caller. You do this by adding a throws part to the signature of the method. For example, if you're reading from input using a library class that might throw you an IOException, you can pass the buck by saying throws IOException at the top, like this:
void read() throws IOException { ... }Even if it looks like it's irresponsible to pass the buck like this, it's often correct. Only catch an exception if you know how to fix the problem. Often that can only happen in higher-level routines, so exceptions get passed up several levels before they are handled.
Catching an exception: Ideally your program should handle all exceptions. Any exception that isn't caught will get passed all the way up to the top of the stack, and then your program will terminate. (That's a nice word for crash.) You don't want that.
You catch exceptions with the try ... catch ... construction. It looks like this:
try { statements that might throw an exception } catch (ExceptionClass exceptionObject) { statements that remedy the situation }For example, here's some code to read an integer from a string:
try { n = Integer.parseInt(s); } catch (NumberFormatException e) { System.out.println("That wasn't a number! I'll assume you meant zero"); n = 0; }
New features in Java 1.5
Generic types, autoboxing and auto-unboxing of primitive types, enumerated types, formatted I/O... For more information see Programming with the New Language Features in J2SE 5.0 on the Sun website.
Acknowledgement: Much of this lecture is based on material in the book Big Java by Cay Horstmann (Wiley, 2002).
[ANU] [DCS] [COMP2100/2500] [Description] [Schedule] [Lectures] [Labs] [Homework] [Assignments] [COMP2500] [Assessment] [PSP] [Java] [Reading] [Help]
Copyright © 2005, Ian Barnes, The Australian National University
Version 2005.2, Friday, 4 March 2005, 12:20:35 +1100
Feedback & Queries to
comp2100@cs.anu.edu.au