Last Time - PowerPoint PPT Presentation

About This Presentation
Title:

Last Time

Description:

We should have a midterm next week how about Tuesday the 23rd? ... 'Ragged Arrays' are not 'square' and are legal in Java: int[][] raggedArray = new int[5] ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 61
Provided by: researchC
Category:
Tags: last | ragged | time

less

Transcript and Presenter's Notes

Title: Last Time


1
Last Time
  • Math class
  • Style and Documentation
  • Loops
  • And Exercises!

2
Announcements
  • Lecture exercise sample solutions for last
    lecture are posted.
  • Any questions on these?
  • We should have a midterm next week how about
    Tuesday the 23rd? One hour tutorial followed by
    2 hrs for exam?
  • Optional bring a copy of Java syntax summary
    sheet.
  • All topics up to and including arrays.

3
Today
  • Warm-up exercise to review loops.
  • Arrays One dimensional and two dimensional.
  • Please read array notes linked off of Syllabus
    page.
  • More exercises (of course)!
  • Introduction to class structure
  • Attributes
  • Methods

4
Warm Up!
  • Print out the numbers between 0 and 200,
    inclusive, by 20s, one number per line.
  • Write the program three ways using each type of
    loop, in turn.

5
Warm Up Cont.
  • You could get the same output without using a
    loop, but what a pain! Suppose you had to count
    to 2,000 instead?
  • You can write this program in a very inefficient
    way!

6
Aside - Efficient Code
  • We have talked about coding style and
    documentation.
  • The compiler does not care about how efficient
    your code is either.
  • Who does care?
  • Efficiency is all about execution time

Try to write code that accomplishes your purpose
with the minimum number of instructions, provided
you have not greatly compromised the readability
of your program.
7
Aside Memory Efficiency?
  • These days our computers have so much RAM, we are
    not so concerned about being memory efficient.
  • But
  • Declaring an excess number of variables makes
    your program harder to read, as well as using up
    excess memory.
  • Overly large programs are also harder to debug
    Modular coding can lead to more efficient code
    that is also easier to write, debug and re-use.

8
One-Dimensional Arrays
  • An array is just a collection of items, stored in
    computer memory (RAM).
  • In Java
  • The items must all be of the same base type.
  • Can be of any primitive type or object.
  • The size of the array must be declared before any
    items can be stored.
  • The size of the array cannot be changed after
    declaration.
  • An array occupies a contiguous memory space.
  • Array elements are numbered from zero.

9
One-Dimensional Arrays - Cont.
  • The use of arrays in memory offers great speed
    advantages over processing data in and out of
    files.
  • File operations are always much slower than
    operations dealing only in RAM.
  • Typically, you will write array programs to
  • Read values from a file.
  • Carry out all the calculations and manipulations
    required, in memory.
  • Save the data back to another file.
  • Arrays make it much easier to carry out the same
    calculation on many values.

10
One-Dimensional Arrays - Declaration
  • For example, to create an array to hold 10
    integers
  • int testArray new int10
  • testArray now points to an area of memory that
    holds locations for 10 integers.
  • It also points to one location that holds
    testArray.length which is an attribute of the
    array, that is equal to the number of elements.
  • Arrays are Objects in Java.

11
Aside New Java Keywords?
  • The declaration and use of arrays does not
    require us to learn any new Java keywords.
  • The only new thing are the square brackets .

12
One-Dimensional Arrays - Declaration, Cont.
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0

0480ff
0180ff
int testArray 0480ff
  • As a pointer, testArray points to an area of
    memory that contains a series of int values as
    well as the attribute length.

10
.length
13
One-Dimensional Arrays - Declaration, Cont.
  • The java statement above can be split into two
  • int testArray
  • testArray new int10
  • The first statement creates a variable of type
    int - that is to say that it will be an array
    of ints.
  • The variable, testArray is now an object of type
    int that contains an object reference or a
    pointer. The object reference is null after the
    first statement.

14
One-Dimensional Arrays - Declaration, Cont.
  • int testArray
  • testArray new int10
  • The second statement looks for a chunk of memory
    big enough to contiguously hold 10 integers
    (about 40 bytes), and then changes the object
    reference of testArray from null to the memory
    location of the chunk.
  • This assignment of the object reference of the
    testArray object is carried out by the
    assignment operator.
  • The new keyword is responsible for blocking out
    the memory space and initializing each memory
    location to the default value for a new memory
    location of type int (zero).

15
One-Dimensional Arrays - Cont.
  • Back to the 10 array elements in memory
  • testArray0
  • testArray1
  • testArray2
  • testArray3
  • testArray4
  • testArray5
  • testArray6
  • testArray7
  • testArray8
  • testArray9

0 0 0 0 0 0 0 0 0 0
testArray.length
10
16
One-Dimensional Arrays - Indices
  • The numbers 0 to 9 are called the index values of
    the array. The notation used above allows you to
    refer to individual elements.
  • Note that the elements of the array are numbered
    from zero.
  • arrayname.length returns the number of elements
    in the array.
  • length is an attribute of the array Object.

17
One-Dimensional Arrays - Cont.
  • for loops are often used with arrays. For
    example, to initialize each of the elements of
    testArray to the value 1000 i
  • int i
  • for (i 0 i lt 10 i)
  • testArrayi 1000 i
  • Arrays can also be initialized at declaration,
    using an array initializer. To get the same
    array as above
  • int testArray 0, 1000, 2000, 3000, 4000,
    5000, 6000, 7000, 8000, 9000

18
One-Dimensional Arrays - Cont.
  • Arrays can also be created using a variable (or
    constant) to specify the array size
  • final int MAX_SIZE 1000
  • int testArray new intMAX_SIZE
  • int size testArray.length // size is 1000

19
One-Dimensional Arrays - Cont.
  • All the examples so far, have been arrays of
    ints.
  • Could be arrays of doubles, booleans or even
    Strings (anything in fact, as long as all the
    array elements are the same thing)
  • For example (on the next slide)

20
More Declaration Examples
  • double dArray new double50
  • String sArray new String100
  • String sArray2 Hi, Ho, Silver!
  • Note that there is some flexibility in where the
    first set of goes. These two declarations
    are equivalent
  • double disNDat new double1000
  • double disNDat new double1000

21
One-Dimensional Arrays - Out-of-bounds Error
  • If n is the size of the array, then
  • Array indices (or subscripts) lt 0 or ? n are
    illegal, since they do not correspond to real
    memory locations in the array.
  • These indices are said to be out-of-bounds.
  • Reference to an out-of-bounds index produces an
    out-of-bounds exception, and the program will
    crash if the exception is not caught.

22
One-Dimensional Arrays - Out-of-bounds Error,
Cont.
  • Example
  • // Declare and initialize array
  • int a 1,2,3,4,5
  • // Write array to screen (with an error!)
  • for ( int i 0 i lt 5 i )
  • System.out.println("a" i " "
    ai)
  • On the screen

a0 1 a1 2 a2 3 a3 4
a4 5 java.lang.ArrayIndexOutOfBoundsExcept
ion 5 at TestBounds.main(TestBounds.ja
va15)
23
One-Dimensional Arrays - Reminders
  • The brackets are used in three different
    ways, all associated only with arrays
  • At declaration
  • To specify the base type int
  • To specify the size int10
  • To refer to a single element testArrayi
  • The base type of an array can be any primitive
    type, such as int, double, etc., as well as
    String, or any object type.
  • Each array element must be of the same type.

24
One-Dimensional Arrays - Reminders - Cont.
  • Remember that array elements are numbered
    starting from zero. So, the 10th element in an
    array called myArray is myArray9. Suppose
    myArray was declared to hold 1000 elements. If
    you try to access myArray1000 you will get an
    Array index out of bounds error.

25
Multi-Dimensional Arrays
  • Multi-dimensional arrays are just arrays of
    arrays.
  • For example, to create a two-dimensional array
  • int twoDArray new int1020
  • Holds 200 elements. Initialize each element to
    the sum of its indices, for example
  • int i, j
  • for (i 0 i lt 10 i)
  • for (j 0 j lt 20 j)
  • twoDArrayij i j

26
Multi-Dimensional Arrays - Cont.
  • Everything is the same as for one-dimensional
    arrays, except that you have a set of for
    each dimension.
  • Two-dimensional arrays are suitable for storage
    of a single type of data that would normally be
    viewed in a table with rows and columns.
  • Java does not place any limitation on the number
    of dimensions used in an array.

27
Multi-Dimensional Arrays - Cont.
  • Consider
  • int exArray new int35

0 0 0 0 0
1002fc
int exArray 0480ff
int exArray0 1002fc int exArray1 1010fc in
t exArray2 1201ab
0 0 0 0 0
1010fc
0 0 0 0 0
1201ab
28
Multi-Dimensional Arrays - Cont.
  • So exArray points to three one dimensional
    arrays
  • exArray0
  • exArray1
  • exArray2
  • Each of these arrays has the same length
  • exArray2.length // returns 5

29
Multi-Dimensional Arrays - Cont.
  • int twoDArray new int1020
  • The above is equivalent to
  • int twoDArray
  • twoDArray new int10
  • for (int i 0 i lt 10 i)
  • twoDArrayi new int20
  • As shown above
  • twoDArray.length // gives 10
  • twoDArray0.length // gives 20

30
Multi-Dimensional Arrays - Cont.
  • Ragged Arrays are not square and are legal in
    Java
  • int raggedArray new int5
  • raggedArray0 new int2
  • raggedArray1 new int4
  • raggedArray2 new int6
  • raggedArray3 new int8
  • raggedArray4 new int10

31
Multi-Dimensional Arrays - Cont.
  • Array initializer for two-D array, for example
  • int twoDArray 1, 2, 3,
  • 4, 5, 6,
  • 7, 8, 9,
  • 10, 11, 12
  • System.out.println(twoDArray.length) // 4
  • System.out.println(twoDArray0.length) // 3

32
Time for An Exercise!
  • Prompt the user for how many random numbers to
    generate (using Math.random()). Exit the program
    (use System.exit(0)) if the user enters a number
    lt 1.
  • Generate and store these numbers in an array.
  • Calculate the mean of the array of numbers.
  • Count how many of these numbers are lt 0.5 .
  • Display the mean and the count lt 0.5 and gt 0.5.

33
Array Exercise 2
  • Prompt the user for the number of columns and the
    number of rows of a 2D array. Both numbers must
    be gt 2 (or just exit the program).
  • Generate and then display a 2D array of this size
    with the number 8 all around the outside and 1
    everywhere else.
  • For example for 6 columns and 5 rows

888888 811118 811118 811118 888888
34
Arrays as Objects - Example
int first 1, 2, 3, 4, 5 int second
10, 20, 30, 40, 50, 60, 70
1 2 3 4 5
10 20 30 40 50 60 70
0480ff
0960ff
int first 0480ff
int second 0960ff
.length
  • 5

.length
7
35
Arrays as Objects - Example Cont.
second first // Aliasing!
1 2 3 4 5
10 20 30 40 50 60 70
0480ff
0960ff
int first 0480ff
int second 0480ff
.length
  • 5

.length
7
36
Arrays as Objects - Example Cont.
// after garbage collection
1 2 3 4 5
0480ff
int first 0480ff
int second 0480ff
.length
  • 5

37
Arrays as Objects - Example Cont.
first4 500 // second4 is also 500
1 2 3 4 500
0480ff
int first 0480ff
int second 0480ff
  • 5

.length
38
Arrays as Objects - Aliasing
  • So, setting one array to equal another as in
  • array1 array2
  • sets array1 to point to the same data memory
    location that was (and still is) pointed to by
    array2.
  • Now, changing the value of an element in array2
    will change that same element in array1, or
    visa-versa - this makes sense since both array
    Objects point to the same set of data values in
    memory!

39
Arrays as Objects - Cont.
  • System.out.println() will print anything, but
    when it is used to print an Object, some
    interesting gibberish is produced!
  • Testing Objects for equality (with the
    boolean operator) is also interesting
  • This test will only give a true when both objects
    have been aliased, using the assignment operator
    .
  • So, even if both arrays have identical contents,
    will return false, unless both arrays point
    to the same location.
  • This means that comparing Objects with only
    compares pointers, not contents.

40
Array Exercise 3
  • Using array literals, create two arrays, array1
    holding the numbers 1, 2, 3, 4, 5 and array2 with
    the numbers 100, 200, 300.
  • Use System.out.println(array1) to print out the
    first and then a similar statement to print out
    array2.
  • Run the program.
  • Add the line
  • System.out.println(array1 array2)
  • and run again.

41
Array Exercise 3, Cont.
  • Add code to print out the first elements of both
    arrays, and run again.
  • Add the line
  • array1 array2
  • Add the line
  • System.out.println(array1 array2)
  • as above, and run again.
  • Add or copy the code to print the first elements
    again, and run again. Explain the results.
  • Change the first element of array1 to -500 and
    display both elements again.

42
Array Exercise 4
  • Modify the program you wrote for exercise 2 to
    put zeros on the diagonals.

43
Class Structure
  • A class consists of instance variables and/or
    methods.
  • By convention, instance variables are all
    declared before the methods
  • public class ShowStructure
  • // instance variables here
  • // methods here
  • // end class ShowStructure

44
Instance Variables
  • Also called class variables or attributes.
  • These variables are declared at the same level as
    the methods in a class.
  • They are known to all methods within a class.
    Their scope is the entire class in which they
    were declared.

45
Instance Variables, Cont.
  • The syntax for the declaration of attributes
  • privatepublic static final type
    variable_name literal_value
  • The in this syntax means one or the other.
  • The means that this part is optional.

46
Instance Variables, Cont.
  • private or public determines if the attribute can
    be accessed from outside the class.
  • A static attribute shares only a single memory
    location, regardless of how many times its class
    is instantiated. So, every instantiation shares
    this attribute, and any of them can change it.
  • Otherwise, the declaration of an attribute is
    just the same as any other variable declaration.

47
Methods
  • The syntax for simple method declaration
  • privatepublic static return_type method_name
    (parameter_list)

48
Methods - Cont.
  • Often, utility methods that are only used by
    other methods within a class are kept private.
  • When the static keyword is used with methods,
    it means that the method can be used without
    instantiation. (All the methods in the Math
    class are static, for example.)
  • When a static method is invoked for the first
    time, it is loaded into memory and then will stay
    in memory until the program completes.

49
Aside - Instantiation???
  • Simply put, it is the creation of a new Object
    using the new keyword.
  • Another Object is required to provide the
    pattern for the new Object
  • Familiar example
  • Scanner input new Scanner(System.in)

50
Aside - Instantiation??? Cont.
  • Another example
  • String aString new String(Hello class!)
  • is actually better form than
  • String aString Hello class!
  • The latter form (aliasing aString to a String
    literal) is allowed because it is convenient
    (and much like using primitive types.)

51
Methods - Cont.
  • A method must also have a return_type.
  • A return type is what the method will return. It
    can be any single Object or a primitive type.
    (For example an int, double, String, an array,
    or any other pre-defined Object.)
  • If the method does not return anything, then the
    keyword void is used instead.
  • The main method does not return any value, so
    thats why it is declared as in
  • public static void main (String args)

52
Methods - Cont.
  • parameter_list provides a means of passing items,
    or parameters, into a method.
  • It is optional.
  • It can consist of one or many parameters,
    separated by commas.
  • Each parameter type must be declared in the
    parameter list.

53
Methods - Cont.
  • Also important Unless the return type is void,
    the method must contain at least one return
    statement. A void method can also use a return
    statement without anything after it, as a means
    of termination of the method.
  • A method always stops (terminates) when a return
    statement is encountered.
  • Syntax
  • return literalexpression

54
Methods - Cont.
  • The type of literalexpression must match the
    return type specified in the method declaration
    statement.

55
Method Examples
  • public void printHello()
  • System.out.println(Hello)
  • // end printHello
  • public void printHelloName(String yourName)
  • System.out.println(Hello yourName)
  • // end printHelloName
  • public void printAvg(int a, int b)
  • System.out.println((a b) / 2.0)
  • // end printAvg

56
Method Examples - Cont.
  • public double average(double a, double b)
  • return (a b) / 2
  • // end average
  • public int lowest(int a, int b)
  • if (a lt b)
  • return a
  • else
  • return b
  • // end lowest

57
Aside - Methods in the Same Class as main
  • Since main is static, then any method it invokes
    that is declared in the same class as main, must
    also be declared static.
  • (Well see lots of examples of this situation!)

58
Methods - Cont.
  • Why use methods?
  • Modular design.
  • Avoids repetitious code.
  • Independent testing of sub-tasks.
  • Reusable code.
  • Design and test a method once, and re-use it
    whenever you need to solve a similar problem.
  • Isolation from unintended side effects.
  • The only variables from the caller that can be
    seen from a method are those in the parameter
    list.

59
Methods - Cont.
  • Start thinking of your program as a collection of
    methods, where the main method only acts to call
    the other methods.
  • The use of modular design techniques with methods
    is part of what is called encapsulation.

60
Methods - Cont.
  • When designing method operations, make sure a
    method only does one thing, do not combine
    operations (except in main).
  • Concentrate on coding the individual methods, one
    at a time, when you write a program.
  • If you have thought out the code-level
    interface between the methods, then the methods
    will be completely independent of each other.
  • Try to minimize the size of the main method, if
    possible. However, if the main method is often
    going to be responsible for screen I/O - then
    more code may be necessary.
Write a Comment
User Comments (0)
About PowerShow.com