Download presentation
Presentation is loading. Please wait.
Published byDominick Hudson Modified over 7 years ago
2
These notes are intended for use by students in CS0401 at the University of Pittsburgh and no one else These notes are provided free of charge and may not be sold in any shape or form Material from these notes is obtained from various sources, including, but not limited to, the following: Starting Out with Java, From Control Structures through Objects, Third to Fifth Editions by Gaddis Java Software Solutions, Fourth and Fifth Editions by Lewis and Loftus Java By Dissection by Pohl and McDowell The Java Tutorial (click for link) The Java home page and its many sub-links:
3
Lecture 1: Prerequisites
Students taking CS401 should already have some programming background: Previous experience with Java (ex: CS 0007) is recommended, but Python, C, C++ and VB are also acceptable Concepts that you are expected to be familiar with and have used in programs include: Basic program structure and syntax How do we build programs and how do we get them to run Primitive types and expressions Numbers, characters, operators, precedence
4
Lecture 1: Prerequisites
Control Statements and Decisions Boolean expressions if and switch (or case) statements Loops (for and while) Methods (or functions) and parameters Calling methods and flow of execution Arguments and parameters Arrays and their uses One-dimensional only If you do not have this background, you should consider taking CS 0007 before taking CS0401 First Response Question Second Response Question
5
Lecture 1: Goals of the Course
Goals for CS 0401 Course: To (quickly) cover the basics of the Java language (including items mentioned in the previous slide) These will be covered more from a Java implementa-tion point of view than from a conceptual point of view You should already be familiar with (most of) the concepts, so learning the Java implementations should be fairly straightforward Also will touch on the foundations of object-oriented programming This includes Chapters 1-5 of the Gaddis text Those who have had CS 0007 should consider this to be an extended review!
6
Lecture 1: Goals of Course
To learn the principles of object-oriented programming and to see Java from an object-oriented point of view Objects, methods and instance variables References and their implications Creating new classes Syntax and logic required Inheritance and composition Building new classes from old classes Polymorphism and dynamic binding Accessing different objects in a uniform way Chapters 6, 8-10 of Gaddis We will focus a lot of attention on these chapters
7
Lecture 1: Goals of Course
Note that we are covering OOP concepts using Java as our language However, the general principles of object-oriented programming apply to any object-oriented language Ex: C++, Objective-C, C#, Smalltalk, etc. The more important goal here is to learn to program effectively in an object-oriented way Understand why it is good and how to do it
8
Lecture 1: Goals of Course
To cover additional useful programming techniques and features of Java in order to become proficient programmers (using the Java language) Array use and algorithms (sorting, searching) (Chapter 7) Reading and Writing Files (Chapters 4, 11 + Notes) Exception Handling (Chapter 11) Graphical User Interfaces and Applications (Chapters 12, 13, 14) Introduction to recursion (Chapter 15) Third Response Question
9
Lecture 1: Why Java? Java Java is an interpreted, platform-independent, object-oriented language Interpreted, platform-independent: Source .java code is compiled into intermediate (byte) code Byte code is executed in software via another program called an interpreter Benefits: More safety features and run-time checks can be built into the language – discuss Code can be platform-independent As long as the correct interpreter is installed, the same byte code can be executed on any platform
10
Program Execution Lecture 1: Why Java? Java Source Code (.java) Java
JRE for Windows Java Source Code (.java) Java Byte Code (.class) JRE for Linux Java Compiler Program Execution JRE for Solaris The same .class file can execute on any platform, as long as the JRE is installed there JRE for Mac
11
Object-oriented Lecture 1: Why Java? Drawback:
Interpreted code executes more slowly than regular compiled code Since program is run in software rather than hardware, it cannot match the execution times of code that is compiled for specific hardware Ex: C, C++ code No language is best for every application However, Java implementations can use JIT compilation of bytecode to execute faster Object-oriented Primary mode of execution is interaction of objects with each other We will discuss object-oriented programming in much more detail soon
12
Lecture 1: Getting Started with Java
How do we execute Java programs? First we must compile our source (.java) code into the intermediate (.class) code We do this with the Java Compiler javac program Next we must interpret our .class code to see the result We do this with the Java Interpreter, or Java Run-time Environment (JRE) java program Demonstrate compiling and execution example, as well as platform independence
13
Lecture 1: Getting Started with Java
Both programs come with the Software Development Kit (SDK) for Java This is installed on all of the lab PCs and the Mac Minis The most recent version (1.8) can be easily downloaded and installed from the Oracle Web site: It is free! More on the basics of using the Java software development kit is shown in Lab 1 See the Lab Info link on the CS 0401 site for details But let’s look at an ex. and talk more about Java basics See ex1.java – Carefully read the comments!
14
Lecture 1: Getting Started with Java
When you have a chance, try the following: Download ex1.java from the Web site onto a PC that has the SDK installed (yours or a lab PC) Open a terminal (command prompt) window Change to the correct directory Compile the program: javac ex1.java Execute the program: java ex1 Adding the .class extension is optional – it is assumed even if you don’t put it there Show the directory to see that the .class file is now there Also try the same thing from one of the Lab workstations during your first lab session
15
Lecture 1: Getting Started with Java
Note: Most developers use an IDE (integrated development environment) for program devel. Here are two possibilities: Both are available free These allow you to edit, compile and debug Java programs in an easy, integrated way However, you should realize that the final program does NOT depend on the IDE, and you should be able to compile and run Java programs without the IDE I will not be emphasizing these in lecture, but you are free to use one if you wish
16
Lecture 2: Java Basics What fundamental entities / abilities do we need for any useful Java program? A way to get data into and out of our program I/O A way to create / name / variables and constants to store our data Identifiers and variables A way to manipulate / operate on the data Statements and Expressions A way to make decisions and control our flow of execution Control structures We will be reviewing all of these in the next few lectures.
17
Output (we will defer input until after we discuss variables)
Lecture 2: Java Basics Output (we will defer input until after we discuss variables) Java has a predefined object called System.out This object has the ability to output data to the standard output stream, which is usually the console (display) This ability is via methods (procedures) Ex: print, println We pass information to the System.out object through methods and parameters, and the information is then shown on the display For example: System.out.println(“Hello Java Students!”);
18
We will see more on this once we discuss variables
Lecture 2: Java Basics We can output strings, values of variables and expressions and other information using System.out This will be very useful in all of our programs We will see more on this once we discuss variables We will understand how System.out works more precisely after we have discussed classes and objects later in the term
19
Lexical elements – groups of characters used in program code
Lecture 2: Java Basics Lexical elements – groups of characters used in program code These form all of the parts of the program code Ex: keywords, identifiers, literals, delimiters We will discuss some of these in the Java language Keywords Lexical elements that have a special, predefined meaning in the language Cannot be redefined or used in any other way in a program Ex: program, if, class, throws See p. 10 in Gaddis for complete list
20
Predefined Identifiers
Lecture 2: Java Basics Predefined Identifiers Identifiers that were written as part of some class / package that are already integrated into the language Ex: System, Applet, JFrame – class names Ex: println, start, close – method names Ex: E, PI – constant names Programmers can use these within the context in which they are defined In Java there are a LOT because Java has a large predefined class library
21
Other Identifiers Defined by programmer
Lecture 2: Java Basics Other Identifiers Defined by programmer used to represent names of variables, methods, classes, etc Cannot be keywords We could redefine predefined identifiers if we wanted to, but this is generally not a good idea Java IDs must begin with a letter, followed by any number of letters, digits, _ (underscore) or $ characters Similar to identifier rules in most programming langs
22
Important Note: Naming Convention: Lecture 2: Java Basics
Java identifiers are case-sensitive – this means that upper and lower case letters are considered to be different – be careful to be consistent! Ex: ThisVariable and thisvariable are NOT the same Naming Convention: Many Java programmers use the following conventions: Classes: start with upper case, then start each word with an upper case letter Ex: StringBuffer, BufferedInputStream, ArrayIndexOutOfBoundsException Methods and variables: start with lower case, then start each word with an upper case letter Ex: compareTo, lastIndexOf, mousePressed Show Question 1
23
Literals Values that are hard-coded into a program
Lecture 2: Java Basics Literals Values that are hard-coded into a program They are literally in the code! Different types have different rules for literal values They are fairly intuitive and similar across most programming languages Ex: Integer An optional +/- followed by a sequence of digits Ex: Ex: String A sequence of characters contained within double quotes Ex: “Hello” “My name is Inigo Montoya” See Section 2.3 for more details on literals
24
Putting all of this together, we get:
Lecture 2: Java Basics Putting all of this together, we get: Lexical elements are the building blocks of Java programs Some useful lexical elements include: Keywords Restricted to their predefined use Predefined identifiers Predefined but could be redefined Programmer defined identifiers Made up by programmer for variable names, class names, method names, etc Literals Values that are hard-coded into a program
25
Statements Units of declaration or execution
Lecture 2: Java Basics Statements Units of declaration or execution A program execution can be broken down into execution of the program’s individual statements Every Java statement must be terminated by a semicolon (;) Ex: Variable declaration statement int var1, var2; Ex: Assignment statement var1 = 100; Ex: Method call System.out.println(“Answer is “ + var1); We will see many more statements later
26
incompatible types found: java.lang.String
Lecture 2: Java Basics Variables Memory locations that are associated with identifiers Values can change throughout the execution of a program In Java, must be specified as a certain type or class The type of a variable specifies its properties: the data it can store and the operations that can be performed on it Ex: int type: discuss Java is fairly strict about enforcing data type values You will get a compilation error if you assign an incorrect type to a variable: Ex: int i = “hello”; Ex: int type: can store values to Has operations +, –, *, /, % Study of various data types is a large part of the CS 0445 Data Structures course (blatant plug for CS 0445) incompatible types found: java.lang.String required: int int i = "hello"; ^
27
possible loss of precision found : double
Lecture 2: Java Basics Note: For numeric types, you even get an error if the value assigned will “lose precision” if placed into the variable Generally speaking this means we can place “smaller” values into “larger” variables but we cannot place “larger” values into “smaller” variables Ex: byte < int < long < float < double Ex: int i = 3.5; Ex: double x = 100; This is ok possible loss of precision found : double required: int int i = 3.5; ^ Discuss other examples
28
statements in the box to
Lecture 2: Java Basics Floating point literals in Java are by default double If you assign one to a float variable, you will get a “loss of precision error” as shown in the previous slide If you want to assign a “more precise” value to a “less precise” variable, you must explicitly cast the value to that variable type int i = 5; int j = 4.5; float x = 3.5; float y = (float) 3.5; double z = 100; i = z; y = z; z = i; j = (long) y; j = (byte) y; Error check each of the statements in the box to the right Idea of requiring casting: If some information / precision in a value will be lost, Java wants the programmer to acknowledge this explicitly, via a cast. Some languages do it implicitly, which can lead to logic errors. Answers to error-checks: OK Illegal – possible loss of precision Illegal – possible loss of precision because the literal 3.5 is double
29
Lecture 2: Data and Expressions
In Java, variables fall into two categories: Primitive Types Simple types whose values are stored directly in the memory location associated with a variable Ex: int var1 = 100; There are 8 primitive types in Java: byte, short, int, long, float, double, char, boolean See Section 2.4 and ex3.java for more details on the primitive numeric types var1 100
30
Lecture 2: Data and Expressions
Reference Types (or class types) Types whose values are references to objects that are stored elsewhere in memory Ex: String s = new String(“Hello There”); There are many implications to using reference types, and we must use them with care Different objects have different capabilities, based on their classes We will discuss reference types in more detail later when we start looking at Objects s Hello There
31
Lecture 2: Data and Expressions
Rules for declaration and use In Java, all variables must be declared before they can be used Ex: x = 5.0; This will cause an error unless x has previously been declared as a double variable Java variables can be initialized in the same statement in which they are declared Ex: double x = 5.0; However, keep in mind that two things are being done here – declaration AND initialization cannot resolve symbol symbol : variable x location : class classname x = 5.0; ^
32
Lecture 2: Data and Expressions
Multiple variables of the same type can be declared and initialized in a single statement, as long as they are separated by commas Ex: int i = 10, j = 20, k = 45; Multiple variables of different types cannot be declared within a single declaration statement See ex2.java
33
Lecture 2: Data and Expressions
Operators and Expressions Numeric operators in Java include +, –, *, /, % These are typical across most languages A couple points, however: If both operands are integer, / will give integer division, always producing an integer result – discuss implications The % operator was designed integer operands and gives the remainder of integer division However, % can be used with floating point as well int i, j, k, m; i = 19; j = 7; k = i / j; // answer? m = i % j; // answer?
34
Lecture 3: Data and Expressions
Precedence and Associativity What do these mean? Recall that the precedence indicates the order in which operators are applied in an expression See Table 2-8 Recall that the associativity indicates the order in which operands are accessed given operators of the same precedence General guidelines to remember for arithmetic operators: *, /, % same precedence, left to right associativity +, – same (lower) precedence, also L to R See Table 2-9
35
Lecture 3: More Operators
Java has a number of convenience operators Allow us to do operations with less typing Ex: X = X + 1; X++; Y = Y – 5; Y –= 5; See Section 2.6 for more details One point that should be emphasized is the difference between the prefix and postfix versions of the unary operators What is the difference between the statements: X++; ++X; Discuss See ex3.java When used as shown above, the operators have the same effect. However, when used as part of another expression there is a difference: The postfix operator is performed AFTER the previous value is used in the expression The prefix operator is performed BEFORE the value is used in the expression So for example: X = 5; Y = X++; // Now Y is 5 and X is 6 Y = ++X; // Now Y is 6 and X is 6
36
Lecture 3: Input and the Scanner Class
Java has a predefined object called System.in Analogous to System.out discussed previously Allows data to be input from the standard input stream Recall that System.out accessed the standard output stream By default this object allows us to read data from the console / keyboard
37
Lecture 3: Input and the Scanner Class
In JDK releases up to 1.4 Console text input was fairly complicated to use Objects had to be created and exceptions had to be handled Made it difficult to show students learning Java simple input and output Consequently, textbook authors often created their own classes to make console I/O easier But they weren't standard Java, so students would not find them useful after their courses ended In JDK 1.5, the Scanner class was added
38
Lecture 3: Input and the Scanner Class
Scanner is a class that reads data from the standard input stream and parses it into tokens based on a delimiter A delimiter is a character or set of characters that distinguish one token from another A token is all of the characters between delimiters By default the Scanner class uses white space as the delimiter The tokens can be read in either as Strings next() Or they can be read as primitive types Ex: nextInt(), nextFloat(), nextDouble()
39
Lecture 3: Input and the Scanner Class
If read as primitive types, an error will occur if the actual token does not match what you are trying to read Ex: Please enter an int: hello Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at ex3.main(ex3.java:39) These types of errors are run-time errors and in Java are called exceptions Java has many different exceptions We'll look at exceptions in more detail later Let's look at ex4.java
40
Lecture 3: Control Statements
Java Statements We already discussed some Java statements Declaration statement Assignment statement Method call One of the most important types of statements in programming is the control statement Allows 2 very important types of execution Conditional execution Statements may or may not execute Iterative execution Statements may execute more than one time
41
Lecture 3: Control Statements
Linear Execution Conditional Execution Iterative Execution
42
Lecture 4: Boolean Expressions
Key to many control statements in Java are boolean expressions Expressions whose result is true or false true and false are predefined literals in Java Can be created using one or more relational operators and logical operators Relational operators Used to compare (i.e. relate) two primitive values Result is true or false based on values and the comparison that is asserted Ex: 6 < true because 6 IS less than 10 7 != false because 7 IS NOT not equal to 7
43
Lecture 4: Boolean Expressions
Java has 6 relational operators < <= > >= == != Some boolean expressions are more complicated than just a simple relational operation These expressions require logical operators Operate on boolean values, generating a new boolean value as a result ! && || Recall their values from a truth table A B true false !A false true A&&B true false A||B true false
44
Lecture 4: Boolean Expressions
Let’s look at some examples int i = 10, j = 15, k = 20; double x = 10.0, y = , z = 100.0; i < j || j < k && x <= y (i / 3) == y (x / 3) == y !(x != i) Note: Precedence in boolean expressions: relational operators ! && || Examples: True, due to the higher precedence of && over || False, due to integer division False, due to precision issues with floating point numbers True – mixed expressions are cast to the more “precise” type, so i is cast into a double
45
The if statement is very intuitive:
Lecture 4: if statement The if statement is very intuitive: if (booleanexpression) <true option>; else <false option>; Each of <true option> and <false option> can be any Java statement, including a block Java blocks are delimited by { } and can contain any number of statements else + <false option> is optional Note parens around booleanexpression - required
46
Lecture 4: if statement Nested ifs Since both <true option> and <false option> can be any Java statement, they can certainly be if statements This allows us to create nested if statements We can nest on <true option>, on <false option> or both Show on board Enables us to test multiple conditions and to have a different result for each possibility if (grade >= 90) System.out.println(“A”); else if (grade >= 80) System.out.println(“B”); else if (grade >= 70) System.out.println(“C”); else if (grade >= 60) System.out.println(“D”); else System.out.println(“F”);
47
Lecture 4: if statement Dangling else The structure of a Java if statement allows for an interesting special case: if (grade >= 95) // condition1 if (extraCredit) // condition2 System.out.println(“A+”); else System.out.println(“?”); Question: is the <false option> for condition1 or condition2? As shown above it will ALWAYS be for condition2 Rule is that an else will always be associated with the “closest” unassociated, non-terminated if
48
Thus, there is no problem for the computer
Lecture 4: if statement Thus, there is no problem for the computer Problem is if the programmer does not understand the rule Result is a LOGIC ERROR Logic errors can be very problematic and difficult to correct Unlike a syntax error, which prevents the program from being compiled, with a logic error the program may run and may seem fine However, one or more errors in the programmer’s logic cause the result will be incorrect! Compare on board: SYNTAX ERROR, RUN-TIME ERROR, LOGIC ERROR Luckily, in this case the problem is easy to correct How? Make sure you get in-class notes comparing syntax error, run-time error and logic error.
49
The while loop is also intuitive
Lecture 4: while loop The while loop is also intuitive while (booleanexpression) <loop body>; where <loop body> can be any Java statement Logic of while loop: Evaluate (booleanexpression) If result is true, execute <loop body>, otherwise skip to next statement after loop Repeat while loop is called an entry loop, because a condition must be met to get IN to the loop body Implications of this? Implications: <loop body> will execute 0 or more times
50
Let’s now use if and while in a simple program:
Lecture 4: Example Let’s now use if and while in a simple program: User will enter some scores and the program will calculate the average Let’s do this together, trying to come up with a good solution Consider some questions / issues: What is the acceptable range for the scores? What do we do if a score is unacceptable? How many scores are there? Do we even know this in advance? What to do if we do not know this in advance? Range of scores: 0-100? Maybe > 100 if extra credit is allowed? What to do: Make user re-enter? Ignore value? How many scores: If we know we can count as they are entered If we don’t know, we need some type of sentinel to indicate when we are finished
51
Once we have a solution, let’s look at two possible solutions
Lecture 4: Example Are there any special cases that we need to consider? What variables will we need to use? And what will be their types? Once we have a solution, let’s look at two possible solutions ex5a.java and ex5b.java Note that for many programming problems, there are MANY possible solutions Special cases: What if there are zero scores? Make sure we don’t divide! Variables: Counter for number of scores (int) Value for current score (double) Accumulator for sum (double) Maybe others – we’ll see What if user enters an illegal score? Can’t handle this yet – will be able to with exceptions! What if user enters invalid data (ex: character data when numbers are wanted)
52
The for loop is more complicated
Lecture 5: for loop The for loop is more complicated Its obvious use is as a counting loop Goes through a specified number of iterations for (int i = 0; i < max; i++) { // will iterate max times } However it is much more general than that for (init_expr; go_expr; inc_expr) { // loop body } Let’s talk about this a bit
53
These expressions make the for loop extremely flexible
Lecture 5: for loop init_expr Any legal Java statement expression Evaluated one time, when the loop is FIRST executed go_expr Java Boolean expression Evaluated PRIOR to each execution of the for loop body If true, body is executed If false, loop terminates inc_expr Evaluated AFTER each execution of the for loop body These expressions make the for loop extremely flexible
54
Lecture 5: for loop Try some examples: For loop to sum the numbers from N to M N + (N+1) + … + (M-1) + M For loop to output powers of 2 less than or equal to K See forexamples.java In effect we can use a for loop as if it were a while loop if we’d like However, it is more readable and less prone to logic errors if you use it as a counting loop Let’s look at the programs from Example 5, but now with a for loop: ex5c.java and ex5d.java int sum = 0; for (int i = N; i <= M; i++) sum += i; for (int value = 1; value <= K; value *= 2) System.out.println(value);
55
Since Java 1.5+, there is an additional version of the for loop:
Lecture 5: for loop Since Java 1.5+, there is an additional version of the for loop: for (type var : iterator_obj) <loop body>; This version is called the "foreach" loop In a lot of scripting languages such as Perl and PHP, so it was adopted into Java However, to use it we need to understand something about objects and iterators This version is really cool! We will come back and talk about this later
56
Lecture 5: switch statement
We know that if can be used in a multiple alternative form If we nest statements Sometimes choices are simple, integral values In these cases, it is easier and more efficient to use a more specialized statement to choose This is where switch comes in handy However it is kind of wacky so be careful to use it correctly!
57
Lecture 5: switch statement
switch (int_expr) { case constant_expr: … default: // this is optional } int_expr is initially evaluated constant_expr are tested against int_expr from top to bottom First one to match determines where execution within the switch body BEGINS However, execution will proceed from there to the END of the block
58
Lecture 5: switch statement
If we want the execution of the different cases to be exclusive of each other, we need to stop execution prior to the next case We can do this using the break statement Switch is actually passed down to Java from C – it doesn’t really fit too well with the spirit of the Java language, but it is there and can be used Let’s look at an example using switch Program to rate movies User enters a “star” value from 1-4 and the program comments back on the movie quality See ex6.java Handout also shows some formatting See also ex6b.java
59
Lecture 6: Methods and Method Calls
If programs are short We can write the code as one contiguous segment The logic is probably simple There are not too many variables Not too likely to make a lot of errors As programs get longer Programming in a single segment gets more and more difficult Logic is more complex Many variables / expressions / control statements
60
Lecture 6: Methods and Method Calls
Chances of “bugs” entering code is higher Isolating and fixing is also harder If multiple people are working on the program, it is difficult to “break up” if written as one segment If parts need to be modified or added, it is difficult with one large segment If similar actions are taken in various parts of the program, it is inefficient to code them all separately And can also introduce errors Ex: Draw a rectangle somewhere in a window Most of these problems can be solved by breaking our program into smaller segments Ex: Break some sticks!
61
Lecture 6: Methods and Method Calls
Method (or function or subprogram) A segment of code that is logically separate from the rest of the program When invoked (i.e. called) control jumps from main to the method and it executes Usually with parameters (arguments) When it is finished, control reverts to the next statement after the method call Show on board System.out.println(“Here is a message to output”); System.out.println(“Printing something else”); // Note that we don’t need to know how the println() method works in order to use it
62
Lecture 6: Functional Abstraction
Methods provide us with functional (or procedural) abstraction We do not need to know all of the impl. details of the methods in order to use them We simply need to know What arguments (parameters) we must provide What the effect of the method is (i.e. what does it do?) The actual implementation could be done in several different ways Ex: Predefined method: sort(Object [] a) There are many ways to sort! This allows programmers to easily use methods that they didn’t write
63
Lecture 6: Return Value vs. Void
Java methods have two primary uses: To act as a function, returning a result to the calling code In Java these methods are declared with return types, and are called within an assignment or expression Ex: X = inScan.nextDouble(); Y = (Math.sqrt(X))/2; To act as a subroutine or procedure, executing code but not explicitly returning a result In Java these methods are declared to be void, and are called as separate stand-alone statements Ex: System.out.println(“Wacky”); Arrays.sort(myData);
64
Lecture 6: Predefined Methods
There are MANY predefined methods in Java Look in the online API These are often called in the following way: ClassName.methodName(param_list) Where ClassName is the class in which the method is defined Where methodName is the name of the method Where param_list is a list of 0 or more variables or expressions that are passed to the method Ex: Y = Math.sqrt(X); These are called STATIC methods or CLASS methods They are associated with a class, not with an object
65
Lecture 6: Predefined Methods
Some are also called in the following way ClassName.ObjectName.methodName(param_list) Where ObjectName is the name of a static, predefined object that contains the method Ex: System.out.println(“Hello There”); System is a predefined class out is a predefined PrintStream object within System println is a method within PrintStream These are instance methods – associated with an object – we will discuss these shortly For now we will concentrate on static methods
66
Lecture 6: Writing Static Methods
What if we need to use a method that is not predefined? We will have to write it ourselves Syntax: public static void methodName(param_list) { // method body } public static retval methodName(param_list) Where retval is some Java type When method is not void, there MUST be a return statement
67
Lecture 6: Writing Static Methods
Really simple example: public static void sayWacky() { System.out.println(“Wacky”); } Now in our main program we can have: sayWacky(); for (int i = 0; i < 5; i++) Note we are not using any parameters in this example
68
Lecture 6: Writing Static Methods
So what about the param_list? It is a way in which we pass values into our methods This enables methods to process different information at different points in the program Makes them more flexible In the method definition: List of type identifier pairs, separated by commas Called formal parameters, or parameters In the method call: List of variables or expressions that match 1-1 with the parameters in the definition Called actual parameters, or arguments
69
Lecture 6: Writing Static Methods
Ex: public static double area(double radius) { double ans = Math.PI * radius * radius; return ans; } … double rad = 2.0; double theArea = area(rad); Note: If method is called in same class in which it was defined, we don’t need to use the class name in the call parameter argument
70
Parameters in Java are passed by value
Lecture 6: Parameters Parameters in Java are passed by value The parameter is a copy of the evaluation of the argument Any changes to the parameter do not affect the argument answer calculated method completed answer returned area method Main Class value passed from arg. to parameter radius rad 2.0 2.0 Look at ex6.java result returned to main ans 12.566… theArea 12.566… double ans = Math.PI * radius * radius; double theArea = area(rad); main calls area method return ans;
71
Lecture 6: More on Parameters
Effect of value parameters: Arguments passed into a method cannot be changed within the method, either intentionally or accidentally Good result: Prevents accidental side-effects from methods Bad result: What if we want the arguments to be changed? Ex: swap(A, B) Method swaps the values in A and B But with value parameters will be a “no-op” - Discuss We can get around this issue when we get into object-oriented programming
72
Lecture 6: Local variables and scope
Variables declared within a method are local to that method They exist only within the context of the method This includes parameters as well Think of a parameter as a local variable that is initialized in the method call We say the scope of these variables is point in the method that they are declared up to the end of the method Show on board
73
Lecture 6: Local variables and scope
However, Java variables can also be declared within blocks inside of methods In this case the scope is the point of the declaration until the end of that block Show on board Be careful that you declare your variables in the correct block See Java Debug Help slides for more details debug.ppt
74
Lecture 6: Local variables and scope
Note that either way, local variables cannot be shared across methods In other words, a local variable declared in one method cannot be accessed in a different method We can still get data from one method to another How? To share variables across methods, we need to use object-oriented programming We will see this soon! See ex7.java Get data from one method to another using parameters!!
75
Lecture 7: References and Reference Types
Recall from Slides that Java has primitive types and reference types Also recall how they are stored With primitive types, data values are stored directly in the memory location associated with a variable With reference types, values are references to objects that are stored elsewhere in memory var1 100 s Hello There
76
Lecture 7: References and Reference Types
What do we mean by “references”? The data stored in a variable is just the “address” of the location where the object is stored Thus it is separate from the object itself Ex: If I have a Contacts file on my PC, it will have the address of my friend, Joe Schmoe (stored as Schmoe, J.) I can use that address to send something to Joe or to go visit him if I would like However, if I change that address in my Contacts file, it does NOT in any way affect Joe, but now I no longer know where Joe is located However, I can indirectly change the data in the Joe Schmoe object through the reference Knowing his address, I can go to Joe’s house and steal his 88 inch 4K Ultra High Definition Curved TV
77
Lecture 7: Classes and Objects
What do we mean by "objects"? Let's first discuss classes Classes are blueprints for our data The class structure provides a good way to encapsulate the data and operations of a new type together Instance data and instance methods The data gives us the structure of the objects and the operations show us how to use them Ex: A String Discuss
78
Lecture 7: Classes and Objects
User of the class knows the general nature of the data, and the public methods, but NOT the implementation details But does not need to know them in order to use the class Ex: BigInteger We call this data abstraction Compare to functional abstraction discussed previously Java classes determine the structure and behavior of Java objects To put it another way, Java objects are instances of Java classes
79
Lecture 7: Classes and Objects
class Foo { int x; void f(); … } Class Foo definition Foo object x = 10 f() Declaring Foo variable Creating Foo object The class defines what a Foo is (both its data and methods) The object is an instance of the class – a realization of the properties defined in class Foo Foo F; F = new Foo(10); F Foo reference
80
Lecture 7: More References
Back to references, let's now see some of the implications of reference variables Declaring a variable does NOT create an object We must create objects separately from declaring variables StringBuilder S1, S2; Right now we have no actual StringBuilder objects – just two variables that could access them To get objects we must use the new operator or call a method that will create an object for us S1 = new StringBuilder("Hello"); S1 now references an instance of a StringBuilder object but S2 does not
81
Lecture 7: More References
So what value does S2 have? For now we will say that we should not count on it to have any value – we must initialize it before we use it If we try to access it without initializing it, we will get an error Multiple variables can access and alter the same object S2 = S1; Now any change via S1 or S2 will update the same object S1 Hello S2
82
Lecture 7: More References
Properties of objects (public methods and public instance variables) are accessed via "dot" notation S1.append(" Friends!"); The process of accessing an object in this way is called dereferencing the object S1 is a reference (address) S1.<whatever> means: Go to the object whose address is stored in S1 Access / call the specified variable or method Note: In this case S2 will also access the appended object S1 Hello Friends! S2
83
Lecture 7: More References
Comparison of reference variables compares the references, NOT the objects StringBuilder S3 = new StringBuilder("Hello Friends!"); if (S1 == S2) System.out.println("Equal"); // yes if (S1 == S3) System.out.println("Equal"); // no Recall that S1, S2 and S3 are all variables storing addresses The == simply compares those address values i.e. Are they looking at the same location? What if we want to compare the objects? Do the objects (where ever they are) have the same data stored within them?
84
Lecture 7: More References
We use the equals() method This is generally defined for many Java classes to compare data within objects We will see how to define it for our own classes soon However, the equals() method is not (re)defined for the StringBuilder class, so we need to convert our StringBuilder objects into Strings in order to compare them: if (S1.toString().equals(S3.toString())) System.out.println("Same value"); // yes We will also use the compareTo() method later It seems complicated but it will make more sense when we get into defining new classes
85
Lecture 7: More references
Note the difference in the tests: The == operator shows us that it is the same object The equals method show us that the values are in some way the same (depending on how it is defined) References can be set to null to initialize or reinitialize a variable Null references cannot be accessed via the "dot" notation If it is attempted a run-time error results S1 = null; S1.append("This will not work!");
86
Lecture 7: More references
Why? The method calls are associated with the OBJECT that is being accessed, NOT with the variable If there is no object, there are no methods available to call Result is NullPointerException – common error so remember it! Let's take a look at ex8.java Side note: speaking of common errors Take another look at debug.ppt – it has some of the things we just mentioned
87
Lecture 7: Intro. to Object-Oriented Programming (OOP)
Object-Oriented Programming consists of 3 primary ideas: Encapsulation and Data Abstraction Operations on the data are considered to be part of the data type We can understand and use a data type without knowing all of its implementation details Neither how the data is represented nor how the operations are implemented We just need to know the interface (or method headers) – how to “communicate” with the object Compare to functional abstraction with methods We discussed this somewhat already
88
Inheritance Polymorphism
Lecture 7: Intro. to OOP Inheritance Properties of a data type can be passed down to a sub-type – we can build new types from old ones We can build class hierarchies with many levels of inheritance We will discuss this more in Chapter 11 Polymorphism Operations used with a variable are based on the class of the object being accessed, not the class of the variable Parent type and sub-type objects can be accessed in a consistent way
89
Lecture 8: Encapsulation and Data Abstraction
Consider primitive types Each variable represents a single, simple data value Any operations that we perform on the data are external to that data X + Y X 10 + Y 5
90
Lecture 8: Encapsulation and Data Abstraction
Consider the data In many applications, data is more complicated than just a simple value Ex: A Polygon – a sequence of connected points The data here are actually: int [] xpoints – an array of x-coordinates int [] ypoints – an array of y-coordinates int npoints – the number of points actually in the Polygon Note that individually the data are just ints However, together they make up a Polygon This is fundamental to object-oriented programming (OOP)
91
Lecture 8: Encapsulation and Data Abstraction
Consider the operations Now consider operations that a Polygon can do Note how that is stated – we are seeing what a Polygon CAN DO rather than WHAT CAN BE DONE to it This is another fundamental idea of OOP – objects are ACTIVE rather than PASSIVE Ex: void addPoint(int x, int y) – add a new point to Polygon boolean contains(double x, double y) – is point (x,y) within the boundaries of the Polygon void translate(int deltaX, int deltaY) – move all points in the Polygon by deltaX and deltaY
92
Lecture 8: Encapsulation and Data Abstraction
These operations are actually (logically) PART of the Polygon itself int [] theXs = {0, 4, 4}; int [] theYs = {0, 0, 2}; int num = 3; Polygon P = new Polygon(theXs, theYs, num); P.addPoint(0, 2); if (P.contains(2, 1)) System.out.println(“Inside P”); else System.out.println(“Outside P”); P.translate(2, 3); We are not passing the Polygon as an argument, we are calling the methods FROM the Polygon
93
Lecture 8: Encapsulation and Data Abstraction
Objects enable us to combine the data and operations of a type together into a single entity: encapsulation P xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate() Thus, the operations are always implicitly acting on the object’s data Ex: translate means translate the points that make up P
94
Lecture 8: Encapsulation and Data Abstraction
For multiple objects of the same class, the operations act on the object specified int [] moreXs = {8, 11, 8}; int [] moreYs = {0, 2, 4}; Polygon P2 = new Polygon(moreXs, moreYs, 3); P P2 xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate() xpoints [8,11,8]] ypoints [0,2,4] npoints 3 addPoint() contains() translate() Consider P.translate(3,3) vs. P2.translate(3,3) In both cases we are moving a Polygon 3 over and 3 down – the difference is which Polygon is being moved
95
Lecture 8: Encapsulation and Data Abstraction
Recall that we previously discussed data abstraction We do not need to know the implementation details of a data type in order to use it This includes the methods AND the actual data representation of the object This concept is exemplified through objects We can think of an object as a container with data and operations inside (i.e. encapsulating them) We can see some of the data and some of the operations, but others are kept hidden from us The ones we can see give us the functionality of the objects
96
Lecture 8: Encapsulation and Data Abstraction
As long as we know the method names, params and how to use them, we don’t need to know how the actual data is stored Note that I can use a Polygon without knowing how the data is stored OR how the methods are implemented I know it has points but I don’t know how they are stored Data Abstraction! P xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate()
97
Lecture 8: Instance Variables
Let us look again at StringBuilder Instance Variables These are the data values within an object Used to store the object’s information As we said previously, when using data abstraction we don’t need to know explicitly what these are in order to use a class For example, look at the API for StringBuilder Note that the instance variables are not even shown there In actuality it is a variable-length array with a counter to keep track of how many locations are being used and is actually inherited from AbstractStringBuilder See source in StringBuilder.java and AbstractStringBuilder.java – cool!!!
98
Lecture 8: Instance Variables
Many instance variables are declared with the keyword private This means that they cannot be directly accessed outside the class itself Instance variables are typically declared to be private, based on the data abstraction that we discussed earlier Recall that we do not need to know how the data is represented in order to use the type Therefore why even allow us to see it? In AbstractStringBuilder the value variable has no keyword modifier This makes it private to the package
99
Lecture 8: Class Methods vs. Instance Methods
Recall that methods we discussed before were called class methods (or static methods) These were not associated with any object Now, however in this case we WILL associate methods with objects (as shown with Polygon) These methods are called instance methods because they are associated with individual instances (or objects) of a class These are the operations within an object StringBuilder B = new StringBuilder(“this is “); B.append(“really fun stuff!”); System.out.println(B.toString());
100
Lecture 8: Class Methods vs. Instance Methods
Class methods have no implicit data to act on All data must be passed into them using arguments Class methods are called using: ClassName.methodName(param list) Instance methods have implicit data associated with an Object Other data can be passed as arguments, but there is always an underlying object to act upon Instance methods are called using: VariableName.methodName(param list) Where VariableName is a reference to an object
101
Lecture 8: Constructors, Accessors and Mutators
Instance methods can be categorized by what they are designed to do: Constructors These are special instance methods that are called when an object is first created They are the only methods that do not have a return value (not even void) They are typically used to initialize the instance variables of an object StringBuilder B = new StringBuilder(“hello there”); B = new StringBuilder(); // default constructor B = new StringBuilder(10); // capacity 10
102
Lecture 8: Constructors, Accessors and Mutators
These methods are used to access the object in some way without changing it Usually used to get information from it No special syntax – categorized simply by their effect StringBuilder B = new StringBuilder(“hello there”); char c = B.charAt(4); // c == ‘o’ String S = B.substring(3, 9); // S == “lo the” // note that end index is NOT inclusive int n = B.length(); // n == 11 These methods give us information about the StringBuilder without revealing the implementation details
103
Lecture 8: Constructors, Accessors and Mutators
Used to change the object in some way Since the instance variables are usually private, we use mutators to change the object in a specified way without needing to know the instance variables B.setCharAt(0, ‘j’); // B == “jello there” B.delete(6,7); // B == “jello here” B.insert(6, “is “); // B == “jello is here”; These methods change the contents or properties of the StringBuilder object We use accessors and mutators to indirectly access the data, since we don’t have direct access – see ex9.java
104
Lecture 8: Simple Class Example
We can use these ideas to write our own classes Let’s look at a VERY simple example: IntCircle Instance variable: private int radius Cannot directly access it from outside the class Constructor: take an int argument and initialize a new circle with the given radius Accessors: public double area(); public double circumference(); public String toString(); Mutator: public void setRadius(int newRadius); See IntCircle.java and ex10.java (note COMMENTS!!!)
105
Lecture 9: More on Classes and Objects
Define the nature and properties of objects Objects Instances of classes Let’s learn more about these by developing another example together Goal: Write a class that represents a playlist (group of songs) Write a simple driver program to test it
106
Lecture 9: Developing Another Example
Remember the things we need for a class: Instance variables Fill in ideas from board Constructors Accessors Mutators
107
Lecture 9: Developing Another Example
Once we have the basic structure of the class we can start writing / testing it A good approach is to do it in a modular, step-by-step way Ex: Determine some instance variables, a constructor or two and an accessor to “output” the data in the class Write a simple driver program to test these features Once a method has been written and tested we don’t have to worry about it anymore! Add more to the class, testing it with additional statements in the driver program Let’s look at one example
108
Lecture 9: Intro. to Java Files
So far Our programs have read input from the keyboard and written output to the monitor This works fine in some situations, but is not so good in others: What if we have a large amount of output that we need to save? What if we need to initialize a database that is used in our program? What if output from one program must be input to another?
109
Lecture 9: Java Text Files
In these situations we need to use files Most files can be classified into two groups: Text Files and Binary Files We will focus on Text Files now and come back to Binary Files later A text file is simply a sequence of ASCII characters stored sequentially Any “larger” data types are still stored as characters and must be “built” when they are read in Ex: Strings are sequences of characters Ex: ints are also sequences of characters, but interpreted in a different way
110
Lecture 9: Java Text Files
To create an actual int we need to convert the characters into an integer – this is what the nextInt() method in the Scanner class does We will discuss the conversion procedure more later If we want to read data into an object with many instance variables, we can read each data value from the file then assign the object via a constructor or via mutators See PlayListTest.java If we want to fill an array, we can read in as many values as we need We may first need to read in how many values there are, then create the array and read in the actual data See PlayListTest.java and another example soon
111
Lecture 9: Java Text Files
Similarly, if we have data in our program that we wish to save to a text file, we need to first convert it into a sequence of characters (i.e. a String) Ex: the toString() method for a class However, now we need a different class that has the ability to write data to a file There are several classes in Java that have this ability For now we will focus on the PrintWriter A PrintWriter allows us to write primitive types and Strings to a text file See API
112
Lecture 9: Java Text Files
It is fairly simple to use See FileTest.java However, when creating the file an Exception can occur We will see how to handle this later For now we will “pass the buck” We do this via the “throws” clause in the method header States that we are not handling the exception Must be stated in a method where the exception could occur or in any method that calls a method … (since the exception is passed on)
113
So far (for the most part) we have stored data in a 1:1 fashion
Lecture 10: Arrays So far (for the most part) we have stored data in a 1:1 fashion 1 variable : 1 value (or object) This works fine if we know exactly how many values we will need to store, and if there are few of them However, consider the following scenario: We want to input the test scores of a given number of students, then 1) find the maximum, 2) minimum, 3) average and 4) list them in sorted order
114
We can do the first three things using only a few variables
Lecture 10: Arrays We can do the first three things using only a few variables Read in current score Add it to the sum If it is less than the minimum score, make it the minimum score If it is greater than the maximum score, make it the maximum score Repeat until all scores have been read Divide sum by number of scores to get average However, what about listing them in sorted order?
115
We can’t know the final order until all scores have been read
Lecture 10: Arrays We can’t know the final order until all scores have been read Last value could be smallest, largest or anywhere in between Thus, we need to store all of the values as they are being read in, THEN sort them and print them out To do this we need a good way to store an arbitrary number of values, without requiring the same number of variables This is a good example of where an array is necessary
116
Java Arrays In Java, arrays are objects, with certain properties
Lecture 10: Java Arrays Java Arrays In Java, arrays are objects, with certain properties Like other reference types Simply put, an array is logically a single variable name that allows access to multiple variable locations In Java, the locations also must be contiguous and homogeneous Each directly follows the previous in memory All references in the array are of the same type
117
Syntax: First, consider only PRIMITIVE TYPE data
Lecture 10: Java Arrays Syntax: First, consider only PRIMITIVE TYPE data We create a Java array in 2 steps: prim_type [] var_name; where prim_type is any primitive type where var_name is any legal identifier This creates array variable, but NOT an actual array var_name = new prim_type[arr_size] where arr_size is the number of elements that will be in the array Indexing in Java always starts at 0 This creates the array object
118
These two steps can be done as one if we’d like
Lecture 10: Java Arrays Ex: int [] myArray; myArray = new int[20]; // size can be a variable // or expression These two steps can be done as one if we’d like int [] myArray = new int[20]; Once we have created the array, we now need to put values into it Numeric types are initialized to 0 Booleans are initialized to false This is because the locations within an array are considered as instance variables within the array object We can change these values via indexing
119
Lecture 10: Java Arrays Indexing an array An array variable gives us access to the “beginning” of the array To access an individual location in the array, we need to index, using the [] operator Ex: myArray[5] = 250; myArray[10] = 2 * myArray[5]; myArray[11] = myArray[10] – 1; Show on board Discuss
120
Iterating through an array
Lecture 10: Java Arrays Iterating through an array We can easily iterate through an entire array using a loop (often a for loop) To know “when to stop” we access the length attribute of the array variabe – note the syntax for (int i = 0; i < myArray.length; i++) { System.out.print(“Value “ + i + “ = “ + myArray[i]); } Or we can iterate on the values without a counter for (int value : myArray) System.out.println(“Next value is : “ + value);
121
Lecture 10: Direct Access and Sequential Access
The previous two slides demonstrate the two basic ways of accessing arrays: Direct Access Arbitrary items are accessed by providing the appropriate index of the item Sequential Access Items are accessed in index order from beginning to end (or from end to beginning) The usefulness of arrays comes from allowing access in both of these ways Let’s see both direct and sequential access of arrays with a file example
122
Lecture 10: References and Reference Types
Recall from previous discussions that Java has primitive types and reference types Also recall (once again!) how they are stored With primitive types, data values are stored directly in the memory location associated with a variable With reference types, values are references to objects that are stored elsewhere in memory var1 100 s Hello There
123
Lecture 10: Arrays as Reference Types
Java arrays are reference types The array variable is a reference to the actual array If I assign the variable (as a whole) it does not change the array object But I can alter the contents of the array through indexing Ex: int [] A = new int[5]; for (int i = 0; i < 5; i++) A[i] = 2*i; int [] B = A; A[3] = 5; A = new int[4]; A[1] = 3; A[3] = 7; A 1 2 3 1 2 4 3 6 8 B 3 7 5
124
Lecture 10: Arrays as Parameters
Recall that all Java parameters are value A copy of the argument is passed to the param Changes to the parameter do not affect the argument What about arrays? Still passed by value, but now what is copied is the reference (i.e. the variable), NOT the object Thus the effect is that the parameter is another reference to the same object that the argument is a reference to We cannot change the argument variable in the method but we CAN mutate the array object!
125
Lecture 10: Arrays as Parameters
See ex11.java Sounds confusing, right? Not so much once you picture it! Show example on board We will also see an example shortly This allows us to change arrays within methods Ex: Read data into an array Ex: Remove data from an array Ex: Sort an array
126
Lecture 10: Searching an Array
Often we may want to see if a value is stored in an array or not: “Is this book in the library?” “Is Joe Schmoe registered for classes?” There are many searching algorithms available, some simple and some quite sophisticated We will start off simple here with Sequential Search
127
Lecture 10: Sequential Search
Start at the beginning of the array and check each item in sequence until the end of the array is reached or the item is found Note that we have two conditions here One stops the loop with failure (get to end) The other stops the loop with success (found item) We should always consider all possible outcomes when developing algorithms Q: What kind of loop is best for this? Think about what needs to be done Let’s look at an example: ex12a.java Answer: A while loop works best due to the compound condition
128
Lecture 11: Exam One Exam One
129
Lecture 12: Arrays of Objects
We have now seen how to create and use Java arrays of primitive types: int [] data; // declare variable (reference) data = new int[20]; // create array object … data[4] = 77; // index array to access locations How does it differ if we want arrays of objects? The first two steps are the same Declare variable Create array object In addition we must now create objects for the locations
130
Lecture 12: Arrays of Objects
However, remember that objects are accessed by reference types Thus, when we create the array, we have an array of references, with no objects yet All of the locations are initialized to null We need to create objects to store in the array separately For example: String [] names; names = new String[5]; names[1] = new String(“Herb”); names[3] = new String(“Madge”); names[4] = new String(“Mort”); names[0] and names[2] are still null Show on board See
131
Lecture 12: Arrays of Objects
Note that we have two levels of references here See PlayListTest.java for another example 1 2 3 4 names Herb Madge Mort
132
Lecture 12: Instance Data and Composition
When we create a new class we can have arbitrary instance variables within it If the instance variables are reference types (i.e. other classes) we say we are building a new class via composition We are “composing” the new class from pieces that already exist, putting them together in an appropriate way We briefly discussed this already with the PlayList class Also sometimes called aggregation Our use of these classes is limited to the functionality provided as public We are building new classes using “off the shelf” components, so we may have to compromise based on what the “off the shelf” components can do
133
Lecture 12: Instance Data and Composition
As a simple example, consider the Scramble class from Assignment 2 More than likely you have something like: Strings for the regular and scrambled words A Random object to "do the scrambling" Thus you are composing your Scramble class out of the existent String and Random classes From within Scramble: We are a client of String and Random, having access to only the public methods in the classes From outside Scramble: User may not even know a String is used since it is a private instance variable, and even more so for Random These variables are abstracted out of the user’s view
134
Lecture 12: Arrays as Instance Data
For another example, if an array is used as an instance variable We have the same access to the array within our class as we would anywhere else in our program However, from outside the class, we may not even know the array is being used Encapsulation and data hiding See ex12b.java and Scores.java Yet another example of composition is seen in our previous example PlayList.java From outside PlayList we do not even necessarily know that class Song is being used within PlayList
135
Lecture 12: Resizing an array
Java array objects can be of any size However once created, they cannot be resized This is fine if we know how many items we will need in advance: System.out.println("How many integers?"); int size = inScan.nextInt(); int [] theInts = new int[size]; However, we don't always know this in advance User may have an arbitrary amount of data and doesn't know how much until he/she has entered it Amount may vary over time Ex: Students in a university
136
Lecture 12: Resizing an array
So what do we do if we fill our array? Logically, we must "resize" it Physically, we must do the following: Create a new, larger array object Copy the data from the old array to the new Assign our reference to the new object Show on board This is not difficult syntactically, but it is important to realize that this takes time, especially if the array is large Clearly we don't want to do this too often A typical approach is to double the size, so we have a lot of free locations after the resizing For the "why" of this, take CS 0445!
137
Lecture 12: Resizing an array
What if we don’t have enough data to fill all of those new slots? We must keep track of the number of locations that are actually being used in the array i.e. we need an additional variable besides the array data itself This way we can “add” elements to the end of the array until it fills – only then will we have to resize Note that the array size and number of elements being stored in the array are not necessarily the same This is what is done in the predefined ArrayList class
138
Programmers can use arrays in arbitrary ways
Lecture 12: ArrayLists Programmers can use arrays in arbitrary ways However, many applications require a common set of array operations Ex: Add an object to the end of an array Ex: Find an object in an array Ex: Iterate through an array Rather than making the programmer implement these operations each time they are needed, the developers of Java have included a standard class that already does them ArrayList
139
Remember data abstraction?
Lecture 12: ArrayLists Remember data abstraction? We can use an ArrayList effectively without having to know how it is implemented We don’t need to know the internal data representation We don’t need to know the method implementation Ex: When and how is it resized? We simply need to look up its functionality in the Java API However, it is useful for computer scientists to understand how the ArrayList is implemented Helps us to better understand programming in general Helps us to implement similar types if necessary Look at a simple example: ArrayL.java
140
Idea: Data is maintained in two parts:
Lecture 12: ArrayLists Idea: Data is maintained in two parts: an array to actually store the information an int to keep track of the number of elements being stored Most of our operations are concerned with the logical size of the array Number of actual elements being stored The physical size of the array is abstracted out of our view This changes as necessary but we never need to know what it actually is in order to use the ArrayList Remember previous discussion on resizing
141
Lecture 12: ArrayLists We can also implement this type of variable size array ourselves if we want to We may want to do this if our needed functionality is very different from that of the ArrayList We simply need to keep an array and an int to keep track of the number of used locations You will do a simple example of this in Lab 6
142
Two-D arrays in Java are actually arrays of arrays
Lecture 13: 2-D Arrays Two-D arrays in Java are actually arrays of arrays int [][] A = new int[4][8]; The first index gives us a "row", which is an array of items We say this is "row major order" The second index gives us the "column", which is the specific item within the row Demonstrate on board To iterate through all locations we typically use nested loops See ex13.java
143
Lecture 13: Simple Sorting
What does it mean to sort our data? Consider an array, A of N items: A[0], A[1], A[2], …, A[N-1] A is sorted in ascending order if A[i] < A[j] for all i < j A is sorted in descending order if A[i] > A[j] for all i < j Q: What if we want non-decreasing or non-increasing order? What does it mean and how do we change the definitions?
144
Lecture 13: Simple Sorting
How do we sort? There are MANY ways of sorting data Sorting has been widely studied in computer science Some algorithms are better than others The most useful measure of “better” here is how long it takes to run The better algorithms run a lot more quickly than the poorer algorithms However, some very simple algorithms are ok if N is not too large We will look at a simple algorithm here In CS 0445 you will see other, better ways of sorting
145
Lecture 13: SelectionSort
SelectionSort is very intuitive: Idea: Find the smallest item and swap it into index 0 Find the next smallest item and swap it into index 1 Find the next smallest item and swap it into index 2 … Find the next smallest item and swap it into index N-2 What about index N-1? Let’s trace it on the board for the following data: Once we move the correct item into index N-1, the last item (index N-1) is in the correct place See text and Lab 6 for finding minimum value of an array. Note that sorting here is simply finding the minimum value and then swapping over and over – but considering a smalle array each time 1 2 3 4 5 6 7 35 50 20 40 75 10 15 60
146
Lecture 13: SelectionSort
Let’s look at the code SortInt.java and ex14.java (also see text handout) Note 1: Done in a modular way utilizing methods Trace it on the example from previous slide See result on board Note 2: The code shows another simple sorting algorithm, InsertionSort. Look over that as well Note 3: The sorts here are done in terms of only one type – int What if we want to sort different types of data? We can use Java Generics to allow our method to sort an array of arbitrary objects. We may look at this later after discussing inheritance and polymorphism and interfaces.
147
We could write a version of SelectionSort (or InsertionSort) for each
Lecture 13: Sorting We could write a version of SelectionSort (or InsertionSort) for each Lots of typing, where everything other than the types involved is the same for each one This is a key issue – the only difference in the sorts of different types is the data values and how they are compared The sorting algorithm is the same Is there a way we can do this without having to write the method so many times? Yes! Java Generics We will discuss this later after we discuss polymorphism and interfaces
148
Lecture 13: Binary Search
Consider Sequential Search again See previous slides and ex12a.java Note that in the worst case we look at every item in the array We say this is a linear run-time – or time proportional to N, the number of items in the array Can we do better? If the data is unsorted, no It could be any item, so in the worst case we’ll have to try them all What if we sort the data? Will that help? Consider example: Guess number from
149
Lecture 13: Binary Search
Idea of Binary Search: Searching for a given key, K Guess middle item, A[mid] in array If A[mid] == K, we found it and are done If A[mid] < K then K must be on right side of the array If A[mid] > K then K must be on left side of the array Either way, we eliminate ~1/2 of the remaining items with one guess Show on board for a search for 40 1 2 3 4 5 6 7 10 15 20 35 40 50 60 75
150
Lecture 13: Binary Search
What if item is not in array? We need a stopping condition in the “not found” case Think about what is happening with each test Either we move left index to the right or We move right index to the left Eventually they will “cross” – in this case the item is not found Idea is there is “nothing left” in the array to search Search previous array for 25 How to code this? Not difficult! We can do it with a simple while loop See author's code: BinarySearchDemo.java
151
Lecture 13: Binary Search
Notes: As with the version of SelectionSort we saw previously, this version of Binary Search only works for arrays of ints If we want to generalize it we need to write it in a slightly different way, using Java generics We will look at this later once we have discussed inheritance and interfaces
152
Lecture 13: Binary Search
So is Binary Search really an improvement over Sequential Search? Each “guess” removes ~½ of the remaining items Thus the total number of guesses cannot exceed the number of times we can cut the array in half until we reach 0 items Ex: => 6 Generally speaking, for N items in the array, in the worst case we will do ~log2N guesses This is MUCH better than Sequential Search, which has ~N guesses in the worst case You will discuss this more in CS 0445 and CS 1501
153
Lecture 14: Additional OO Notes
static variables Variables that are associated with the class itself rather than individual objects Can be accessed through the class using ClassName.variableName or through the objects using variableName from within an object objectName.variableName from outside an object Show logic of this on the board To access from class or from outside of an object, the data must be public Used when variables should be shared amongst all objects
154
Lecture 14: Additional OO Notes
When should I use a variable and when should I use a method? Variables should be used to store the basic properties of an object Can be changed through mutators but should not become "obsolete" Methods should be used to calculate / determine values using variables We don't want to waste time calculating something that is set However, if a value may change over time, it should be calculated Look again PlayList.java and PlayListTest.java
155
Lecture 14: Misc OO Notes Copying objects Sometimes, for various reasons, we need to make a copy of an object In Java there are two primary ways of doing this: Using a “copy constructor” for the class This method takes an argument of the same class type and makes a copy of the object Ex: String newString = new String(oldString); Using the “clone” method for a class This allows an object to “make a copy of itself” It is a bit more complicated to use We will defer it to CS 0445
156
Lecture 14: Misc OO Notes When copying objects, we always need to be aware of exactly WHAT is being copied: Shallow copy: Assign each instance variable in the old object to the corresponding instance variable in the new object If the instance variables are themselves references to objects, those objects will be shared See ex12b.java and Scores.java Deep copy: Copy primitive types normally For reference types, do not assign the reference; rather “follow the reference” and copy that object as well Note that this process could proceed through many levels
157
Neither shallow nor deep is necessarily correct or incorrect
Lecture 14: Misc OO Notes Deep copies tend to be more difficult to implement than shallow copies, due to the somewhat indefinite number of references that will have to be “followed” for the copy to be made Ex: A linked list, which you will see in CS 0445 Neither shallow nor deep is necessarily correct or incorrect It depends on the needs for a given class The important thing is to be AWARE of how your copies are being made and the implications thereof
158
Returning references from methods
Lecture 14: Misc OO Notes Returning references from methods We know a method can return only a single value However, that value can be a reference to an object which can contain an arbitrary amount of data We already discussed composition / aggregation, so we know an object can contain references to other objects within it Question: If an instance method is to return a reference to an object within another object, do we Return a reference to the actual object Return a reference to a copy of the object Answer: It depends
159
Lecture 14: Misc OO Notes What access do we need? Are we just looking at the object, or do we need to mutate it? If we want to mutate it, do we want the mutation to be local (i.e. in the copy) or should it impact the encompassing object? Text suggests returning copies, but, again, it depends on the goals What do we want to do with it? What if we need to update the data? A reference gives us access to do this easily
160
Lecture 14: Misc OO Notes The alternative is to return a copy, delete the original, update the copy, then reinsert it This is possible but a lot more work However, keep in mind that returning references to the “originals” is more dangerous than returning copies If we accidentally modify the object via the returned reference, that will impact the original encompassing object
161
Lecture 14: Misc OO Notes The this reference Often in instance methods you are accessing both instance variables and method variables If a method variable has the same name as an instance variable, updates will change the method variable, NOT the instance variable This is a common programming mistake!!! this is a pseudo-instance variable that is a self-reference to an object It allows disambiguation between instance variables and method variables See example on board
162
Lecture 14: Misc OO Notes Garbage Collection When a reference to an object is reassigned, the original object can no longer be accessed through that reference If there is no other reference to that object, then it cannot be accessed, period In this case the object has become garbage An object sitting in memory that can no longer be an active part of the program If a program produces a lot of garbage it can consume a lot of memory
163
Lecture 14: Misc OO Notes The garbage collector runs when needed to deallocate the memory taken up by garbage so that it can be reused The details of how it works are very interesting, but beyond the scope of this course
164
Much useful Java functionality relies on classes / objects
Lecture 14: Wrappers Much useful Java functionality relies on classes / objects Inheritance (Chapter 10) Polymorphic access (Chapter 10) Interfaces (Chapter 10) Unfortunately, the Java primitive types are NOT classes, and thus cannot be used in this way If I make an array of Object or any other class, primitive types cannot be stored in it
165
Wrapper classes allow us to get around this problem
Lecture 14: Wrappers Wrapper classes allow us to get around this problem Wrappers are classes that “wrap” objects around primitive values, thus making them compatible with other Java classes We can't store an int in an array of Object, but we could store an Integer Each Java primitive type has a corresponding wrapper Ex: Integer, Float, Double, Boolean Ex: Integer i, j, k; i = new Integer(20); j = new Integer(40);
166
Lecture 14: Wrappers The wrapper classes also provide extra useful functionality for these types Ex: Integer.parseInt() is a static method that enables us to convert from a String into an int Ex: Character.isLetter() is a static method that tests if a letter is a character or not See more in API Integer int Double double
167
Lecture 15: Wrappers and Casting
However, arithmetic operations are not defined for wrapper classes So if we want to do any “math” with our wrappers, we need to get the underlying primitive values If we want to keep the wrapper, we then have to wrap the result back up Logically, to do the following: k = i + j; The actual computation being done is k = new Integer(i.intValue() + j.intValue()); In words: Get the primitive value of each Integer object, add them, then create a new Integer object with the result
168
In Java 1.5 autoboxing was added
Lecture 15: Wrappers In Java 1.4 and before: Programmer had to do the conversions explicitly Painful! In Java 1.5 autoboxing was added This does the conversion back and forth automatically Saves the programmer some keystrokes However, the work STILL IS DONE, so from an efficiency point of view we are not saving Should not use unless absolutely needed We will see more on how wrappers are useful after we discuss inheritance, polymorphism and interfaces
169
Lecture 15: Parsing Primitive Types
One ability of the wrapper classes is static methods to parse strings into the correct primitive values Ex: Integer.parseInt(), Double.parseDouble(), Boolean.parseBoolean() These enable us to read data in as Strings, then convert to the appropriate primitive type afterward Ex: “12345” in a file is simply 5 ASCII characters: To convert it into an actual int requires processing the characters (as we discussed previously) However, let’s now see the actual algorithm
170
Lecture 15: Parsing Primitive Types
We know ‘0’ is ASCII 48 So our integer is (49-48)x104 + (50-48)x103 + (51-48)x (52-48)x101 + (53-48)x100 This can be done “manually” in a nice efficient way using a simple loop, and is what the parseInt() method does Let’s do it ourselves to see how it can be done Any suggestions on how to start? See MyInteger.java and ex15.java
171
Lecture 15: Character class
The Character wrapper class provides many useful methods: Ex: Case conversion, checking for letters, checking for digits Can be useful when we are parsing text files ourselves The String class has some very useful methods as well See text for a lot of them (ex: split()) See ex16.java
172
We can achieve this in object-oriented languages using inheritance
Lecture 15: Inheritance Sometimes we want to build a new class that is largely like one we already have Much of the functionality we need is already there, but some things need to be added or changed We can achieve this in object-oriented languages using inheritance Attributes of a base class, or superclass are passed on to a subclass
173
Lecture 15: Inheritance and “is a”
We can understand this better by considering the “is a” idea A subclass object “is a” superclass object However, some extra instance variables and methods may have been added and some other methods may have been changed Note that “is a” is a one way operation Subclass “is a” superclass (specific "is a" general) With modifications / additions Superclass is NOT a subclass (general not "is a" specific) Missing some properties Ex: ArrayList “is a” AbstractList
174
Lecture 15: Inheritance and “is a”
AbstractList is a is a is a AbstractSequentialList ArrayList Vector AbstractSequentialList, ArrayList and Vector are all AbstractLists LinkedList “is a” AbstractSequentialList However, an AbstractList is not necessarily an AbstractSequentialList, ArrayList or Vector “Is a” is a one way relationship is a LinkedList
175
Lecture 15: Extending Classes
Inheritance in Java is implemented by extending a class public class NewClass extends OldClass { … We then continue the definition of NewClass as normal However, implicit in NewClass are all data and operations associated with OldClass Even though we don’t see them in the definition This is important! Don't forget this!
176
Lecture 15: private, public and protected
We already know what public and private declarations mean The protected declaration is between public and private Protected data and methods are directly accessible in the base class and in any subclasses (and in the current package) However, they are not directly accessible anywhere else Note that private declarations are STILL PART of subclasses, but they are not directly accessible from the subclass’ point of view See SuperClass.java, SubClass.java, Subby.java and ex17.java
177
Lecture 16: Inheritance Example
As another example Compare MixedNumber class and MixedNumber2 class Both utilize the RationalNumber class from the Lewis & Loftus text to do most of the "work" Both also have the same functionality, but MixedNumber uses composition and MixedNumber2 uses inheritance Note simplicity of MixedNumber2 methods Read over the comments carefully! See ex18.java, RationalNumber.java, MixedNumber.java and MixedNumber2.java
178
Lecture 16: Inheritance Example
RationalNumber Lecture 16: Inheritance Example int numerator int denominator add(), subtract(), multiply(), divide(), etc. Composition: MixedNumber class utilizes a RationalNumber object. Methods in MixedNumber must manipulate the RationalNumber object as a "client", since it has no special relationship to RationalNumber MixedNumber int whole RationalNumber frac add(), subtract(), multiply(), divide(), etc. Inheritance: MixedNumber2 class is a RationalNumber, but with modifications. Ex: The numerator in MixedNumber2 is that defined in RationalNumber. Methods in RationalNumber can be used directly, and new versions are only needed where the return type must be MixedNumber2. MixedNumber2 extends RationalNumber RationalNumber int numerator int denominator add(), subtract(), multiply(), divide(), etc. add(), subtract(), multiply(), divide(), etc.
179
Lecture 16: Inheritance Example
Note Lines in ex18.java In this code we are using RationalNumber references to access both RationalNumber and MixedNumber2 objects This is legal due to the "is a" relationship of MixedNumber2 to RationalNumber We will examine this type of access in more detail soon when we discuss polymorphism Important Note (will be repeated): When a superclass reference is used to access a subclass object The only methods that are callable are those that were initially defined in the superclass The object may have additional methods (defined initially in the subclass) that cannot be called
180
Lecture 16: Java Class Hierarchy
In Java, class Object is the base class to all other classes If we do not explicitly say extends in a new class definition, it implicitly extends Object The tree of classes that extend from Object and all of its subclasses is called the class hierarchy All classes eventually lead back up to Object This will enable consistent access of objects of different classes, as we shall see shortly
181
Lecture 16: Polymorphism
Idea of polymorphism See internet definition: On Google type “definition polymorphism” and see the results This search works for many CS terms that you may be curious about Generally, it allows us to mix methods and objects of different types in a consistent way Earlier in the text, one type of polymorphism was already introduced
182
Lecture 16: Method Overloading
This is called ad hoc polymorphism, or method overloading In this case different methods within the same class or in a common hierarchy share the same name but have different method signatures (name + parameters) public static float max(float a, float b) public static float max(float a, float b, float c) public static int max(int a, int b) Note: The return value is not considered to be part of the signature When a method is called, the call signature is matched to the correct method version Note: This is done during program COMPILATION
183
Lecture 16: Method Overloading
If an exact signature match is not possible, the one that is closest via “widening” of the values is used “Widening” means that values of “smaller” types are cast into values of “larger” types Ex: int to long int to float float to double Fewer widenings provides a "closer" match If two or more versions of the method are possible with the same amount of “widening”, the call is ambiguous, and a compilation error will result See ex19.java Note: This type of polymorphism is not necessarily object-oriented – can be done in non-object-oriented languages
184
Lecture 17: Polymorphism
Subclassing Polymorphism Sometimes called “true polymorphism” Consists basically of two ideas: Method overriding A method defined in a superclass is redefined in a subclass with an identical method signature Since the signatures are identical, rather than overloading the method, it is instead overriding the method For subclass objects, the definition in the subclass replaces the version in the superclass See OverrideDemo.java, MyAList.java, SortAList.java
185
Lecture 17: Polymorphism
Dynamic (or late) binding The code executed for a method call is associated with the call during run-time The actual method executed is determined by the type of the object, not the type of the reference Allows superclass and subclass objects to be accessed in a regular, consistent way Array or collection of superclass references can be used to access a mixture of superclass and subclass objects This is very useful if we want access collections of mixed data types (ex: draw different graphical objects using the same draw() method call for each)
186
Lecture 17: Polymorphism
Ex. Each subclass overrides the move() method in its own way Animal [] A = new Animal[3]; A[0] = new Bird(); A[1] = new Person(); A[2] = new Fish(); for (int i = 0; i < A.length; i++) A[i].move(); Animal move() move() References are all the same, but objects are not move() method invoked is that associated with the OBJECT, NOT with the reference move()
187
Lecture 17: Object, Method and Instance Variable Access
When mixing objects of difference classes, some access rules are important to know: Superclass references can always be used to access subclass objects, but NOT vice versa Animal A = new Bird(); // this is ok Bird B = new Animal(); // this is an ERROR Given a reference R of class C, only methods and instance variables that are defined (initially) in class C or ABOVE in the class hierarchy can be accessed through R They still exist if defined in a subclass, but they are not accessible through R
188
Lecture 17: Object, Method and Instance Variable Access
Ex: Suppose class Fish contains a new instance variable waterType and a new method getWaterType() Fish F = new Fish(); Animal A = new Fish(); System.out.println(F.getWaterType()); // ok System.out.println(A.getWaterType()); // NO! The above is NOT legal, even though the method exists for class Fish. The reason is that the method is not visible from the reference’s point of view (A is an Animal reference so it can only “see” the data and methods defined in class Animal) System.out.println(((Fish) A).getWaterType()); This is ok, since we have now cast the reference to the Fish type, which CAN access the method
189
Lecture 17: Object, Method and Instance Variable Access
Note that we can access these methods or instance variables INDIRECTLY if an overridden method accesses them So, for example, if the move() method as defined in class Fish called the getWaterType() method, and we called A.move(); It would work fine Also note that if we cast a reference to a different type, and the object is not that type (or a subtype), we will get ClassCastException If unsure, test using instanceof operator before casting See ex20.java for an example
190
Lecture 17: Object, Method and Instance Variable Access
To summarize: Superclass references CAN BE used to reference subclass objects Subclass references CANNOT BE used to reference superclass objects The type of the reference determines what data and methods are ACCESSIBLE The type of the object determines what data and methods EXIST Methods and data initially defined within a subclass CANNOT BE accessed via a superclass reference The type of the object also determines which VERSION of an overridden method is called
191
Lecture 17: Abstract Classes
Sometimes in a class hierarchy, a class may be defined simply to give cohesion to its subclasses No objects of that class will ever be defined But instance data and methods will still be inherited by all subclasses This is an abstract class Keyword abstract used in declaration One or more methods may be declared to be abstract and are thus not implemented No objects may be instantiated
192
Lecture 17: Abstract Classes
Subclasses of an abstract class must implement all abstract methods, or they too must be declared to be abstract Advantages Can still use superclass reference to access all subclass objects in polymorphic way However, we need to declare the methods we will need in the superclass, even if they are abstract No need to specifically define common data and methods for each subclass - it is inherited Helps to organize class hierarchy See ex21.java
193
Lecture 17: Java Interfaces
Java allows only single inheritance A new class can be a subclass of only one parent (super) class There are several reasons for this, from both the implementation (i.e. how to do it in the compiler and interpreter) point of view and the programmer (i.e. how to use it effectively) point of view However, it is sometimes useful to be able to access an object through more than one superclass reference
194
Lecture 17: Java Interfaces
We may want to identify an object in multiple ways: One based on its inherent nature (i.e. its inheritance chain) Ex: A Person Classes are used to identify objects in this way Others based on what it is capable of doing Ex: A swimmer Ex: A musician Ex: A performer Note a Person can potentially do many things They can also be identified by this ability Interfaces are used to identify objects in this way
195
Lecture 17: Intro. to Interfaces
A Java interface is a named set of methods However, no method bodies are given – just the headers [See note at bottom of this slide] Static constants are allowed, but no instance variables are allowed Any Java class (no matter what its inheritance) can implement an interface by implementing the methods defined in it Essentially an interface is stating an ABILITY of the class A given class can implement any number of interfaces Since Java 8 interfaces are allowed to have default methods. These are methods that are defined within the interface and that become part of any class that implements the interface.
196
Lecture 17: Intro. to Interfaces
Ex: public interface Laughable { public void laugh(); } public interface Booable public void boo(); Any Java class can implement Laughable by implementing the method laugh() Any Java class can implement Booable by implementing the method boo()
197
Lecture 17: Intro. to Interfaces
Ex: public class Comedian implements Laughable, Booable { // various methods here (constructor, etc.) public void laugh() System.out.println(“Ha ha ha”); } public void boo() System.out.println(“You stink!”); Note that in the class header we must declare that the interfaces are implemented
198
Lecture 17: Intro. to Interfaces
An interface variable can be used to reference any object that implements that interface Note that the same method name (ex: laugh() below) may in fact represent different code segments in different classes But only the interface methods are accessible through the interface reference Thus, even though a single class may implement many interfaces, if it is being accessed through an interface variable, the methods in the other interfaces are not available The interface masks the object such that only the interface methods are visible / callable If other methods are attempted to be accessed, a compilation error will result
199
Lecture 17: Intro. to Interfaces
Ex: Laughable [] funny = new Laughable[3]; funny[0] = new Comedian(); funny[1] = new SitCom(); // implements Laughable funny[2] = new Clown(); // implements Laughable for (int i = 0; i < funny.length; i++) funny[i].laugh(); funny[0].boo(); // illegal even though Comedia // has the boo() method See ex22.java Interfaces are closely related to inheritance and polymorphism
200
Recall our previous discussion of polymorphism
Lecture 18: Interfaces Recall our previous discussion of polymorphism This behavior also applies to interfaces – the interface acts as a superclass and the implementing classes implement the actual methods however they want An interface variable can be used to reference any object that implements that interface However, only the interface methods are accessible through the interface reference Recall our previous example: Laughable [] funny = new Laughable[3]; funny[0] = new Comedian(); funny[1] = new SitCom(); // implements Laughable funny[2] = new Clown(); // implements Laughable for (int i = 0; i < funny.length; i++) funny[i].laugh(); Same polymorphic behavior we saw with Animal hierarchy
201
Lecture 18: "Generic" Operations
How does it benefit us to be able to access objects through interfaces? Sometimes we are only concerned about a given property of a class The other attributes and methods still exist, but we don't care about them for what we want to do For example: Sorting We can sort a lot of different types of objects Various numbers People based on their names alphabetically Movies based on their titles Employees based on their salaries Each of these classes can be very different However, something about them all allows them to be sorted
202
Lecture 18: “Generic” Operations
They all can be compared to each other So we need some method that invokes this comparison In order to sort them, we don't need to know or access anything else about any of the classes Thus, if they all implement an interface that defines the comparison, we can sort them all with a single method that is defined in terms of that interface Huh? ¿Qué? Perhaps it will make more sense if we develop an example…but first we will need some background! We can’t write a method that can sort “anything”, but we can write a method that can sort any Comparable objects – note the use of the interface here
203
Lecture 18: “Generic” Operations
Consider the Comparable interface: It contains one method: int compareTo(Object r); Returns a negative number if the current object is less than r, 0 if the current object equals r and a positive number if the current object is greater than r Look at Comparable in the API Consider what we need to know to sort data: is A[i] less than, equal to or greater than A[j] Thus, we can sort Comparable data without knowing anything else about it Awesome! Polymorphism allows this to work
204
Lecture 18: “Generic” Operations
Think of the objects we want to sort as “black boxes” We know we can compare them because they implement Comparable We don’t know (or need to know) anything else about them Show on board Thus, a single sort method will work for an array of any Comparable class Let’s write it now, altering the code we already know from our simple sort method See SortAll.java and ex23.java Also see SortAllT.java and ex23T.java
205
Lecture 18: Graphical Interfaces
So far all of our programs have used Input from the keyboard (or file) Output to the console (or file) This is effective but in today’s world is not so user-friendly Users want to use the mouse Users want windows with dialog boxes and buttons Users need maximum guidance with minimum room for error
206
Lecture 18: Graphical Interfaces
Java has all of the tools for us to design and implement complex graphical interfaces Graphical output and use of a mouse and other graphical components for input Ex: Windows with buttons, textfields, pulldown menus, radiobuttons, labels, and more To use these tools we need to learn some Java classes and some programming theory But once we learn how to do it we will typically prefer it over console applications
207
Lecture 18: AWT and Swing The AWT (Abstract Windowing Toolkit) was developed for the first versions of Java Created components such as Frame, Panel, Button, TextField, Label However, the look and feel of the AWT varied on different windowing systems The same AWT Java program looks different when run on MS Windows machines, MACs and Sun Workstations This is because the underlying windowing systems on those machines differ
208
Lecture 18: AWT and Swing Since a goal of Java is to be platform independent, its look and feel should also be platform independent Swing was developed from Java v. 1.2 to be more consistent in its look and feel across all platforms It also adds some extra features that did not exist in the AWT Many Swing components are similar to AWT in name, but with a “J” in front Ex: JFrame, JPanel, JButton, JTextField, JLabel
209
JavaFX JavaFX is a “Set of graphics and media packages that enables developers to design, create, test, debug and deploy rich client applications that operate consistently across diverse platforms” -- from Oracle JavaFX docs As more programming moves toward Web interfaces, JavaFX will gain in popularity Can be used with Swing as well, so learning Swing is still a good thing We will not cover JavaFX but it is worth looking into
210
Lecture 18: JFrames and JApplets
JFrames are objects that will be the windows in graphical applications We can draw/paint graphics within them We can place and manipulate graphical components within them JApplets are similar in their functionality to JFRames However, they are run within the context of another program (i.e. a Web browser) Used to be very popular, but not so much any more
211
We will focus on JFrames
Lecture 18: JFrames We will focus on JFrames To use them we: Create a JFrame object Size it as desired Show it on the display Once we have a JFrame we can do a LOT with it Draw graphics within it Store and organize other components React to events such as mouse movement and clicking We will gradually be looking at all of these things
212
JLabels are simple components to show formatted text on the display
Lecture 18: JLabels JLabels are simple components to show formatted text on the display We can set the font type, size and color We can set and change the text itself as desired throughout program execution Let’s look at a very simple example: Create a JFrame, then put a JLabel in it and display it See ex24a.java See the comments to determine how the various objects are created and set up properly
213
Lecture 18: Simple Example
Note that this example does not really do much No interaction with the user But it does show us some of the basic setup for graphical applications Let’s now add a bit more functionality Add a button that user can click to change the color of the label text
214
JButtons are simple components that can also show text on the display
Lecture 18: JButtons JButtons are simple components that can also show text on the display However, in addition to showing text, they also respond to clicks of the mouse If a user clicks the mouse within a JButton, an ActionEvent object is generated in response This object is passed automatically to an ActionListener object The ActionListener must be registered to “listen” to the JButton ActionListener is actually an interface with the single method actionPerformed() Remember interfaces?
215
Lecture 18: Event-Driven Programming
Thus any class that implements actionPerformed() can be an ActionListener This causes the actionPerformed method within the ActionListener to execute It is the actionPerformed method that is doing the actual response to the button click This idea is called event-driven programming As program executes, user generates events in various ways Ex: click a button, move the mouse, edit text Programmer writes code to respond to the various events that may occur See trace on next slide (run as a presentation to see effects)
216
Lecture 19: Event-Driven Programming
AE JButton ActionListener object public void actionPerformed( ) { // code to execute } JButton is clicked ActionEvent (AE) generated Event passed to ActionListener actionPerformed executed Note that because the ActionEvent is passed to the actionPerformed method, the method can get information from the ActionEvent through its accessor methods
217
Lecture 19: Event-Driven Programming
There are many different types of events in Java programs, but the basic idea for all of them is similar to that shown in the previous slide: In some way an event is triggered Triggered object generates an event object Event object is passed to some event listener object Method in the event listener executes to handle the event It is important that event handlers are linked to the appropriate event generators Otherwise event will still be generated but will not be responded to Do example in class See ex24b.java
218
Lecture 19: Another Example
Let’s look at another simple example: Toggle Button Click it once and it does an action Click it again and it does a different action Each click it alternates between the two actions The setup of this program is very similar to ex24b.java Only difference is what the listener is doing See ex24c.java
219
Lecture 19: Multiple Components
If we want to have multiple components, we need to determine how to lay them out To do this we use a layout manager These determine how components appear in a window and how much space is allocated for them There are many layout managers in Java Two simple ones are: FlowLayout Places components as we read a book – left to right top to bottom GridLayout Places components in an equally sized 2-dimensional rectangular grid
220
Lecture 19: Multiple Components
If multiple components generate events, we must also manage our listeners Do we share a listener between components? Ex: ex24b2.java Do we have a separate listener for each component? Ex: ex24b3.java Neither is right or wrong – but they behave differently We need to know which is better for a given situation
221
Lecture 19: Multiple Components
Multiple components may also need to interact with each other Listener for one component may need to access the other component In this case we must allow the listener access to all components involved -- so it must be different from how we did it in ex24b.java and ex24c.java Ex: Consider a JTextField This is a component in which the user can enter text Once user hits “Enter”, the component generates an ActionEvent Same event generated by a JButton
222
Lecture 19: Multiple Components
We can use this to process input from a user For example to change the contents of a JLabel or a JButton Let’s look at another example Our JFrame will have a JButton and a JTextField The JButton will behave as in ex24b – clicking it will change the color of the text The JTextField will allow us to enter new text for the JButton We will also set things up differently to allow for more convenient access See ex24d.java
223
What if we want different parts of our window laid out differently?
Lecture 19: More on GUIs What if we want different parts of our window laid out differently? There is a GridBagLayout that allows for arbitrary configurations, but it is quite complicated to use A simpler solution is to subdivide our window We can do this with JPanels Have most of the functionality of JFrames, except without the title/menu bar Can store other components and lay them out using a layout manager
224
When doing this, a common way of laying out our JFrame is BorderLayout
Lecture 19: More on GUIs So now we can use the layout manager of our JFrame to store our JPanels We can then use our JPanels to store our other components See drawing on board When doing this, a common way of laying out our JFrame is BorderLayout BorderLayout subdivides our window into 5 areas NORTH, SOUTH, EAST, WEST, CENTER We can put a component in each area or just some of them If the component is a JPanel, we can then put our other components within that
225
How to terminate a graphical program?
Lecture 19: More on GUIs How to terminate a graphical program? So far we have set an option in the JFrame that causes the program to stop when it closes: theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); However, we may want to quit in some other way Ex: A menu option or a "quit" button We can do this with the System.exit(0); method call However, we need to make sure the method is called only when we really want to quit the program Use a listener (ex: ActionListener) See Counters.java
226
Lecture 20: More on JPanels
What if we want to encapsulate data within a JPanel? The JPanel class contains instance variables and methods, but these are geared toward its graphical function We can attach components to it but this is solely for display purposes The variables are still outside the JPanel What if we want it to also store and manipulate our own data in the JPanel? We need to extend it using inheritance
227
Lecture 20: Extending JPanels
So, we can do this: class MyPanel extends JPanel We can then put whatever we’d like into our new class We can add new instance variables, methods or both Now our new class has all of the functionality of the original class The abilities of any Java JPanel to store, arrange and manipulate components Plus any new functionality that we give it via additional instance variables and methods Things like this are what make inheritance great! See Counters2.java and JPanelDemo.java
228
Lecture 20: Other GUI Features
Java has a lot of other classes / interfaces to allow us to build GUIs See text and Java API for some examples Here is a simple example demonstrating MouseEvents and some other things: Mousey.java
229
Lecture 20: Intro. to Exceptions in Java
Run-time errors happen User enters incorrect input Resource is not available (ex. file) Logic error (bug) that was not fixed For Production software Having a program "crash" is a HIGHLY UNDESIRABLE thing Users think software is no good Lose confidence
230
Lecture 20: Intro. to Exceptions in Java
An occurrence of an erroneous, unusual or unexpected event in a program execution In older languages Code the handling of exceptions into each area of the program that needed it, typically with if statements Some exceptions could not even be handled by the HLL ex. standard Pascal cannot handle I/O errors or division by 0 Ask for integer and user enters a text string – what do you do? Discuss
231
Lecture 20: Intro. to Exceptions in Java
In newer languages Exception handling built into the language We can separate exception handling from the "main line" code Java uses an exception handling model similar to that used in C++ Exceptions are objects that are thrown … and catched Some exceptions are built into the language Others can be created and thrown by the programmer
232
Lecture 20: Exceptions in Java
Java exception handling Exceptions are handled using try-catch blocks try { // code that will normally execute } catch (ExceptionType1 e) { // code to "handle" this exception catch (ExceptionType2 e) ... // can have many catches finally { // code to "clean up" before leaving try block
233
Lecture 20: Exceptions in Java
If all goes well (no exceptions occur) Code in try block is executed, followed by code in (optional) finally block If an exception occurs anywhere in the try block Execution immediately jumps out of the try block (i.e. the try block does not complete its execution) An exception handler is sought in a catch block If exception is handled in a catch block, that block executes followed by the (optional) finally block If the exception is not handled in a catch block, the (optional) finally block is executed and then the exception is propagated Note that in all cases the finally block is executed if it is present
234
Lecture 20: Exceptions in Java
If an exception is handled Execution resumes immediately AFTER try/catch block in which it was handled, and does NOT return to throw point termination model of exception handling As opposed to a resumption model, where execution resumes from where the exception occurred If an exception is propagated A handler is searched for by backing up through the call chain on the run-time stack This is dynamic exception propagation If no handler is ever found Console applications crash and report exception GUI applications will continue to execute, but may be in an inconsistent state – more soon Demonstrate propagation on board
235
Lecture 20: Exceptions in Java
Checked vs. Unchecked exceptions Checked exceptions If a method does NOT handle these, the method MUST state that it throws them Done in a throws clause in the method header These include IOException, and InterruptedException (and their subclasses) That is why various handouts throughout the term have had some exception handling – it was required Unchecked exceptions Method not required to explicitly "throw" these These include RunTimeException and Error
236
Lecture 20: Exceptions in Java
Catching exceptions Catching a superclass of an exception will catch subclass exception objects catch (Exception e) "catch all" if no other exceptions match Should list exceptions in order of most specific to most general If catch above is first NO OTHER catches in the block could ever execute It is better style to be as specific as possible with the exceptions that are caught See ex25.java
237
Lecture 20: Exceptions in GUIs
GUIs run using multiple execution threads A thread is a logically separate execution chain that shares the same data See board Events in GUIs are generated and handled by threads In future courses you may see how to use threads yourselves For now we just want to know the effect of exceptions on applications that have multiple threads
238
Lecture 20: Exceptions in GUIs
If the thread in which the exception was thrown does not handle it, the thread will terminate However, other threads will continue the execute, so GUI may continue to run This does NOT mean that it will run correctly The exception may have caused a problem that persists in the GUI Don't think that because the window didn't close that everything is ok It is best to always try to anticipate and handle exceptions in GUIs
239
Lecture 20: Defining Exception Classes
Just like most Java classes, Exception classes can be extended There are many predefined exceptions, designed for different circumstances However, we may have a specific issue that we’d like to create a new exception class for Note that if our class is a subclass of some other exception class, it can be caught using the superclass exception, or the subclass exception See MiniCalcTwo.java, DoMathInt.java, DoMathIntCheck.java
240
A Java method can call any other public Java method
Lecture 21: Recursion A Java method can call any other public Java method main() is just a method itself, and we have called other methods from it Thus, a method should be able to call itself – we call this a RECURSIVE CALL Since it is a method At first thought this seems odd or even impossible – why would we want to do this? However, it will be very useful in a lot of different programming approaches
241
Some mathematical functions are in fact defined recursively
Lecture 21: Recursion Before we look at the programming in detail, let’s try to get the idea down, using math Some mathematical functions are in fact defined recursively Example in text: Factorial N! = N * (N-1)! Note that the function is defined in terms of itself, but with an important change: The “recursive call” is smaller in size (N-1) than the original call (N) This is vital to recursion being viable Let’s trace 4! in this way to see what happens (see board) Uh oh! The recursive calls never stop!
242
What is the base case for factorial?
Lecture 21: Recursion What we are missing in the previous slide is a condition that allows the recursion to stop Every recursive algorithm must have some terminating condition, to keep it from recursing “forever” We call this the BASE CASE What is the base case for factorial? This now allows us to complete our algorithm: 0! = 1 N! = N * (N-1)! when N > 0 N! = 1 when N = 0
243
Three important rules for any recursive algorithm:
Lecture 21: Recursion Three important rules for any recursive algorithm: There must be some recursive case, in which the algorithm “calls itself” There must be some base case, in which no recursive call is made The recursive calls must lead eventually to the base case Usually by “reducing” the problem size in some way Don’t forget these!
244
Lecture 21: More Recursion
Let’s look at another example: Calculating an integer power of another integer MN = Don’t forget the base case The actions we take are slightly different from factorial, but the basic idea is similar Trace this on board Note how first call made is last call to complete This is important in the implementation of recursion M * MN-1 N > 0 recursive case 1 N = 0 base case
245
Lecture 21: Implementing Recursion
So how do we implement recursion? Luckily the computer code is very similar to the mathematical functions Consider factorial below Note that the recursive call is made within the return statement This is fine – return is done AFTER call completes public static int fact(int N) { if (N <= 1) return 1; else return (N * fact(N-1)); }
246
Lecture 21: Implementing Recursion
How does recursion actually work? Each time a method is called, an activation record (AR) is allocated for it This consists of memory for the parameters and local variables used in the method Each new activation record is placed on the top of the run-time stack When a method terminates, its activation record is removed from the top of the run-time stack Thus, the first AR placed onto the stack is the last one removed
247
Lecture 21: Implementing Recursion
N <= 1? YES return fact(1) 1 N = 2 N <= 1? NO return (2 * fact(1)) = 1 fact(2) 2 N = 3 N <= 1? NO return (3 * fact(2)) = 2 fact(3) 6 N = 4 N <= 1? NO return (4 * fact(3)) = 6 fact(4) 24 24
248
Lecture 21: Recursion vs. Iteration
Some recursive algorithms can also be easily implemented with loops Both factorial and power can easily be done in this way When possible, it is usually better to use iteration, since we don’t have the overhead of the run-time stack (that we just saw on the previous slide) Other recursive algorithms are very difficult to do any other way (ex: Towers of Hanoi in text) You will see more about recursion in CS 0445 For now, let’s look at recursion.java Also look at many handouts in the text
249
Same length and general format as Exam One Focus on Lectures 12-21
Lecture 22: Exam Two Same length and general format as Exam One Focus on Lectures 12-21 See online review materials and practice questions See next slides (250+) for some extra material – this material will not be on the exam
250
Extra Material: File Types
Text Files – discussed previously Advantage of text files: Can read them outside of the program by many different editors or programs Easy to create Disadvantage of text files: Must be converted into the desired types as they are read in (as demonstrated with parseInt) This takes time to do and slows I/O Not the most efficient way to store non-String data Ex: int requires 8 bytes in a text file, but only needs 4 bytes in the computer as an int or in a binary file
251
Extra Material: Binary Files
Data in the file is stored in the same way (or in a “serialized” version) that it is stored in the program We can store arbitrary bytes or we can store “whole” data types, including primitive types (int, double, etc.) and objects (String, any other Serializable object type) We will discuss Serializable more shortly
252
Extra Material: File Types
Advantages: Since data is already in its binary form, reading and writing require little if any conversion and is faster than for text files Non-string data can often be stored more efficiently in its binary form than in ASCII form Disadvantage: Data in the files is not readable except via a specific computer program Ex: A Java object in a file can only be read in by a Java program There are reasons to use both of these types of files in various applications
253
Extra Material: IO Streams
In Java, file access is provided through a hierarchy of file and stream classes These allow various different access functionalities implemented in a systematic, consistent way Often we “wrap” streams around others to provide more specific access Stream wrappers are a similar notion to our primitive type wrappers – in both cases we are wrapping an object around other data to increase the functionality of the data However, in this case the data being “wrapped” is already an object
254
Extra Material: IO Streams
We have already seen a couple of these: Scanner (input), PrintWriter (output) There are many other IO Streams that we can use in our programs The choice depends on the functionality that we want to wrap around the underlying file Ex: For text files, PrintWriter is nice since it allows us to write out strings Ex: For binary files of primitive types, DataOutputStream is good since it allows us to write each of the primitive types
255
Extra Material: Text vs. Binary Files
We discussed previously that numeric data can often be stored more efficiently in binary form than in text form Let's compare the two by writing the same data (numbers) to a text file and a binary file Since the data is just numbers we can use a DataOutputStream for our output Allows only simple methods such as writeInt(), writeDouble(), etc
256
Extra Material: Text vs. Binary Files
Let’s try this and then compare the sizes of the binary and text files We will generate a number of random ints and random doubles Store each in a text file and in a binary file and compare sizes at the end Note that the size of the integer text file depends greatly on the values of the integers, while the size of the integer binary file is independent of the values If we are storing very small integers, using a text file will actually save us space, but for large integers it will cost us space See ex26.java
257
Extra Material: Object Streams
Java has the ability to write entire objects to files in a serialized form The class type as well as the instance variables are written in a way that allows the object to be restored easily upon reading This is done utilizing the ObjectOutputStream and ObjectInputStream classes It will only work if the class implements the Serializable interface Note that if the class uses composition, all data within it must also implement Serializable See ex27a.java, ex27b.java
258
Extra Material: Preview of Data Structures
In Data Structures, we want to learn, understand and be able to utilize many of the data structures that are fundamental to computer science Data structures such as vectors, stacks, queues, linked-lists and trees are used throughout computer science We should understand these from a user's point of view: What are these data structures and how do I use them in my programs?
259
Extra Material: Preview of Data Structures
We also want to understand implementation issues related to these data structures, and to see how they can be implemented in the Java programming language Data structures can be implemented in various ways, each of which has implications (ex: run-time differences, code complexity, modifiability) We should understand these data structures from an implementer's point of view: How can these data structures be effectively implemented?
260
Extra Material: Preview of Data Structures
We also want to understand and utilize programming ideas and techniques utilized in data structure implementation Object-oriented programming, dynamic memory utilization, recursion and other principles must be understood in order to effectively implement data structures What tools must I know and be able to use in order to implement data structures?
261
Extra Material: Preview of Data Structures
We also want to learn more of the Java programming language and its features, and to become more proficient at programming with it Java is a very large language with extensive capabilities As your programming skills improve, you can utilize more of these capabilities effectively Since I am working with Java, how well can I learn and use the language and its features?
262
Extra Material: Preview of Data Structures
Example: Consider the idea of a List: Ordered (by position), indexable collection of data In Java this is an interface – with some methods as shown: void add(int index, Object element) Add a new object at the specified index int indexOf(Object o) Find the object and return its index Object get(int index) Return the object at the specified index Object remove(int index) Remove (and return) the object at the specified index
263
Extra Material: Preview of Data Structures
We can implement a List in different ways ArrayList Use an array as the underlying data structure You are already familiar with this LinkedList Use a linked list of nodes as the underlying data structure See singly linked list below Actual Java implementation is a doubly linked list More details in CS 0445! Head
264
Extra Material: Preview of Data Structures
Each implementation has advantages and disadvantages Ex: Advantage of ArrayList get(i) can be done in one step, since we just go to that index in the array In a LinkedList we must follow references down the list Ex: Advantage of LinkedList add(0, obj) requires only creating a new object and linking it correctly to front of list In an ArrayList we must shift all of the items from 0 down a spot in order to make "room" at index 0
265
Extra Material: Preview of Data Structures
Queue and Stack Two fundamental data structures used through computer programming Queue: Data managed First In First Out (FIFO) Stack Data managed Last In First Out (LIFO) Manipulation in other ways is not (or should not be) allowed Using data abstraction and encapsulation we can implement these nicely
266
Extra Material: Preview of Data Structures
In CS 0445 you will see these and other implementation ideas in detail Ex: See ex28.java Note that the showList method works for all of the objects, using the Collection interface However, the underlying objects are different and give different functionalities and efficiencies More in CS 0445!
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.