Title: Last Time
1Last Time
- Some discussion of program efficiency.
- Arrays 1D and 2D
2Announcements
- Lecture exercise sample solutions for last
lecture are posted. - Midterm next week 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 (the
material actually presented on the 16th). - Midterm practice problems are posted.
- Assignment 2 posted (soon) due in a week.
3Today
- Warm-up exercise to review arrays Array
Exercise 2 from Tuesday. - Aliasing Objects
- Introduction to class structure
- Attributes
- Methods
- Writing and Using Methods
4Warm Up - Array Exercise 2
- Prompt the user for the number of columns and the
number of rows of a 2D array. Both numbers must
be 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
5Arrays 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
.length
7
6Arrays 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
.length
7
7Arrays as Objects - Example Cont.
// after garbage collection
Poof!
1 2 3 4 5
0480ff
int first 0480ff
int second 0480ff
.length
8Aside Garbage Collection in Java
- Some computer programming languages require you
to indicate when you are done with variables so
the memory they are occupying can be released
back to the OS. Called Garbage Collection. - (Fortunately!) Java has an automatic Garbage
Collection system - Variables are garbage collected once you move
outside their scope. - Object contents are garbage collected when there
are no pointers pointing to the contents.
9Arrays as Objects - Example Cont.
first4 500 // second4 is also 500
1 2 3 4 500
0480ff
int first 0480ff
int second 0480ff
.length
10Arrays 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!
11Arrays 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.
12Array 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.
13Array 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.
14Classes and Objects
- Classes in Java are used to define Objects.
- A Class is an Object and an Object is a Class.
- A class can hold methods (code that does
something) and attributes (data).
data
method
data
method
data
class
method
data
data
method
data
15Class 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
16Instance 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.
17Instance 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.
18Instance 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.
Also, you can access a static attribute without
instantiating the class. - Otherwise, the declaration of an attribute is
just the same as any other variable declaration.
19Methods
- The syntax for simple method declaration
- privatepublic static return_type method_name
(parameter_list)
20Methods - 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.
21Aside - 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)
22Aside - 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.)
23Methods - 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)
24Methods - 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.
25Methods - 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
26Methods - Cont.
- The type of literalexpression must match the
return type specified in the method declaration
statement.
27Method 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
28Method Examples - Cont.
- public double average(double a, double b)
- return (a b) / 2
- // end average
- public int lowest(int a, int b)
- if (a
- return a
- else
- return b
- // end lowest
29Aside - 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!)
30Methods - 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.
31Methods - 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.
32Methods - 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.
33Methods - Example
- For example, suppose we have to obtain four
integer values from the user - Student number
- Birthday date
- Birthday month
- Birthday year
- Each value will have a certain legal range
- Student number between 3,000,000 and 6,000,000
- Birthday date between 1 and 31
- Birthday month between 1 and 12
- Birthday year between 1900 and 2000 (a little
generous here!)
34Methods - Example - Cont.
- In code
- do
- System.out.print("Student number ")
- sn input.nextInt()
- while (sn 6000000)
- do
- System.out.print("Birthday day ")
- bDay input.nextInt()
- while (bDay 31)
- do
- System.out.print("Birthday month ")
- month input.nextInt()
- while (month 12)
- do
- System.out.print("Birthday year ")
- year input.nextInt()
- while (year 2000)
35Methods - Example - Cont.
- You should be able to see that all these loops
are very similar. - It would be easier to write
- sn getInt("Student number ", 3000000,
5000000) - bDay getInt("Birthday day ", 1, 31)
- month getInt("Birthday month ", 1, 12)
- year getInt("Birthday year ", 1900, 2000)
- All of these statements use a getInt method.
- We supply just the unique parts of each
structure. - This method is defined as follows
36Methods - Example - Cont.
- public static int getInt (String prompt, int low,
int high) - int userVal
- Scanner input new Scanner(System.in)
- do
- System.out.print (prompt)
- userVal input.nextInt ()
- while (userVal high)
- return userVal
- // end getInt method
37Methods Example Cont.
- You could put this method in the same class as
other methods that will use it, but if you think
you will use it more often, then how about
putting it in a helper class - import java.util.Scanner
- public class Helper
- public static int getInt ()
- // other handy-dandy methods?
- // end Helper class
38Methods Example Cont.
- Now, in some other class (in the same folder),
you could use your helper class method. For
example - aGrade Helper.getInt(Enter grade , 0, 100)
- (Aside to put Helper in some other folder, you
would make it part of a package and put it on the
classpath. Then you would be able to import
this class like you do the Scanner class.)
39Method Exercise 1
- Write the Helper class as outlined above.
- In the same folder create another class with a
main method. - Add code to the main method invoking the getInt
method to get a number between 0 and 100, then
display the number.
40Method Exercise 1, Cont.
- In the same class that contains the main method,
add another method, also called getInt that just
accepts a String (the prompt) and no other
parameters. - Write code in main to test this method. Note
that you can invoke this new getInt method
without naming its owner Object.
41Method Exercise 1, Cont.
- Cut this new getInt method and paste it into your
Helper class. - Alter the code in your main method to test this
single parameter getInt method that is now in the
Helper class. - How does Java know which version of getInt you
are invoking?
42Method Overloading
- A method can have the same name in many different
classes (println, for example). - Overloading is when a method name is used more
than once within the same class. - The rule is that no two methods with the same
name within a class can have the same number
and/or types of parameters in the method
declarations. (The NOT rule.)
43Method Overloading - Cont.
- Why bother? Convenience!
- Allows the user to call a method without
requiring him to supply values for all the
parameters. - One method name can be used with many different
types and combinations of parameters. - Allows the programmer to keep an old method
definition in the class for backwards
compatibility.
44Method Overloading - Cont.
- How does it work?
- Java looks through all methods until the
parameter types match with the list of arguments
supplied by the user. If none match, Java tries
to cast types in order to get a match. (Only
widening casting like int to double, however.)
45Method Overloading - Cont.
- Final notes on overloading
- You can have as many overloaded method
definitions as you want, as long as they are
differentiated by the type and/or number of the
parameters listed in the definition. - Note that you cannot use the return type to
differentiate overloaded methods.
46Method Exercise 2
- Add a method (called average) to the class
containing your main method that returns, as a
double, the average of an array of ints supplied
as a parameter. This method should also take two
more parameters the starting and finishing
positions in the array, over which to carry out
the calculation. - Write an overloaded version of this same method
that only has one parameter just the array.
Note that this method only needs one line of code
47Method Exercise 2, Cont.
- Add a loop in your main method that prompts the
user for int values (as you have done before),
until he enters a negative number. Use your
Helper class in this loop. - Test the operation of your average method with
this array. - Test the operation of the other average method
with an array declared using an array literal.