Presentation is loading. Please wait.

Presentation is loading. Please wait.

Last Time Some discussion of program “efficiency”. Arrays – 1D and 2D

Similar presentations


Presentation on theme: "Last Time Some discussion of program “efficiency”. Arrays – 1D and 2D"— Presentation transcript:

1 Last Time Some discussion of program “efficiency”. Arrays – 1D and 2D
Spring 2006 CISC101 - Prof. McLeod

2 Announcements 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. Spring 2006 CISC101 - Prof. McLeod

3 Today Warm-up exercise to review arrays – “Array Exercise 2” from Tuesday. Aliasing Objects Introduction to class structure: Attributes Methods Writing and Using Methods Spring 2006 CISC101 - Prof. McLeod

4 Warm 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 Spring 2006 CISC101 - Prof. McLeod

5 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 Spring 2006 CISC101 - Prof. McLeod

6 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 Spring 2006 CISC101 - Prof. McLeod

7 Arrays as Objects - Example Cont.
// after garbage collection Poof! 1 2 3 4 5 0480ff int[] first 0480ff int[] second 0480ff .length 5 Spring 2006 CISC101 - Prof. McLeod

8 Aside – “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. Spring 2006 CISC101 - Prof. McLeod

9 Arrays as Objects - Example Cont.
first[4] = 500; // second[4] is also 500 1 2 3 4 500 0480ff int[] first 0480ff int[] second 0480ff .length 5 Spring 2006 CISC101 - Prof. McLeod

10 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! Spring 2006 CISC101 - Prof. McLeod

11 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. Spring 2006 CISC101 - Prof. McLeod

12 System.out.println(array1 == array2);
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. Spring 2006 CISC101 - Prof. McLeod

13 System.out.println(array1 == array2);
Array Exercise 3, Cont. Add code to print out the first elements of both arrays, and run again. Add the line array1 = array2; 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. Spring 2006 CISC101 - Prof. McLeod

14 Classes 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 Spring 2006 CISC101 - Prof. McLeod

15 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 Spring 2006 CISC101 - Prof. McLeod

16 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. Spring 2006 CISC101 - Prof. McLeod

17 Instance Variables, Cont.
The syntax for the declaration of attributes: [private|public] [static] [final] type variable_name [= literal_value]; The “|” in this syntax means “one or the other”. The “[ ]” means that this part is optional. Spring 2006 CISC101 - Prof. McLeod

18 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. 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. Spring 2006 CISC101 - Prof. McLeod

19 Methods The syntax for simple method declaration:
[private|public] [static] return_type method_name ([parameter_list]) {…} Spring 2006 CISC101 - Prof. McLeod

20 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. Spring 2006 CISC101 - Prof. McLeod

21 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); Spring 2006 CISC101 - Prof. McLeod

22 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.) Spring 2006 CISC101 - Prof. McLeod

23 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 that’s why it is declared as in: public static void main (String[] args) {…} Spring 2006 CISC101 - Prof. McLeod

24 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. Spring 2006 CISC101 - Prof. McLeod

25 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 [literal|expression]; Spring 2006 CISC101 - Prof. McLeod

26 Methods - Cont. The type of “literal|expression” must match the return type specified in the method declaration statement. Spring 2006 CISC101 - Prof. McLeod

27 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 Spring 2006 CISC101 - Prof. McLeod

28 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 <= b) return a; else return b; } // end lowest Spring 2006 CISC101 - Prof. McLeod

29 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. (We’ll see lots of examples of this situation!) Spring 2006 CISC101 - Prof. McLeod

30 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. Spring 2006 CISC101 - Prof. McLeod

31 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”. Spring 2006 CISC101 - Prof. McLeod

32 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. Spring 2006 CISC101 - Prof. McLeod

33 Methods - 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!) Spring 2006 CISC101 - Prof. McLeod

34 Methods - Example - Cont.
In code: do { System.out.print("Student number: "); sn = input.nextInt(); } while (sn < || sn > ); System.out.print("Birthday day: "); bDay = input.nextInt(); } while (bDay < 1 || bDay > 31); System.out.print("Birthday month: "); month = input.nextInt(); } while (month < 1 || month > 12); System.out.print("Birthday year: "); year = input.nextInt(); } while (year < 1900 || year > 2000); Spring 2006 CISC101 - Prof. McLeod

35 Methods - 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: ", , ); 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: Spring 2006 CISC101 - Prof. McLeod

36 Methods - 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 < low || userVal > high); return userVal; } // end getInt method Spring 2006 CISC101 - Prof. McLeod

37 Methods – 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 Spring 2006 CISC101 - Prof. McLeod

38 Methods – 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.) Spring 2006 CISC101 - Prof. McLeod

39 Method 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. Spring 2006 CISC101 - Prof. McLeod

40 Method 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. Spring 2006 CISC101 - Prof. McLeod

41 Method 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? Spring 2006 CISC101 - Prof. McLeod

42 Method 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.) Spring 2006 CISC101 - Prof. McLeod

43 Method 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”. Spring 2006 CISC101 - Prof. McLeod

44 Method 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.) Spring 2006 CISC101 - Prof. McLeod

45 Method 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. Spring 2006 CISC101 - Prof. McLeod

46 Method 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… Spring 2006 CISC101 - Prof. McLeod

47 Method 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. Spring 2006 CISC101 - Prof. McLeod


Download ppt "Last Time Some discussion of program “efficiency”. Arrays – 1D and 2D"

Similar presentations


Ads by Google