february 11, 1999cspp503 week 6 bring on the caffeine cspp503 week 6
TRANSCRIPT
February 11, 1999 CSPP503 Week 6
Bring on the Caffeine
CSPP503
Week 6
February 11, 1999 CSPP503 Week 6
Are You Java’s Type?
• Type: a set of values that are semantically similar
• Java is a strongly typed language– Every variable and every expression has a
type that is known at compile time.
– Strong typing helps detect errors at compile time.
February 11, 1999 CSPP503 Week 6
Inside a Primitive Type• Actual values for integral types:
byte: -128 to 127
short: -32768 to 32767
int: -2147483648 to 2147483647
long: -9223372036854775808 to 9223372036854775807
char: from '\u0000' to '\uffff’ (from 0 to 65535)
• Why use int instead of long?
February 11, 1999 CSPP503 Week 6
Building a Boolean from a Number• Can’t say (why not?):if (x) System.out.println(“Congratulations, it’s a Boole!”);
• Convert an integer x (following the C language convention that any nonzero value is true):
if (x != 0) System.out.println(“Congratulations, it’s a Boole!”);
February 11, 1999 CSPP503 Week 6
Building a Boolean from an Object
• Object reference obj can be converted (any reference other than null is true): obj! = null
February 11, 1999 CSPP503 Week 6
The Other Kind of Type
• Reference types– Variables of reference types don’t hold
values, but references to values– Classes, interfaces and arrays are all
reference types
February 11, 1999 CSPP503 Week 6
A Graphical View
0010010
1110010
int counter
Airport midway
The data of the midway object
February 11, 1999 CSPP503 Week 6
Classes, Interfaces and Arrays, oh my!
• Classes we’ve already seen• Interfaces are programming contracts
– An interface is a set of constants and methods
– In Java, a class implements an interface
February 11, 1999 CSPP503 Week 6
Implementing an Interface• An example from the Comparison
applet:public class Comparison extends Applet implements ActionListener
• Comparison promises to do everything an ActionListener does
February 11, 1999 CSPP503 Week 6
Comparison Does What It Has To
• What does an ActionListener have to do?actionPerformed public abstract void actionPerformed(ActionEvent e)
• Provides an implementation for the interface:public void actionPerformed(ActionEvent e) { number1 = Integer.parseInt(input1.getText() );
number2 = Integer.parseInt(input2.getText() );
repaint();
}
February 11, 1999 CSPP503 Week 6
Comparison Object has Two Types
• Comparison is a class that implements an interface:
public class Comparison extends Applet implements ActionListener
February 11, 1999 CSPP503 Week 6
Interface Type Example
• From the Comparison applet:input2 = new TextField( 10 );
input2.addActionListener( this );
add( input2 ); // put input2 on applet
• What is addActionListener()?public synchronized void addActionListener(ActionListener l)
February 11, 1999 CSPP503 Week 6
Sideline Events• Events are things that happen to programs
(other than errors)// Process user's action on the input2
// text field
public void actionPerformed(ActionEvent e) {
number1 = Integer.parseInt( input1.getText() );
number2 = Integer.parseInt( input2.getText() );
repaint();
}
February 11, 1999 CSPP503 Week 6
Class ? Type
• Variables have types• Objects (and arrays) don’t have a type,
but belong to a class• Usually we’ll consider them the same
February 11, 1999 CSPP503 Week 6
Casting Against Type• A value could be two different types
– Is 12 an int or a float?
• Compiler isn’t smart, so it’s conservative (signals an error)
• Override the compiler with a cast– Cast says: Treat this variable as the type I
say– To cast in Java, write:
(newType) variable
February 11, 1999 CSPP503 Week 6
Examples of casting
// Casting a float literal to a type int.
// Without the cast operator, this would be a
// compile-time error, because it’s a narrowing
// conversion:
int i = (int)12.5f;
// From class average applet (Figure 2.9)
if ( counter != 0 ) {
average = (double) total / counter;
System.out.println( "Class average is " + average );
} else ...
February 11, 1999 CSPP503 Week 6
Can’t Always Cast
• Can’t do this:if ((boolean) x) System.out.println(“Congratulations, it’s a Boole!”);
• Sometimes casts are automatic, and are called conversions
February 11, 1999 CSPP503 Week 6
One of Two Ways
• Create an expression in a context where the type of the expression is not appropriate and either:– Error at compile time (if statement has
any type other than boolean)– May be able to accept a type that is related
to the type of the expression
February 11, 1999 CSPP503 Week 6
Funky Conversions• What does this print?
class Test {public static void main(String[] args) {
int big = 1234567890; float approx = big; System.out.println(big -(int)approx);}
}
February 11, 1999 CSPP503 Week 6
What’s an Array
• An array is a group of values of the same type (usually stored in consecutive memory locations)
• Arrays are objects– Can be assigned to variables of type
Object
• Dynamically created
February 11, 1999 CSPP503 Week 6
An Array of Examples
From Figure 5.3
int n[]; // declare an array of integers
// initialize instance variables
public void init() {
n = new int[ 10 ]; //dynamic allocation
}
February 11, 1999 CSPP503 Week 6
The Declaration of Array
Array declarations
int[] ai; // array of intshort[][] as; // array of array of short
Object[] ao, // array of Object otherAo; // array of Object
February 11, 1999 CSPP503 Week 6
Declaring Arrays
• Can’t specify the length in a declarationint test [] = new int [100]; // Okay
int test2 [100]; // No good
int test3 [100]=new int [100]; // No good
February 11, 1999 CSPP503 Week 6
Some Array Definitions
These create array objects:
Exception ae[] = new Exception[3]; Object aao[][] = new Exception[2][3];int[] factorial = { 1, 1, 2, 6, 24 };String[] aas = {"array", "of", "String"};
February 11, 1999 CSPP503 Week 6
An Array Exampleint face;int frequency[];
// initialize instance variablespublic void init() { frequency = new int[ 7 ];
for (int roll=1; roll <= 6000; roll++ ) { face = 1 + (int) (Math.random() * 6 ); ++frequency[ face ]; }}
February 11, 1999 CSPP503 Week 6
An Array of Observations• Arrays know their own length
test.length == 100– What kind of loops do we usually use with
arrays?• Arrays start at index 0
– Last index == ??
• Arrays must be indexed by int values (short, byte, or char are okay, but long is no good)
February 11, 1999 CSPP503 Week 6
Operating on an Array
• Square brackets are an operator• Brackets have very high precedence
– Same as ()’s
• Example-17*studentGrades[12] * 2
February 11, 1999 CSPP503 Week 6
"Can he do that?"
• What’s wrong with the following code?
int scores[] = {98, 76, 84, 97, 101, 78};
int counter=0;
for (; counter <= scores.length; counter++) {
System.out.println("Test #" + counter +
": " + scores[counter]);
}
February 11, 1999 CSPP503 Week 6
Array Initializers
• Use {}’s to set initial values– int grades[] = {87, 92, 76, 94}
February 11, 1999 CSPP503 Week 6
Searching & Sorting Data
• The Second Law of Thermodynamics• Sorting restores order to the world• Sorting in everyday life
– Bank checks by account
• Searching is easier when sorted– Reverse directories of phone numbers
February 11, 1999 CSPP503 Week 6
Sorting in Computers
• Usually start with an array of items to be sorted– Integers– Social Security numbers– Last names and first names
• Lots of data– All the SSN’s in the U.S.– All of GM’s employees
February 11, 1999 CSPP503 Week 6
Different Ways to Sort
• Bubble sort– Compare two neighbors, swap if out of
order
1 2 5 4 7 8 6
1 2 4 5 7 8 6
1 2 4 5 7 6 8
1 2 4 5 6 7 8
February 11, 1999 CSPP503 Week 6
The Code for Bubble Sortpublic void sort() {
int hold; // temporary holding area for swap
// passes
for ( int pass = 1; pass < a.length; pass++ )
// one pass
for ( int i = 0; i < a.length - 1; i++ )
// one comparison
if ( a[ i ] > a[ i + 1 ] ) {
// one swap
hold = a[i]; a[ i ] = a[ i + 1 ]; a[ i + 1 ] = hold;
}
}
Nested for loops
February 11, 1999 CSPP503 Week 6
There’s More Than One Way to Sort a Cat
• Other sorts– Quicksort– Heapsort– Bucket sort
• Different sorts have different characteristics– Memory usage– Speed
February 11, 1999 CSPP503 Week 6
Searching Here, There & Everywhere
• Need to find a value? Search for it!• Linear search
– Is it the next one?• No, then look again• Yes, stick a fork in me, ‘cuz I’m done
– Works on unsorted items
• Binary search– Cut in half every time
February 11, 1999 CSPP503 Week 6
Arrays of Arrays
• Arrays in multiple dimensions– Not just a list– A table (an array of arrays)– A cube (an array of arrays of arrays)
February 11, 1999 CSPP503 Week 6
An Example
An array of arrays
int b[][] = { {1,2}, {3, 4, 5}}
Row 0: 1 2
Row 1: 3 4 5
A 3x3 array
int b[][];
b = new int[3][3];
February 11, 1999 CSPP503 Week 6
Where Do You Want To Go Today?
• Building new objects• Accessors• this and That
February 11, 1999 CSPP503 Week 6
Caution, Objects Under Construction!
• Objects have structure and structure has to be builtnew means create a new instance of an
object
• How are objects actually built?– Objects know how to do things, including
how to build themselves
February 11, 1999 CSPP503 Week 6
Constructor Methods• Constructors are special methods that
build new objects– Declaration looks just like a method
declaration that has no result type
public class Circle {double x_center, y_center, radius;
public Circle(double x, double y, double r) {x_center = x;y_center = y;radius = r;
}}
February 11, 1999 CSPP503 Week 6
A Few Notes on Constructors I
• Don't have to declare a constructor– Java creates a default constructor
public class Circle {public double x_center, y_center, radius;
// Uses the default constructor
public double Area() {return 3.141592654d * radius * radius;
}}
February 11, 1999 CSPP503 Week 6
A Few Notes on Constructors II
• Constructors have the same name as the class
• No return type (why not?)• Constructor declarations are not
members– Never inherited, so no hiding or overriding
February 11, 1999 CSPP503 Week 6
Multiple Constructors
public Circle(double x, double y, double r) {x_center = x;y_center = y;radius = r;
}
public Circle() {x_center = 0;y_center = 0;radius = 1;
}
public Circle(double x, double y) {x_center = x;y_center = y;radius = 1;
}
February 11, 1999 CSPP503 Week 6
Handling Multiple Constructors
• How does Java tell the constructors apart?– Method signatures– Signatures include:
• Name of the method
• Number formal parameters
• Types of formal parameters
– Doesn't include the name of the parameter
February 11, 1999 CSPP503 Week 6
Method Signatures
• For this method:public Circle(double x, double y, double r)
• Signature is:Circle(double, double, double)
• Different methods, same signaturepublic Circle(double x, double y)
public Circle(double x, double r)
February 11, 1999 CSPP503 Week 6
Back to Multiple Constructors
• Multiple constructors are okay– Each constructor has to have a unique
signature(All of a class's methods have to have unique
signatures, not just constructors)
• Method overloading: multiple versions of the same method (but with different signatures)
February 11, 1999 CSPP503 Week 6
The Linda Tripp Problem
• How do we keep private data private?• Avoid having object1 mess with object2's dataExample: Student objects know student's
grades, but one student shouldn't modify another student's grades.
• Storing invalid data– Stuffing 12-hr time into a 24-hr time object
February 11, 1999 CSPP503 Week 6
If It's Public...
• Start with:public class Circle {
public double x_center, y_center;
public double radius, area;
public Circle(double x, double y) {
x_center = x;
y_center = y;
radius = 1;
area = 3.141592654
}
}
February 11, 1999 CSPP503 Week 6
…other objects can mess with it
• Create a circleCircle duPont = new Circle(100d, 100d);
// Change the area, but leave r the same
duPont.Area = 11;
// Now a circle with radius 1 has area 11
February 11, 1999 CSPP503 Week 6
Using private
• Declare variables to be private
public class Circle {
private double x_center, y_center;
private double radius, area;
:
:
}
• Now only Circle can modify the variables (x_center, y_center, ...)
February 11, 1999 CSPP503 Week 6
Granting Access
• Other classes might need to read or write the values stored in private members
• Create accessor functions– Set (or settor)– Get (or gettor)
• Control access through get and set
February 11, 1999 CSPP503 Week 6
Setting and Getting
• What's the difference between using get and set methods, and just making everything public?
• Two benefits– Protect instance variables from outside
meddling– Insulates class users from changes in
variables
February 11, 1999 CSPP503 Week 6
Example from Fig 6.5// blah, blah, blah. Set invalid values to zero. public void setTime( int h, int m, int s ) { setHour( h ); // set the hour setMinute( m ); // set the minute setSecond( s ); // set the second }
// set the hour public void setHour( int h ) {
hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); }
// set the minute public void setMinute( int m ) {
minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); }
// set the second public void setSecond( int s ) {
second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }
February 11, 1999 CSPP503 Week 6
Me, a Name I Call Myself
• How can objects refer to themselves?– Every object has a built-in reference to
itself, called this
• this can be used only in:– Body of a method or constructor
– Initializer of an instance variable
– Anywhere else is a compile-time error
February 11, 1999 CSPP503 Week 6
This is Bad,public class Circle {
public double x, y;
public double r, area;
public Circle(double x, double y) {
x = x; // This doesn't do much, because we're
y = y; // just assigning parameters to themselves
r = 1;
area = 3.141592654
}
}
February 11, 1999 CSPP503 Week 6
But this is okaypublic class Circle {
public double x, y;
public double r, area;
public Circle(double x, double y) {
this.x = x; // Now we're assigning the instance
this.y = y; // variables to the parameters
r = 1;
area = 3.141592654
}
}
Better to avoid this mess altogether by using different names for data members and method parameters