Download int

Document related concepts
no text concepts found
Transcript
CS 2410
Introduction to GUI Development in Java
Lecture 2
Transition from C++ to Java
Dr. Young-Woo Kwon
Slides from UMBC CMSC 34
Important Java Concepts and
Terminology
• JRE is the Java Runtime Environment and it creates a
virtual machine within your computer known as the
JVM (Java Virtual Machine). JRE is specific to your
platform and is the environment in which Java byte
code is run.
• JDK (formerly SDK) is the Java Development Kit.
JDK = JRE + development tools
• Java SE is the Java Platform Standard Edition, which
you will be using in this course to build stand alone
applications.
• To learn more about JDK, JRE, etc., visit
http://www.oracle.com/technetwork/
java/javase/tech/index.html
2
Important Java Concepts
• Everything in Java must be inside a class.
• Every file may only contain one public
class.
• The name of the file must be the name of
the class appended to the java extension.
• Thus, Hello.java must contain one public
class named Hello.
3
C++ File Structure
• We typically have header files (*.h, *.hpp)
and a source file (*.c, *.cpp)
• There is no coloration between the name
of the file and the classes (if any) defined
within
C++ Example – factorial.h
#ifndef _FACTORIAL_H_
#define _FACTORIAL_H_
int factorial(int n);
#endif
C++ Example – factorial.c
#include "factorial.h"
int factorial(int n) {
int result = 1;
for(int i = n; i > 0; i--) {
result *= i;
}
return result;
}
C++ Example – example1.c
#include <iostream>
#include "factorial.h"
using namespace std;
int main(int argc, char** argv) {
int n = 4;
cout << "factorial(" << n << "): "
<< factorial(n) << endl;
exit(0);
}
Running and Compiling C/C++
Project Library
for Linux
Linux
binary
C++
Code
Linux
executable
Linux C/C++ linker
Project Library
for Windows
Windows
binary
Windows
executable
Windows C/C++ linker
8
C++ Compilation
• Compilation in C++ is
done by compiling
each of the *.C files,
to produce *.o files
• The object files are
then linked to create
an executable which
can be run directly
To run:
a.out
a.out
g++ example1.o factorial.o
example1.o
g++ -c example1.C
example1.C
factorial.o
g++ -c factorial.C
factorial.H
factorial.C
Java File Structure
• No separate header file – all code is in a *.java
file
– No duplication of method signature in declaration (*.h)
and definition (*.c) to keep in sync
– No guarding of files to prevent against multiple
includes
• A file must contain a class of the same name
– By convention files/classes start with a capital letter
– Enforced consistency
• No code lives outside of any class
Java Main Signature
• Main signature is a bit different
– No return value
– Only 1 argument to main – a String array
public static void main(String[] args)
Java Factorial Example
public class Factorial {
public static void main(String[] args) {
int n = 4;
System.out.print("factorial(");
System.out.print(n);
System.out.print("): ");
System.out.println(factorial(n));
}
static int factorial(int n) {
int result = 1;
for(int i = n; i > 0; i--) {
result *= i;
}
return result;
}
}
Running and Compiling Java
Java
Code
Java
Bytecode
Java interpreter
translates bytecode to
machine code in JRE
javac Hello.java
Java compiler
Hello.java
JRE for
Linux
Hello.class
JRE for
Windows
JRE contains class libraries which are loaded at runtime.
13
Java Compilation
• In Java, *.java files are compiled into *.class files
• These *.class files contain what is known as
“bytecode”
– Bytecode does not get run directly
– Bytecode is not linked to produce an executable
– Instead, this bytecode is interpreted and executed by
another program known as the Java Virtual Machine
(JVM)
– Bytecode can be run on any platform having a JVM
Java Compilation & Execution
• *.java files are compiled using
the javac command
• The class files are then
executed using the java
command
– Note no .class specified when
running
To run:
java Factorial
Factorial.class
javac Factorial.java
Factorial.java
Methods in Java
The main method has a specific signature.
• Example: “Hello world!” Program in Java
public class Hello
{
public static void main(String args[])
{
System.out.println(“Hello world!”);
}
}
Notice no semi-colon at the end!
16
Methods in Java (cont.)
• All methods must be defined inside a class.
• Format for defining a method:
[modifiers] return_type method_name([param_type param]*)
{
statements;
}
• For main, modifiers must be public static, return type
must be void, and the parameter represents an array of
type String, String []. This parameter represents the
command line arguments when the program is executed.
The number of command line arguments in the Hello
program can be determined from args.length.
17
Static Method Invocation
•
•
•
•
Methods are invoked using the dot notation.
Methods are either static or instance methods.
Static methods do not have access to instance data.
Static methods are typically invoked using the class
name as follows:
Math.random();
18
Instance Method Invocation
• Create an instance of the class and have
object invoke method.
• System.out is an object in the System
class that is tied to standard output. We
invoke the println() and print() methods on
the object to write to standard output.
System.out.println(“Hello
world!”);
19
Instance Method Invocation
(cont.)
• The println and print methods have been
overloaded so that they can convert all 8
of Java’s primitive types to a String.
• The + sign is overloaded to work as a
concatenation operator in Java if either
operand is a String.
int x =15, y = 16;
System.out.println(x + y + “/” + x + y);
20
Instance Method Invocation
(cont.)
• To invoke an instance method, you must
first create an instance of the class (an
object) and then use the object to invoke
the method.
StringBuffer phrase;
phrase = new StringBuffer(“Java is fun”);
phrase.replace(8,11, “cool”);
System.out.println(phrase);
21
Data Types
• There are two types of data types in Java
– primitives and references.
• Primitives are data types that store data.
• References, like pointers and references
in C++, store the address of an object,
which is encapsulated data.
int x = 5;
x
5
Date d = new Date();
d
FEO3
Date
FEO3
int
Date ref
obj
22
Primitive Data Types
• Java has 8 primitive data types which
always allocate the same amount of
memory in JVM.
– Integral
•
•
•
•
byte – 8 bits
short – 16 bits
int – 32 bits – default for integer literals
long – 64 bits
int x = 5;
short y = 03;
long z = 0x23453252L;
23
Primitive Data Types (cont.)
• 8 primitive data types (cont.)
– Floating point
• double - 64 bits - default for literal decimal value
double d = 234.43;
double db = 123.5E+306;
• float - 32 bits - literal value must contain a F or f to
avoid compiler errors
float f = 32.5f;
24
Primitive Data Types (cont.)
• 8 primitive data types (cont.)
– Logical
• boolean - 1 bit
boolean a = true;
boolean b = 5 < 3;
– Textual
• char- 16 bit - Unicode
char
char
char
char
c
d
e
f
=
=
=
=
‘A’;
‘\u04a5’
‘\t’;
96;
25
Primitive Types
• Like C++, Java has a built-in boolean type
– C++ uses the keyword bool, whereas Java
used the keyword boolean
– Both use the values true and false
– Unlike C++, you cannot assign non-boolean
types into booleans
• boolean x = 1 results in a compiler error
Primitive Types
• Like C++, Java defines a character type
– Just like C++, Java uses the char keyword to
declare this type
– Character literals are defined using single
quotes such as 'a'
Primitive Types
• Integer types are pretty much the same, both
provide the following types
– A C++ short int is a Java short
– A C++ int is a Java int
– A C++ long int is a Java long
• There are no unsigned variants in Java
• Unlike C++, if you want to assign a higher
precision number into a lower precision
container you must explicitly down cast…
int i = 1234567;
short s = (short)i;
Primitive Types
• Like C++, Java has both float and double types
• The same down casting rules that applied with
integer types applies to doubles and floats also
– So if you want to assign a double into a float you must
cast it to be a float
• Additionally, Java assumes that floating point
literals are doubles by default
– If you want to create a literal you can tack on an “f” to
the literal to declare it of a float type
float f = 1234.5678f;
Reference Data Types
• Reference data types contain an address and
function like pointers without the complex syntax.
• In the following code, the second line does not call a
copy constructor, but rather you will have two
references pointing to the same object.
Date d = new Date();
Date e = d;
• Java tackled the problem of memory leaks in C++ by
– not allowing the programmer to have direct access to the
memory (i.e. no more pointer arithmetic),
– checking array bounds at runtime, and
– having a garbage collector in the JVM that periodically
reallocates memory that is not referenced.
30
Arrays
• Arrays in Java are objects. The first line of
code creates a reference for an array
object.
• The second line creates the array object.
int [] arrayRef;
arrayRef = new int[5];
arrayRef[2] = 5; arrayRef
DFO7
int [ ] ref
DFO7
0
0 Array
5 obj
0
0
31
Arrays (cont.)
• All primitive data in an array is initialized to
its zero value.
– boolean - false
– char – ‘\u0’
– byte, short, int, long, float, double – 0
• All references are initialized to null.
• All arrays have a length property that gives
you the number of elements in the array.
– args.length is determined at runtime
32
Arrays (cont.)
• An array of objects is an array of object
references until the objects are initialized.
Point pArray [] = new Point[5];
pArray[2] = new Point();
pArray
CDO8
Point [ ] ref
CDO8
null
null Array
AB12 obj
null
null
AB12
Point
obj
33
Arrays (cont.)
• Arrays may also be initialized when they
are declared using the following syntax.
int intArray[]={1,2,3,4,5};
Point pArray[]={ new Point(1,2),
new Point(3,4),
new Point(5,6) };
34
Arrays (cont.)
• Because arrays are objects and the name
of an array is its reference, arrays in Java
can grow or shrink upon reassignment.
• Also, the location of the square brackets
can change.
int [] aArr = new int[5];
int bArr [] = new int[3];
bArr = aArr; // now both are pointing
// to same array and have
// length of 5
35
Arrays (cont.)
• The System class provides an arraycopy method
that performs a shallow copy of one array to
another. Use System.arraycopy to copy an
array of primitive data, not for an array of
references.
number of
elements
System.arraycopy(srcArray, 4, destArray, 3, 2);
Index in
source
Index in
target
36
Arrays (cont.)
• The declaration of array is carried through
a comma separated list. The following
declares two integer arrays.
int [] a, b;
37
Multidimensional Arrays
• The following declares a two-dimensional
array, a reference.
int [][] twodim;
• The following creates the array with twenty
elements initialized to 0.
twodim = new int [4][5];
• The following does both at the same time.
Notice the array is not rectangular.
int [][] twodim2 = {{1,2,3}, {3,4}, {5,6,7,8}};
38
Multidimensional Arrays (cont.)
• A pictorial rendition of twodim2.
twodim2
int [ ] [ ]
ref
Array
obj of
array
refs
Array
obj
1
Array
obj
3 4
Array
obj
5 6
2 3
7 8
Each element is
an int [] ref
39
Java Naming Conventions
• Class name are in UpperCamelCase
• Member names are lowerCamelCase
• Method names are lowerCamelCase
Examples
• Classes and Interfaces
StringBuffer, Integer, MyDate
• Identifiers for methods, fields, and variables
_name, getName, setName,isName, birthDate
• Packages
java.lang, java.util, proj1
• Constants
PI, MAX_NUMBER
41
Comments
• Java supports three types of comments.
– C style /* multi-liner comments */
– C++ style // one liner comments
– Javadoc
/**
This is an example of a javadoc comment. These
comments can be converted to part of the pages
you see in the API.
*/
42
The final modifier
• Constants in Java are created using the final
modifier.
final int MAX = 9;
• Final may also be applied to methods in which case
it means the method can not be overridden in
subclasses.
• Final may also be applied to classes in which case it
means the class can not be extended or subclassed
as in the String class.
43
Packages
• Only one package per file.
• Packages serve as a namespace in Java and
create a directory hierarchy when compiled.
• Classes are placed in a package using the
following syntax in the first line that is not a
comment.
package packagename;
package packagename.subpackagename;
44
Packages (cont.)
• Classes in a package are compiled using
the –d option.
• On the following slide, you will find the
command to compile the code from the
Proj1/src directory to the Proj1/bin
directory.
45
Packages (cont.)
• It is common practice to duplicate the
package directory hierarchy in a directory
named src and to compile to a directory
named bin.
Proj1
src
The following command is run from the src directory:
proj1
gui
javac –d ../bin proj1/gui/Example.java
Example.java
bin
proj1
gui
Example.class
46
Packages (cont.)
• By default, all classes that do not contain a package
declaration are in the unnamed package.
• The fully qualified name of a class is the
packageName.ClassName.
java.lang.String
• To alleviate the burden of using the fully qualified
name of a class, people use an import statement
found before the class declaration.
import java.util.StringBuffer;
import java.util.*;
47
Packages
• Like C++, Java provides a mechanism to
organize code
• Packages are similar to namespaces in
C++ but have different syntax and
conventions
• In Java classes need not be explicitly be
under a package, in which case the default
package will be used
– Though, this practice is discouraged
Namespaces in C++
namespace A {
class Foo {
// minimal class
};
}
int main(int argc, char** argv){
A::Foo aFoo();
return 0;
}
Packaging Conventions
• Typically package names consist of lowercase
letters and/or numbers
• Multiple words are usually separated by periods
• In the real world most projects use something
called reverse domain name notation
– edu.usu.cs.cs2410.ClassName
• Use this as another method to group your code
into logical chunks
Using a Package
• Using a file in a package is very similar to
that of C++
– In C++ we might have something like…
#include <sys/socket.h>
– In Java, the syntax is different – we use the
import keyword, drop the angle brackets, and
the file extension
import java.util.Date;
Fields and Methods
• In Java you have fields and methods. A field is
like a data member in C++.
• Method is like a member method in C++.
• Every field and method has an access level. The
public, private, and protected keywords have the
same functionality as those in C++.
–
–
–
–
public
protected
private
(package)
52
Access Control
Modifier
Same class
Same
package
Subclass
Universe
private
default
protected
public
53
Access Control for Classes
• Classes may have either public or
package accessibility.
• Only one public class per file.
• Omitting the access modifier prior to class
keyword gives the class package
accessibility.
54
Classes
• In Java, all classes at some point in their
inheritance hierarchy are subclasses of
java.lang.Object, therefore all objects have
some inherited, default implementation
before you begin to code them.
– String toString()
– boolean equals(Object o)
55
Classes (cont.)
• Unlike C++ you must define the
accessibility for every field and every
method. In the following code, the x is
public but the y gets the default
accessibility of package since it doesn’t
have a modifier.
public
int x;
int y;
56
Java Differences
• Since Java doesn’t split the declaration
and implementation, all code is inline
• No semi-colon at the end of the class
declaration
• Access explicitly attached to each method
• this is not a pointer, but a reference, so we
use the this. instead of this-> notation
C++ Class Declaration
#ifndef _DATE_H_
#define _DATE_H_
class Date {
private:
int m_month;
int m_day;
int m_year;
public:
Date(int month, int day, int year);
int GetMonth() const;
int GetDay() const;
int GetYear() const;
void SetMonth(int month);
void SetDay(int day);
void SetYear(int year);
};
#endif
C++ Class Definition
#include "Date.H"
Date::Date(int month,
int day,
int year) {
this->m_month = month;
this->m_day = day;
this->m_year = year;
}
int Date::GetMonth() const {
return this->m_month;
}
int Date::GetDay() const {
return this->m_day;
}
int Date::GetYear() const {
return this->m_year;
}
void Date::SetMonth(int month) {
this->m_month = month;
}
void Date::SetDay(int day) {
this->m_month = day;
}
void Date::SetYear(int year) {
this->m_year = year;
}
Java Class Declaration & Definition
public class Date {
public int getYear() {
return this.year;
}
private int month;
private int day;
private int year;
public void setMonth(int month) {
this.month = month;
}
public Date(int month,
int day,
int year) {
this.month = month;
this.day = day;
this.year = year;
}
public int getMonth() {
return this.month;
}
public int getDay() {
return this.day;
}
public void setDay(int day) {
this.day = day;
}
public void setYear(int year) {
this.year = year;
}
}
Instance and Local Variables
• Unlike C++ you must define everything
within a class.
• Like C++,
– variables declared outside of method are
instance variables and store instance or
object data. The lifetime of the variable is the
lifetime of the instance.
– variables declared within a method, including
the parameter variables, are local variables.
The lifetime of the variable is the lifetime of
the method.
61
Static Variables
• A class may also contain static variables
and methods.
• Similar to C++…
– Static variables store static or class data,
meaning only one copy of the data is shared
by all objects of the class.
– Static methods do not have access to
instance variables, but they do have access to
static variables.
– Instance methods also have access to static
variables.
62
Instance vs. Static Methods
• Static methods
– have static as a modifier,
– can access static data,
– can be invoked by a host object or simply by using the
class name as a qualifier.
• Instance methods
–
–
–
–
can access static data,
can access instance data of the host object,
must be invoked by a host object,
contain a this reference that stores the address of host
object.
63
Pass By Value or By
Reference?
• All arguments are passed by value to a method.
However, since references are addresses, in
reality, they are passed by reference, meaning…
– Arguments that contain primitive data are passed by
value. Changes to parameters in method do not effect
arguments.
– Arguments that contain reference data are passed by
reference. Changes to parameter in method may
effect arguments.
64
Constructors
• Similar to C++, Java will provide a default (no
argument) constructor if one is not defined in the
class.
• Java, however, will initialize all fields (object or
instance data) to their zero values as in the array
objects.
• Like C++, once any constructor is defined, the
default constructor is lost unless explicitly
defined in the class.
65
Constructors (cont.)
• Similar to C++, constructors in Java
–
–
–
–
have no return value,
have the same name as the class,
initialize the data,
and are typically overloaded.
• Unlike C++, a Java constructor can call another
constructor using a call to a this method as the
first line of code in the constructor.
66
Expressions and Control Flow
• Java uses the same operators as C++. Only
differences are
– + sign can be used for String concatenation,
– logical and relative operators return a boolean.
• Same control flow constructs as C++, but
expression must return a boolean.
– Conditional
• if(<boolean expression>){…}else if(<boolean
expression>){…}else{…}
• switch(variable){case 1: …break; default:…}
– Variable must be an integral primitive type of size int or smaller,
or a char
67
Control Flow Constructs (cont.)
• Iterative
– while (<boolean expression>) { … }
– do { … } while (<boolean expression>);
– for( <initialize>; <boolean expression>;
<update>) { … }
– break and continue work in the same way
as in C++.
– May use labels with break and continue as
in C++.
68
Control Flow Constructs (cont.)
•
Enhanced for loop since Java 5 for iterating over arrays and collections.
public class EnhancedLoop
{
public static void main(String []a )
{
Integer [] array = {new Integer(5),6,7,8,9};
for (int element: array){
element is a local variable
element+= 10;
System.out.println(element);
}
for (int element: array){
System.out.println(element);
}
}
}
69
C++ Inheritance
• In C++ we can extend a class, by
specifying the superclasses using a “:”
notation at the time of declaration
C++ Inheritance
• Base Vehicle class (header)…
#ifndef _VEHICLE_H_
#define _VEHICLE_H_
#include <string>
using namespace std;
class Vehicle {
private:
string m_make;
string m_model;
public:
Vehicle(string make, string model);
string GetMake() const;
string GetModel() const;
};
#endif
C++ Inheritance
• Base Vehicle class (implementation)…
#include "Vehicle.H"
#include <iostream>
using namespace std;
Vehicle::Vehicle(string make, string model) {
this->m_make = make;
this->m_model = model;
}
string Vehicle::GetMake() const {
return this->m_make;
}
string Vehicle::GetModel() const {
return this->m_model;
}
C++ Inheritance
• A derived Car class (header)…
#ifndef _CAR_H_
#define _CAR_H_
#include "Vehicle.H"
#include <string>
using namespace std;
class Car : public Vehicle {
private:
bool m_fourWheelDrive;
public:
Car(string make, string model, bool fourWheelDrive);
bool HasFourWheelDrive() const ;
};
ostream& operator << (ostream& os, const Car& c);
#endif
C++ Inheritance
• A derived Car class (implementation)…
#include "Car.H"
#include <iostream>
using namespace std;
Car::Car(string make, string model, bool fourWheelDrive): Vehicle(make, model) {
this->m_fourWheelDrive = fourWheelDrive;
}
bool Car::HasFourWheelDrive() const {
return this->m_fourWheelDrive;
}
ostream& operator << (ostream& os, const Car& c) {
os << (c.HasFourWheelDrive() ? "4WD" : "2WD") << " "
<< c.GetMake() << " " << c.GetModel();
return os;
}
C++ Inheritance
• A derived Airplane class (header)…
#ifndef _AIRPLANE_H_
#define _AIRPLANE_H_
#include "Vehicle.H"
#include <string>
using namespace std;
class Airplane : public Vehicle {
private:
string m_varient;
public:
Airplane(string make, string model, string varient);
string GetVarient() const;
};
ostream& operator << (ostream& os, const Airplane& a);
#endif
C++ Inheritance
• A derived Airplane class (implementation)…
#include "Airplane.H"
#include <iostream>
using namespace std;
Airplane::Airplane(string make,string model,string varient): Vehicle(make, model){
this->m_varient = varient;
}
string Airplane::GetVarient() const {
return this->m_varient;
}
ostream& operator << (ostream& os, const Airplane& a) {
os << a.GetMake() << " " << a.GetModel() << " "
<< a.GetVarient();
return os;
}
Java Inheritance
• Uses the extend keyword instead of the “:”
notation
• See access table for visibility of members
in base class
• Use super() to invoke base class
constructor
• Use super.method() notation to invoke a
method on the base class
Java Inheritance
• A Vehicle base class…
public class Vehicle {
private String make;
private String model;
public Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
}
Java Inheritance
• A derived Car class…
public class Car extends Vehicle {
private boolean fourWheelDrive;
public Car(String make, String model, boolean fourWheelDrive) {
super(make, model);
this.fourWheelDrive = fourWheelDrive;
}
public boolean hasFourWheelDrive() {
return this.fourWheelDrive;
}
public String toString() {
return (this.fourWheelDrive ? "4WD" : "2WD") + " " +
this.getMake() + " " + this.getModel();
}
}
Java Inheritance
• A derived Airplane class…
public class Airplane extends Vehicle {
private String varient;
public Airplane(String make, String model, String varient) {
super(make, model);
this.varient = varient;
}
public String getVarient() {
return this.varient;
}
public String toString() {
return this.getMake()+" "+this.getModel()+" "+ this.varient;
}
}
Java Inheritance
Vehicle
• Java avoids the
“diamond problem” by
not permitting multiple
inheritance
Car
Airplane
AirplaneCar
Interface
• Java provides a construct known as an
Interface
– Similar to a pure virtual class in C++
– Classes in Java “implement” may implement
one or more interfaces
– Interfaces typically define a set of operations
(method signatures) which the class must
implement
– Interfaces my have static members
Interface
• Why use interfaces?
– Interfaces are good for defining the set of
operations a given type of structures should
implement
– This is a good practice, as it allows you to
swap out/in anything that implements that
interface with minimal code changes
– Even more powerful when utilized in
conjunction with Java’s version of templates
Java Interface Example
• A simple Java Interface declaration…
public interface Animal {
public void talk();
}
• Note that this is of type interface, not class
Java Interface Example
• A Cat class which implements this
interface…
public class Cat implements Animal {
public void talk() {
System.out.println("Meow");
}
}
Java Interface Example
• A Cat class which implements this
interface…
public class Dog implements Animal {
public void talk() {
System.out.println("Arrrfff!");
}
}
Java Interface Example
• The driver class…
public class Kennel {
public static void main(String[] args) {
Animal[] kennel = {new Cat(), new Dog()};
for(Animal a : kennel) {
a.talk();
}
}
}
• Note that we never have a handle on these animals as a
Cat or Dog, just an animal
– As long as we call just the Animal interface methods, we can add
as many Animal types as we want and not need to change any
code
Exceptions
• Java handles exceptions like C++.
– Place try block around problem code and a catch block
immediately following try block to handle exceptions.
• Different from C++…
– Java uses a finally block for code that is to be executed
whether or not an exception is thrown.
– Java has a built-in inheritance hierarchy for its exception
classes which determines whether an exception is a
checked or an unchecked exception.
– You may declare that a method throws an exception to
handle it. The exception is then passed up the call stack.
– Java forces the programmer to handle a checked
exception at compile time.
88
Exception Hierarchy
• Unchecked exceptions are derived from
RuntimeException. Checked exceptions
are derived from Exception. Error are also
unchecked exceptions, but may not derive
from it.
Throwable
Error
Exception
checked
unchecked
unchecked
IOException
RuntimeException
checked
89
Handling the Exception
Example
public class HandleExample
{
public static void main(String args[])
{
try {
String name = args[0];
System.out.println(args[0]);
} catch (IndexOutOfBoundsException e){
System.out.println(“Please enter name ” +
“after java HandleExample”);
} finally {
System.out.println(“Prints no matter what”);
}
}
}
90
Passing up the Exception
• In Java you may pass the handling of the exception
up the calling stack by declaring that the method
throws the exception using the keyword throws.
• This is necessary for compilation if you call a
method that throws a checked exception such as
the Thread.sleep method.
• The Java API lists the exceptions that a method
may throw. You may see the inheritance hierarchy
of an exception in the API to determine if it is
checked or unchecked.
91
Passing up the Exception
Example
public class PassUpExample
{
public static void main(String [] args){
System.out.println(“Hello”);
main is obligated to handle
try
the exception since it is a
{
passback();
checked exception
}catch(InterruptedException e)
{
System.out.println(“Caught InterruptedException”);
}
This method passes
System.out.println(“Goodbye”);
exception up call stack
}
public static void passback() throws InterruptedException
{
Thread.sleep(3000);
This method throws
}
a checked exception
}
92
Javadoc Comments
• Like C++, Java supports both C style (/* */) and
C++ style end of line comments
• However, Java introduces another type of
comment style know as a Javadoc comment
/**
* This is a javadoc comment
*/
• These special can be analyzed by the javadoc
tool and HTML documentation can be
automatically generated
Javadoc Tags
• The first sentence in the Javadoc comments is used to
provide a high-level description of that
member/method/class
• The rest of the paragraph will be shown in a more
detailed section in the generated documentation
• Additionally, Javadoc supports tags which identify the
attributes of the function such as…
– @param name description
– @return description
• See the following for more details about javadoc…
– http://docs.oracle.com/javase/7/docs/technotes/tools/windows/ja
vadoc.html
A Javadoc Example
/**
* This function takes in a Celsius temperature and
* returns its Fahrenheit equivalent.
*
* @param celsius degrees Celsius to be converted
* @return the Fahrenheit equivalent
*
of the Celsius temperature provided
*/
public double celsiusToFahrenheit(double celsius) {
return 9.0 / 5 * celsius + 32;
}
Javadoc Generation
• To generate the Javadoc generation you
need to run the javadoc tool
$ javadoc Test.java
Loading source file Test.java...
Constructing Javadoc information...
Standard Doclet version 1.6.0_02
Building tree for all the packages and classes...
Generating Test.html...
Generating package-frame.html...
Generating package-summary.html...
Generating package-tree.html...
Generating constant-values.html...
Building index for all the packages and classes...
Generating overview-tree.html...
Generating index-all.html...
Generating deprecated-list.html...
Building index for all classes...
Generating allclasses-frame.html...
Generating allclasses-noframe.html...
Generating index.html...
Generating help-doc.html...
Generating stylesheet.css...
$
Generated HTML Documentation
• Example method listed in method summary…
• Detailed method description…