JavaPrimer
JavaPrimer
Topic 0
Java Primer
Reading: Lambert and Osborne, Appendix A & Sections 1.2 and 2.1–2.7
c Tim French
! CITS2200 Java Primer Slide 1
1. Review of Java Basics
c Tim French
! CITS2200 Java Primer Slide 2
1.2 Local Variables
Result?
c Tim French
! CITS2200 Java Primer Slide 3
1.3 Expressions
arithmetic: +, -, *, /, %,...
c Tim French
! CITS2200 Java Primer Slide 4
1.4 Control Statements
if and if-else
if (<boolean expression>)
<statement>
if (<boolean expression>)
<statement>
else
<statement>
c Tim French
! CITS2200 Java Primer Slide 5
while, do-while, and for
do
<statement>
while (<boolean expression>)
c Tim French
! CITS2200 Java Primer Slide 6
Example
0
1
2
3
c Tim French
! CITS2200 Java Primer Slide 7
Arrays
Declaration
<type>[] <name>;
<type>[]...[] <name>;
Instantiation
Example
int[][] matrixArray;
c Tim French
! CITS2200 Java Primer Slide 8
1.5 Methods
Methods have the form (ignoring access modifiers for the moment)
Example
c Tim French
! CITS2200 Java Primer Slide 9
Parameters are passed by value:
// a method...
void increment (int i) {i++;}
Result?
c Tim French
! CITS2200 Java Primer Slide 10
2. Primitive Types vs Reference Types
Primitive types
• fixed size
• size doesn’t change with reassignment
⇒ store value alongside variable name
c Tim French
! CITS2200 Java Primer Slide 11
i
integer i = 15;
15
Object
Object b = new Object(); b Fields
⇒ reference types
c Tim French
! CITS2200 Java Primer Slide 12
int[] a = {0,1,2,3};
int[] b = a;
b[0]++;
System.out.println(a[0]);
Result?
// a method...
void incrementAll (int[] a) {
for (int i=0; i<a.length; i++) a[i]++;
}
Result?
c Tim French
! CITS2200 Java Primer Slide 13
3. Classes and Objects
Aside from a few built-in types (arrays, strings, etc) all reference types are defined
by a class.
A class is a chunk of software that defines a type, its attributes or instance variables
(also known as member variables), and its methods. . .
c Tim French
! CITS2200 Java Primer Slide 14
class Box {
// instance variables
double width, length, height;
// constructor method
Box (double w, double l, double h) {
width = w;
length = l;
height = h;
}
// additional method
double volume () {return width * length * height;}
}
c Tim French
! CITS2200 Java Primer Slide 15
3.2 Constructors
The runtime engine creates an object or instance of the class each time the new
keyword is executed:
c Tim French
! CITS2200 Java Primer Slide 16
3.3 Different Kinds of Methods
c Tim French
! CITS2200 Java Primer Slide 17
3.4 Packages
In Java:
package myMaths;
class Matrix {
...
If you don’t specify a package Java will make a default package from all classes in
the directory.
c Tim French
! CITS2200 Java Primer Slide 18
Using someone else’s package
package myMaths;
import java.io.*;
class Matrix {
...
c Tim French
! CITS2200 Java Primer Slide 19
3.5 Access Modifiers
c Tim French
! CITS2200 Java Primer Slide 20
3.6 The static Keyword
Used for methods and variables in classes that don’t create objects, or for variables
shared by all instances of a class.
Example:
static Matrix m;
c Tim French
! CITS2200 Java Primer Slide 21
Also used for “constants”.
Example:
c Tim French
! CITS2200 Java Primer Slide 22
4. Class Hierarchies
Example:
c Tim French
! CITS2200 Java Primer Slide 23
public class Shape {
...
}
c Tim French
! CITS2200 Java Primer Slide 24
public class Circle extends Shape {
While we will not be using hierarchies extensively in this unit, we will be using some
very important features of them...
c Tim French
! CITS2200 Java Primer Slide 25
1. Any superclass reference (variable) can hold and access a subclass object.
Example:
public class ShapeTest {
c Tim French
! CITS2200 Java Primer Slide 26
2. All Java classes are (automatically) subclasses of Object
Example:
Object holdsAnything;
holdsAnything = new Circle();
holdsAnything = new Rectangle();
holdsAnything = new Shape();
Example:
Object[] arrayOfAnythings = new Object[10];
arrayOfAnythings[0] = new Circle();
arrayOfAnythings[1] = new Rectangle();
arrayOfAnythings[2] = new Shape();
c Tim French
! CITS2200 Java Primer Slide 27
Java provides wrappers for all primitives to allow them to be treated as Objects:
Note: A new feature in Java 1.5 is autoboxing — automatic wrapping and unwrap-
ping of primitives.
c Tim French
! CITS2200 Java Primer Slide 28
4.1 Casting
Example:
o1 = c1; // OK
c1 = o1; // Error
c Tim French
! CITS2200 Java Primer Slide 29
In the last statement, even though o1 is now “holding” something that was created
as a Character, its reference (ie its class) is Object.
To get the “Character” back, we have to cast it back down the hierarchy:
o1 = c1; // OK
c1 = (Character) o1; // OK - casted back to Character
c Tim French
! CITS2200 Java Primer Slide 30
4.2 Object Oriented Programming in Java
c Tim French
! CITS2200 Java Primer Slide 31
To demonstrate these properties, let’s reconsider the Shape example. This time,
we first define a class Point...
c Tim French
! CITS2200 Java Primer Slide 32
...and use Point to define Shape. This is encapsulation.
private Point p;
c Tim French
! CITS2200 Java Primer Slide 33
Circle inherits from Shape...
c Tim French
! CITS2200 Java Primer Slide 34
as does Rectangle. This demonstrates inheritance.
c Tim French
! CITS2200 Java Primer Slide 35
We can now treat Rectangles and Circles as the more general type Shape:
Example:
c Tim French
! CITS2200 Java Primer Slide 36
Note:
• We did not need to specify how a Shape’s area is calculated. This means that
we are never able to construct just a Shape.
• We chose to encapsulate a Point, rather than inherit from it (a shape is not a
point). Inheritance should be used sparingly. Always consider composition first.
• Once Circles and Rectangles can be treated as shapes we can have an array
that contains both.
• The method area() was different for both shapes, but we did not need to cast.
The Java virtual machine will determine which method is called.
• A good example of inheritance in the API is java.awt (e.g., a Window is a
Container which is a Component which is an Object). However, in general
inheritance hierarchies should be fairly shallow.
c Tim French
! CITS2200 Java Primer Slide 37
5. Interfaces and Abstract Classes
An interface:
c Tim French
! CITS2200 Java Primer Slide 38
Example:
c Tim French
! CITS2200 Java Primer Slide 39
Classes can implement an interface:
Implementation 1:
c Tim French
! CITS2200 Java Primer Slide 40
Why use interfaces?
Example:
Matrix[] myMatrixHolder = new Matrix[10];
myMatrixHolder[0] = new MatrixReloaded(2,2);
myMatrixHolder[1] = new MatrixRevolutions(20,20);
...
myMatrixHolder[0] = myMatrixHolder[1];
c Tim French
! CITS2200 Java Primer Slide 41
2. Specifies the methods that any implementation must implement.
Example:
Matrix[] myMatrixHolder = new Matrix[10];
myMatrixHolder[0] = new MatrixReloaded(2,2);
myMatrixHolder[1] = new MatrixRevolutions(20,20);
...
for (int i=0; i<10; i++)
myMatrixHolder[i].transpose();
c Tim French
! CITS2200 Java Primer Slide 42
This is an important software engineering facility
eg. the Collection interface, also Runnable, Throwable, Iterable, and List.
c Tim French
! CITS2200 Java Primer Slide 43
6. Exceptions
c Tim French
! CITS2200 Java Primer Slide 44
Example program
Output
c Tim French
! CITS2200 Java Primer Slide 45
We can throw exceptions ourselves.
if (<condition>)
throw new <exception type> (<message string>);
Example:
c Tim French
! CITS2200 Java Primer Slide 46
Two types of exceptions:
try {
codeThatThrowsException();
}
catch(Exception e) {
codeThatDealsWithException(e);
}
c Tim French
! CITS2200 Java Primer Slide 47
Compiling and running Java
There are various ways to compile and run Java, but the command line is the most
ubiquitous. The command:
will create the file myClass.class in the current directory. The command:
c Tim French
! CITS2200 Java Primer Slide 48
Objects and Generic Data Structures
/**
* Block representation of a queue (of objects).
*/
public class QueueBlock {
The above queue is able to hold any type of object — that is, an instance of any
subclass of the class Object. (More accurately, it can hold any reference type.)
But there are some commonly used things that are not objects — the primitive
types.
In order to use the queue with primitive types, they must be “wrapped” in an object.
Recall from Topic 4 that Java provides wrapper classes for all primitive types.
c Tim French
! CITS2200 Java Primer Slide 50
Autoboxing — Note for Java 1.5
Integer i = 5;
int j = i;
However:
• Not a change to the underlying language — the compiler recognises the mis-
match and substitutes code for you:
Integer i = Integer.valueOf(5)
int j = i.intValue();
c Tim French
! CITS2200 Java Primer Slide 51
• Can lead to unintuitive behaviour. Eg:
Long w1 = 1000L;
Long w2 = 1000L;
if (w1 == w2) {
// do something
}
may not work. Why?
• Can be slow. Eg. if a, b, c, d are Integers, then
d = a * b + c
becomes
d.valueOf(a.intValue() * b.intValue() + c.intValue())
http://chaoticjava.com/posts/autoboxing-tips/
c Tim French
! CITS2200 Java Primer Slide 52
6.2 Casting
Recall that in Java we can assign “up” the hierarchy — a variable of some class
(which we call its reference) can be assigned an object whose reference is a subclass.
However the converse is not true — a subclass variable cannot be assigned an object
whose reference is a superclass, even if that object is a subclass object.
This issue occurs more subtly when using ADTs. Recall our implementation of a
queue. . .
c Tim French
! CITS2200 Java Primer Slide 53
public class QueueBlock {
private Object[] items; // array of Objects
...
public Object dequeue() throws Underflow { // returns an Object
if (!isEmpty()) {
Object a = items[first];
first++;
return a;
}
else...
Consider the calling program:
c Tim French
! CITS2200 Java Primer Slide 54
The queue holds Objects. Since String is a subclass of Object, the queue can
hold a String, but its reference in the queue is Object. (Specifically, it is an
element of an array of Objects.)
The last statement therefore asks for something with reference Object (the super-
class) to be assigned to a variable with reference String (the subclass), which is
illegal.
c Tim French
! CITS2200 Java Primer Slide 55
6.3 Generics
Java 1.5 provides an alternative approach. Generics allow you to specify the type
of a collection class:
Like autoboxing, generics are handled by compiler rewrites — the compiler checks
that the type is correct, and substitutes code to do the cast for you.
c Tim French
! CITS2200 Java Primer Slide 56
Writing Generic Classes
/**
* A simple generic block stack for
* holding object of type E
**/
class Stack<E> {
c Tim French
! CITS2200 Java Primer Slide 57
Using Generic Classes
c Tim French
! CITS2200 Java Primer Slide 58
How Generics Work
The program:
at compile time. Generics allow the compiler to ensure that the casting is correct,
rather than the runtime environment.
c Tim French
! CITS2200 Java Primer Slide 59
Some Tricks with Generics...
c Tim French
! CITS2200 Java Primer Slide 60
Generics in Java are complex and are the subject of considerable debate. While you
may not need to write them often, it is important you understand them as the Java
Collection classes all use generics.
http://www-128.ibm.com/developerworks/java/library/
j-jtp01255.html
http://weblogs.java.net/blog/arnold/archive/2005/06/
generics_consid_1.html
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
c Tim French
! CITS2200 Java Primer Slide 61