allNotes_blank
allNotes_blank
Contents
Syllabus, Introduction ............................................................................................................................................. 2
Variables, Console IO ............................................................................................................................................. 4
Branching (conditionals) ......................................................................................................................................... 7
Branching (Short circuiting, Loops) ....................................................................................................................... 9
Branching (break, continue, nested for) ................................................................................................................ 14
How to get started ................................................................................................................................................. 15
More string operations, References ...................................................................................................................... 17
Memory Models in Java, Methods........................................................................................................................ 19
Scope of variables, Call tracing ............................................................................................................................ 23
Recursion .............................................................................................................................................................. 25
1D array ................................................................................................................................................................ 27
2D arrays in Java, Arrays class ............................................................................................................................. 30
ArrayList and Applications ................................................................................................................................... 33
Class and Object ................................................................................................................................................... 36
Composition and Inheritance ................................................................................................................................ 41
Constructors in Inheritance, Abstract Class, Interface.......................................................................................... 47
Polymorphism ....................................................................................................................................................... 52
Exceptions in Java................................................................................................................................................. 59
Input and Output in Java ....................................................................................................................................... 65
Java Generics ........................................................................................................................................................ 69
Additional Topic: Binary search ........................................................................................................................... 71
1
CSE 11 - Intro to Java, Expedited – Notes Packet
Syllabus, Introduction
1. Syllabus information (find it on canvas)
- Learning goals
• Understand the basic idea of variables, flow controls, and memory models.
• Be able to debug, test, and document a functional Java program.
• Manipulate strings and files in Java
• Describe and use some of Java's Abstract Data Types (ADTs) and Application Program Interfaces
(APIs).
• Implement algorithms to solve relatively complex problems.
• Design, write and debug relatively complex classes.
• Understand and use inheritance and polymorphism in your programs.
• Implement recursive solutions to problems.
• Design and use test cases to ensure the correctness of your programs.
• Practice good documentation habits.
• Be able to compile and run Java codes in the command line.
• Gain independence and resourcefulness to solve problems and write programs on your own.
- Textbook
Introduction to Java Programming: Comprehensive Version, 11th Edition, by Y. Daniel Liang.
- Components
Class participation: 10% (iclicker, drop 3 weeks, no participation in wk 1)
PA: 45% (allows resubmission and get up to 50% of autograded portion back)
Midterm: 20% (a portion of final can sub midterm, no drop, through prairie learn)
Final exam: 25% (no makeup, no drop, through prairie learn)
- Academic integrity
- OSD students
2
CSE 11 - Intro to Java, Expedited – Notes Packet
2. Introduction
Computer Science, especially intro CS, is about problem solving and learning a new language
- programming languages and computers are tools; they are not the goal, only a means to a goal
What is a program?
- a set of instructions (algorithm) ... different forms understood by humans vs. by a computer
Edit
- we will allow students to use a text editor of their choice and compile using command line.
Compile (translate human-readable Java language program into an equivalent program in a language closer to
what the computer can understand)
javac Foo.java --> Foo.class (Java bytecode)
Run
- we will use Java applications [with a main() method]
For example,
Submit code to gradescope: upload the required .java file and check the response from the autograder
3
CSE 11 - Intro to Java, Expedited – Notes Packet
Primitive Types, Variables, Assignments, Console IO
1. Primitive Data Types
double 4.20 (8 bytes, range is around 10308)
float -1.25F (4 bytes, range is around 1038)
long 42000000000L (8 bytes, range is around 1018)
int -101404505 (4 bytes, range is around 109)
short 3733(2 bytes, range is around 104)
byte 32 (1 byte, range is around 100)
char 'G'(2 bytes, utf-16)
A. int
• For human ages B. short
• For weight of a person C. char
• For college admission result at UCSD D. double
E. More than one is ok
● 0
● 0L
● 0.0
● ‘0’
● “0”
● 0.0f
- automatic conversion (promotion) of primitive data types; other way requires a type cast
4
CSE 11 - Intro to Java, Expedited – Notes Packet
2. Variables
• A location in memory that stores data
o It has an associated name
o In Java (and some other languages), it has a type and will never change
o It also has a value at any given time.
• Variables are first declared (specifies the name and type)
• Variables are then initialized (assigns the value)
• We can declare and initialize a variable simultaneously
3. Assignment operation
lvalue = rvalue;
5
CSE 11 - Intro to Java, Expedited – Notes Packet
4. Console IO
Output
● In Java (and most languages), code runs silently
● When we want to actually display something to the user, we can print it
● We typically use one of two Java functions:
● System.out.print(myVar) prints the value of myVar to the user’s console. However, it won’t end
the line, so any other print statements will occur on the same line
● System.out.println(myVar) prints the value of myVar and goes to the next line
Input
● We use Scanner in this class to read in data
(https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)
● nextInt, nextDouble, next → read in data
● hasNext, hasNextInt, hasNextDouble → check if there is still data to be read
● delimiter → read in data based on a formatting, e.g. csv file
import java.util.*;
public class Input{
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
int value;
value = keyboard.nextInt();
System.out.println("You entered " + value);
}
}
6
CSE 11 - Intro to Java, Expedited – Notes Packet
Branching (conditionals)
1. Conditional statements in Java: if, if-else, and switch
Sequence Selection
if (condition) {
if/true part
}
if (condition) {
if/true part
} else {
else/false part
}
< >=
> <=
== !=
x = 2, y = 4, z = 15
z – 3 * x != y + 5
A. True
B. False
7
CSE 11 - Intro to Java, Expedited – Notes Packet
Cascading if-else-if-else
[Which one of these … might not execute any path? … exactly one path must be taken?]
if (condition1) { if (condition1) {
stmts1; stmts1;
} else if (condition2) { } else if (condition2) {
stmts2; stmts2;
} else if (condition3) { } else if (condition3) {
stmts3; stmts3;
} else { } else if (condition4) {
stmts4; stmts4;
} }
//block 1 //block 2
if (condition A){ if (condition A){ What is true about block 1 and block 2?
//statements A //statements A
}
A. they are basically the same code, no
}
else if (condition B){ if (condition B){ difference
//statements B //statements B B. for block 1, it is impossible that
} } statements A and D are both executed
else if (condition C){ if (condition C){ C. for block 2, it is impossible that
//statements C //statements C
} statements A and D are both executed
}
else{ else{ D. More than one of the answers are
//statements D //statements D correct
} } E. None of the answers is correct
2. switch statement
switch(fastFurious) {
case 1: System.out.println(“The Fast and the Furious”);
break;
case 2: System.out.println(“2 Fast 2 Furious”);
break;
case 3: System.out.println(“The Fast and the Furious: Tokyo Drift”);
break;
default: System.out.println(“Invalid Fast and Furious movie”);
}
8
CSE 11 - Intro to Java, Expedited – Notes Packet
Branching (Short circuiting, Loops)
1. Short circuiting
Logical Operators
if ( value >= 0 && value <= 100 ) // Check if value is in the range 0 – 100
Nested if statements
- always use { } to associate an else with the appropriate if
- indentation means nothing to the compiler
9
CSE 11 - Intro to Java, Expedited – Notes Packet
2. for loops, while loops, and do while loops
initialization exp;
while ( loop condition ) {
statement(s);
loop exp;
}
10
CSE 11 - Intro to Java, Expedited – Notes Packet
General structure of do while loop:
do
statement;
while (loop condition);
do {
statement;
statement;
} while( loop condition );
For Loops
/* Output:
* Program to display the square of integers from 1 to 10. 1 squared = 1
*/ 2 squared = 4
3 squared = 9
public class Squares { 4 squared = 16
public static void main( String[] args ) { 5 squared = 25
//complete me 6 squared = 36
7 squared = 49
8 squared = 64
9 squared = 81
10 squared = 100
}
}
11
CSE 11 - Intro to Java, Expedited – Notes Packet
------------
Do While Loops
/*
* Program to display the square of integers from 1 to 10.
*/
int i;
i = 1;
do {
System.out.println( i + " squared = " + ( i * i ) );
++i;
} while ( i <= 10 );
}
}
Remember that do while loop bodies are always executed at least once
12
CSE 11 - Intro to Java, Expedited – Notes Packet
int n = 4; A. 4
int x = 0;
while(n > 0) {
B. 6
for(int i = 0; i < n; ++i) { C. 7
++x; D. 8
} E. This will cause a compile error
n /= 2;
}
//value of x?
13
CSE 11 - Intro to Java, Expedited – Notes Packet
Branching (break, continue)
1. break and continue
break and continue statements allow us to alter the normal flow of a loop
• break: when executed, the inner-most loop that contains the break statement will be exited immediately.
• continue: when executed, the remainder of the current iteration will be skipped.
for (int i = 0; i < 10; i++){ How many times is continue statement
if (i++%3==0) { executed?
continue;
}
A. 0
if (--i%2==0){ B. 1
break; C. 2
} D. 5
System.out.println(i); E. 10
}
14
CSE 11 - Intro to Java, Expedited – Notes Packet
How to get started
1. How to start a programming project
Given a string, return the string made of its first two chars, so the String "Hello"
yields "He". If the string is shorter than length 2, return whatever there is, so "X"
yields "X", and the empty string "" yields the empty string "". Note that str.length()
returns the length of a string.
15
CSE 11 - Intro to Java, Expedited – Notes Packet
Exercise 2
Given a string, compute a new string by moving the first char to come after the next two
chars, so "abc" yields "bca". Repeat this process for each subsequent group of 3 chars,
so "abcdef" yields "bcaefd". Ignore any group of fewer than 3 chars at the end.
2. Operator Precedence
B. b = 6 % modulus (remainder)
+ addition or string concatenation left-to-right
C. b = 9 - subtraction
D. b = 12 <<
>>
left shift
arithmetic/signed right shift (sign bit duplicated)
left-to-right
16
CSE 11 - Intro to Java, Expedited – Notes Packet
More string operations, References
1. More string operation patterns
- Go through the string and find individual characters
e.g. count the number of letter ‘c’ in the string
17
CSE 11 - Intro to Java, Expedited – Notes Packet
2. References and Primitives
So far, we’ve learned about a bunch of “primitive data types”
- byte, char, short, int, long, float, double, boolean
We also learned about a “non-primitive” type: String
Primitive vs Reference
- Similarity: both hold values in a box
- Difference: The meaning of the value is different. For primitive, it is the value itself. For reference, it is the
address (aka arrow) of the object.
null reference: If a reference variable's value is null, it isn't pointing to any object
Memory regions
In Java, there are two “areas” of memory: the stack and the heap
STACK HEAP
When we create variables in main or other methods, these variables are on the stack.
When we create objects using new, the object is on the heap. Its reference is on the stack
Note: stack/heap is memory region, primitive and reference are variable types. They don’t dictate each other
int mph = 42; Where is the variable message stored?
String message = “I am ”;
if(mph > 100) {
A. stack
message += “fast”; B. heap
} else {
message += “slow”; Where is the object message points to?
}
A. stack
B. heap
19
CSE 11 - Intro to Java, Expedited – Notes Packet
2. Methods/Functions/Procedures in Java
20
CSE 11 - Intro to Java, Expedited – Notes Packet
Stack Frames
• a structure created (pushed on the runtime stack) with each method call
• local variables and formal parameters stored here (along with other info specific to the method call/return
implementation)
• destroyed (popped off the runtime stack) with each method return
21
CSE 11 - Intro to Java, Expedited – Notes Packet
Method (and Constructor) Overloading
• if two methods (or constructors) of a class have the same name but otherwise different signatures, then the
method (or constructor) name is said to be overloaded
• when calling an overloaded method (or constructor), the compiler selects the proper method (or
constructor) by examining the number, types, and order of the arguments in the call and matching them
with the formal parameters of the eligible methods (or constructors) with possible argument coercion
Note: return types and throws clause are not involved (not part of the signature)
Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of
chars to the left and right of the "xyz" must differ by at most one.
xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBB") → true
xyzMiddle("AxyzBBB") → false
22
CSE 11 - Intro to Java, Expedited – Notes Packet
Scope of variables, Call tracing
public class Order {
}
1. Scope of variables
- Scope of a variable: the region in your code that you can use this variable. Defined by the block it is declared
in.
- Objects exist in the heap.
- Method calls goes from one stack frame to another
- Variables may have the same name but exist in different stack frames
- Instance variables and local variables may share the same name
23
CSE 11 - Intro to Java, Expedited – Notes Packet
2. Function call tracing
When a function is called, a stack frame is created for it and all local variables stay in it. When a function call is
done, this stack frame is destroyed and the execution returns to the caller of this function.
public class Trace {
public static void main( String[] args ){
for(int i=0; i<=2; i++){
if(i%2 == 0)
foo1();
else
foo2();
}
}
public static void foo1(){
System.out.print( "A" );
foo2();
System.out.print( "B" );
foo3();
System.out.println();//just print a new line
}
public static void foo2() {
System.out.print( "C" );
foo3();
System.out.print( "D" );
System.out.println();
}
public static void foo3() {
System.out.print( "E" );
System.out.println();
}
}
24
CSE 11 - Intro to Java, Expedited – Notes Packet
Recursion
Recursion
Key idea: Design a program to solve a complex problem by breaking it into simpler problems, solve the simpler
problems, and then assemble the final answer from these simpler pieces. If the simpler versions are of the same
problem/kind the technique is called recursion.
1) Base Case(es) – Solve a problem directly. (Think: how do I stop the recursion?)
2) Recursive Case(es) – Break a complex problem into a (slightly) simpler problem of the same kind.
Leap of faith – assume that simpler recursive calls work correctly.
Recursive Methods
- method that has at least one recursive call to itself
- need at least one base case to stop the recursion
F(n) = { 1
n * F(n – 1)
if n = 0 or n = 1
if n > 1
public static long factorial(int num) {
long result;
if ( num <= 1 ) {
result = 1;
} else {
result = num * factorial(num – 1);
}
return result;
}
25
CSE 11 - Intro to Java, Expedited – Notes Packet
Exercise 1: Write a code that will generate the 200th Fibonacci number. Fibonacci sequence is as follows:
Exercise 2: Given a number n, you should print the length of the 3n+1 sequence starting with n. The sequence is
constructed as follows:
• If the number n is odd, the next number will be 3n+1.
• If the number n is even, the next number will be n/2.
For example, the 3n+1 sequence of 3 is {3,10,5,16,8,4,2,1} and its length is 8.
Please use both the iterative approach and the recursive approach to solving this problem.
26
CSE 11 - Intro to Java, Expedited – Notes Packet
1D array
Java arrays are objects
• dynamically created
• may be assigned to variables of type Object
Arrays are "static" entities in that they remain the same size once they are created
• although an array reference may be reassigned to reference a different array object of the same type but of
a different size
Vectors and ArrayLists are "dynamic" array-like objects which can grow and shrink depending on the program's
changing storage requirements (similar to StringBuilder is to String)
Forward iteration
for( int i = 0; i < array.length; ++i ) {
...
}
Backward iteration
Neighbor check
1. If an array is non-decreasing
27
CSE 11 - Intro to Java, Expedited – Notes Packet
Declaring and Allocating Arrays
or
0 1 2 3 4 5 6 7 8 9
int[] array = new int[ARRAYSIZE]; array
or
length
int array[] = new int[ARRAYSIZE];
int[] a;
a = new int[10];
...
a = new int[20];
int[] a = { 1, 2, 3, 4, 5 };
or
int[] a = new int[] { 1, 2, 3, 4, 5 };
28
CSE 11 - Intro to Java, Expedited – Notes Packet
public static void doSth(int[] inputArray, int[] result ) {
result = new int[inputArray.length];
for ( int i = 0; i < inputArray.length; i++ ) {
result[i] = inputArray[i];
}
return;
}
public static void main( String[] args ) {
int[] a = {1, 2, 3};
int[] b = null;
doSth(a,b);
a[0] = 42;
System.out.println( b[0] );
}
What does the last line of main print? A. 0 B. 1 C .42 D. Other
Array Access
IndexOutOfBoundsException example
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at IOOBEx.main(IOOBEx.java:6)
29
CSE 11 - Intro to Java, Expedited – Notes Packet
2D arrays in Java, Arrays class
Multi dimensional Arrays
In the Java programming language, a multidimensional array is an array whose components are themselves
arrays. This is unlike arrays in C or C++. A consequence of this is that the rows are allowed to vary in length.
30
CSE 11 - Intro to Java, Expedited – Notes Packet
System.out.println("Second round");
print(data, 0, 1);
print(data, 1, 1);
print(data, 2, 0);
print(data, 3, 0);
print(data, 3, 1);
}}
Arrays
class in Java
31
CSE 11 - Intro to Java, Expedited – Notes Packet
Arrays.sort(orig);
Arrays.sort(classes);
System.out.println(Arrays.toString(orig));
System.out.println(Arrays.toString(classes));
}
}
32
CSE 11 - Intro to Java, Expedited – Notes Packet
ArrayList and Applications
Suppose you need to store elements in an array but don’t know how many to store (reading from
input). What should you do?
Class ArrayList provides the capabilities of array-like data structures that can dynamically resize themselves
• a ArrayList's capacity is the space that has been reserved for the array
- number of elements in a ArrayList (size) can be less than or equal to its capacity
• if a ArrayList needs to grow, it grows by an increment you specify or by the default of doubling the current
size
ArrayLists are designed to store references to Objects
• a reference to an object of any class type can be stored in a ArrayList
• to store values of primitive data types, must use type wrapper classes or autoboxing (Java 1.5)
An ArrayList can store any type of object, but you have to specify Type so the compiler can help you:
Example:
ArrayList<String> list = new ArrayList<String>();
ArrayList<int> intList=new ArrayList<int>(); (error)
E get(int index)
Returns the element at the specified position in this list
int size()
Returns the number of elements in this list
E remove(int index)
Removes the element at the specified position in this list
boolean addAll(Collection<? extends E> c)
import java.util.*;
33
CSE 11 - Intro to Java, Expedited – Notes Packet
public class ArrayListTest{
public static void main( String[] args ){
// Create a new ArrayList with capacity 5
ArrayList <Integer> list = new ArrayList <>( 5 ); // or simply ignore capacity
import java.util.ArrayList;
public class ArrayListTest{
public static void removeOne(ArrayList<Integer> list, Integer key){
for (int i=0;i<list.size();i++){//or use indexOf
if(list.get(i).equals(key)){
list.remove(i);
return;}}}
public static void main(String[] args) {
ArrayList<Integer> alist=new ArrayList<Integer>();
alist.add(new Integer(20));
//you can get by using alist.add(20)
alist.add(new Integer(15));
What is the output?
alist.add(new Integer(8)); A. 20
removeOne(alist, 15); B. 8
System.out.println(alist.get(1)); C. run time error
}} D. 0
Exercises 1
Complete the function findLongest that takes in a String ArrayList and returns the longest String in the
list. If the ArrayList is null or the size of the list is 0, return null. It is possible that a reference in the
ArrayList may be null. If every element in the ArrayList is null, then return null. If there are multiple
Strings of the same longest length, you can return any of them.
For example, {"a", "ab", "cde", "c", null} will return cde
34
CSE 11 - Intro to Java, Expedited – Notes Packet
Exercise 2
Complete the function merge that takes in an ArrayList of ArrayLists of Integers. This function is
supposed to return a single ArrayList of Integers that is a merge of all the integers in the original collections
of ArrayList. For example, if we have the list as {{1,2,3,4,5}, {3, null, 3, 4, 5}, {null, 3, 4}}, it
will return an ArrayList of { 1, 2, 3, 4, 5, 3, null, 3, 4, 5, null, 3, 4}. You can assume that the
ArrayList of ArrayLists doesn't have a null ArrayList.
35
CSE 11 - Intro to Java, Expedited – Notes Packet
Class and Object
1. Classes and Objects
Object-Oriented Programming (OOP)
encapsulates into objects:
• data/state (attributes)
• methods (behavior/operations)
Instance Variables
• instance variables are variables defined outside a method/constructor body but within the class definition
- instance variables live in each object - usually want to make instance variable private
• duration/lifetime
- created when an instance of the class (object) is created Foo foo = new Foo();
- destroyed when the object is no longer referenced foo = null;
(actually when the garbage collector runs) OR foo = new Foo();
• scope
- class definition scope — entire class definition (all code defined in the class definition)
- instance variables are directly accessible by all methods in the defining class type on a per object basis
ref.instanceVariableName
default: instanceVar --> this.instanceVar
• instance variables of a class are automatically initialized if not explicitly initialized by the programmer
- default zero-like initialized values
Class Variables
• class variables are variables defined using the keyword static within a class definition
- static/class-wide variables live in the type descriptor in the Class Area
- only one static/class-wide variable shared among all the objects of that type
• duration/lifetime
- created when its class is loaded
36
CSE 11 - Intro to Java, Expedited – Notes Packet
- exists even when no object of that class exists
- only one incarnation of the static variable exists for all objects of that class
- ceases to exist when its class is unloaded
• scope
- class definition scope — entire class definition
- public static class variables can be accessed by any object using the dot operator
I want to design a Student class where I need to have the following variables
• local variables must be initialized/assigned before they can be used (no default values)
37
CSE 11 - Intro to Java, Expedited – Notes Packet
public class Definition {
38
CSE 11 - Intro to Java, Expedited – Notes Packet
Object-Oriented Design
- designing software with objects that often mimics the real world
- list its properties – these will be instance variable, constants, static variables
- private by default! Use non-private accessor/mutator methods if needed.
- list its behaviors – these will be constructors and methods; focus on the ctor/method headers:
- what needs to be initialized in the ctor when an object is being created
- what type of information needs to be passed as actual arguments to the formal parameters?
- what will be the result of each method invocation (message sent to this object)?
39
CSE 11 - Intro to Java, Expedited – Notes Packet
}
public Nim(int[] b, int t){//copy b to board and t to turn
}
}
40
CSE 11 - Intro to Java, Expedited – Notes Packet
Composition and Inheritance
Object-Oriented Programming (OOP) main tenets
Encapsulation / Information Hiding – both data and methods
Inheritance – inheritance of Interface (implements) and inheritance of Implementation (extends)
Polymorphism – allows values of different data types to be handled using a uniform interface
1. Composition of classes
Composition in object oriented programming (OOP) is the idea of having one class to be a data member or
instance variable of another class. It shows the has-a
relationship. public class Address {
//Our own class
public class Student { private String street;
private int id; private String city;
private String name; private String state;
private Address addr; private String postalCode;
} }
When we write the Address class, do we have to know how Student class will use it? A. Yes B. No
Write the constructors and getters/setters. Include no-arg ctor, basic ctor,
and copy ctor.
public class Student {
private int id;
private String name;
private Address addr;
42
CSE 11 - Intro to Java, Expedited – Notes Packet
2. Inheritance
- polymorphism
- enables us to write programs in a general fashion to handle a wide variety of existing and yet-to-be-
specified related classes using a superclass or interface reference
- dynamically (at runtime) select the appropriate behavior based on the type of the object referenced
- makes it easy to add new capabilities
Java does not support multiple inheritance of implementation (only single inheritance of implementation)
single inheritance
single inheritance
Every object of a subclass type is also an object of that subclass’s superclass type (interface types also)
- “subclass-object-is-a-superclass-object” relationship
- contrast with composition — has-a relationship
- converse is not true — superclass objects are not objects of that superclass’s subclasses
- superclass members become members of the subclass
43
CSE 11 – Intro to Programming, Expedited
Employee
1. Technician is a base/superclass of
Employee
HourlyEmployee SalariedEmployee 2. TechnicalStaff is a base/superclass
of Technician
FullTimeHourlyEmp PartTimeHou
3. TechnicalStaff is a derived/subclass
TechnicalStaff Executive
loyee rlyEmployee of Employee
4. TechnicalStaff is a derived/subclass
of SalariedEmployee
Engineer Technician ClericalStaff
Student
GraduateStudent UndergraduateStudent
45
CSE 11 – Intro to Programming, Expedited
this and super keywords
this – use in a class to indicate that calling object reference
super – use in a class to indicate that we call the super object’s method.
public
- accessible by any Java code
- public methods define the public interface of the class
private
- access is permitted only when it occurs from within the class in which the member is declared
- instance variables are typically private
- private methods are often called utility methods or helper methods
protected
- access is permitted
1) from within the same package or
2) from within a subclass of the class in which it is declared
Package P
46
CSE 11 – Intro to Programming, Expedited
Constructors in Inheritance, Abstract Class, Interface
1. Constructors
Constructors are methods that are called atomically to initialize instance variables for objects.
• Special method-like declaration
- Same name as class
- No return type
• Trigger: new operator, string concatenation operator +, …
• Explicit constructor invocation from another constructor
- this() – same class constructor invocation
- super() – immediate superclass constructor invocation
• They may be overloaded (same name, different signature)
- public Foo() { … }
- public Foo( String name ) { … }
• They are never inherited and not subject to hiding or overriding
• Access modifiers: public, protected, private, none (Cannot use method modifiers abstract, static, final,
synchronized, native)
47
CSE 11 – Intro to Programming, Expedited
Implicit
1. Subclass-Object-to-Superclass-Object
SuperClass s1 = new SuperClass();Conversion
2. SuperClass s2 = new SuperClass(9);
2. Abstract Class
Concrete Classes
- classes from which objects can be instantiated (no abstract methods)
- implement the specifics that make it reasonable to instantiate objects
- provides a pure inheritance of implementation (extends keyword)
Abstract Classes
- classes declared with keyword abstract
- classes must be defined abstract if at least one method in the class definition is defined abstract
- classes which are not intended to be instantiated as objects
- too generic to define real objects
- cannot create objects of abstract classes
- used as superclasses for inheritance and polymorphism purposes (abstract superclasses)
- provides an appropriate mixture of inheritance of interface and/or implementation (extends keyword)
- inheritance of interface — inherit abstract method declarations/signatures
- inheritance of implementation — inherit concrete method definitions and instance variables
- abstract classes often constitute the top level(s) of a hierarchy. Why not just use a concrete class?
48
CSE 11 – Intro to Programming, Expedited
3. Interface
Java allows a variable of an interface type to refer to several different types of objects that implement the
interface (one form of polymorphism; inheritance of interface)
Java interface provides a description of the public methods that objects of that type need to provide
- describes the type's public interface (what)
- specifies a contract that any class that implements the interface must satisfy (how)
Interfaces contain no method definitions, no constructors, and no instance variables (no state) [pre-Java SE 8]
- may contain public static final constants
- these constants become part of any class that implements the interface
Extending Interfaces
public interface SubInterface extends SuperInterface1, SuperInterface2
//default method.
default int getRadarRear(double distanceToCar, double speedOfCar){
return distanceToCar / speedOfCar;
}
......
// more method signatures or default methods
}
An interface provides only the method headers (not the bodies) – name, parameters, return type – followed by ;
- classes that implement an interface are required to provide the method bodies for all these headers
Associate an interface with a class with the implements clause in the class header.
Exercise: Design a system such that all the ATMs from these banks will work with some sort uniform
functionality.
50
CSE 11 – Intro to Programming, Expedited
Concrete Classes Abstract Classes Interfaces
Can extend from only 1 base class Can extend from only 1 base class Can implement many interfaces
-single inheritance of -single inheritance of implementation -multiple inheritance of interface
implementation
Can create instances of objects of Cannot create instances of objects of No notion of creating instances of
concrete classes; fully defined abstract classes; incomplete interfaces
No abstract method declarations; Mixture of fully implemented Only abstract method declarations
only fully implemented (concrete) methods and abstract methods and final static constants
methods
1. Suppose A is an interface.
Can you create an instance using new A(); A. Yes B. No
Can you declare a reference var x as: A x; A. Yes B. No
51
CSE 11 – Intro to Programming, Expedited
Polymorphism
1. Relationship between Superclass Objects and Subclass Objects
It is possible to treat superclass objects and subclass objects similarly
- objects of all classes derived from a common superclass can all be treated as objects of that superclass
- this is the basis for polymorphism
- e.g., can create an array of superclass objects (superclass references) that refer generically to any
subclass object
- reverse is not true
- subclass objects can be treated as superclass types (via superclass reference) for many operations
- subclass has inherited members corresponding to each of the non-private superclass members
- implicit conversion because a subclass object is a superclass type through inheritance
superclassRef = subclassRef;
- however, cannot reference subclass-only members with this superclass reference (without a cast)
superclassRef.toString() // OK — toString() in all types inherited from Object
52
CSE 11 – Intro to Programming, Expedited
- methods in subclasses need to be at least declared in superclass type, and then defined or overridden in
subclasses
- this is the key to providing polymorphic behavior (polymorphism and late/dynamic binding)
2. Introduction to Polymorphism
- programs can be written to generically process objects of all existing subclasses in a hierarchy
- using superclass references
- classes that do not yet exist but will be part of the hierarchy can be added with little or no modification to
the generic parts of the program
- objects throughout these hierarchies are manipulated polymorphically
- can eliminate the need for switch/if-else logic
- dynamic binding
Dynamic Binding
- set of shape classes: Circle, Triangle, Rectangle, Square, etc. derived from superclass Shape
Shape shape;
shape.draw();
- need to have a draw() method (abstract method declaration) in superclass (class Shape) or an
interface, and then implement draw() in each subclass to draw the appropriate shape [Key Point]
shape.draw()
- system dynamically (at run time) chooses the correct subclass’s draw() method
- dynamic binding/polymorphism
53
CSE 11 – Intro to Programming, Expedited
final Methods and Classes
54
CSE 11 – Intro to Programming, Expedited
interface Crawable{ class Python extends Snake{
public abstract void crawl(); public void method1() {
} System.out.println("Python 1");
}
abstract class Snake implements Crawable{ public void method3() {
public void method2() { System.out.println("Python 3");
System.out.println("Snake 2"); }
} }
public void method3() {
System.out.println("Snake 3"); class Cobra extends Snake{
} public void method2() {
public void crawl(){ System.out.println("Cobra 2");
System.out.println("Slither"); }
} public void method3() {
} System.out.println("Cobra 3");
}
public void crawl(){
System.out.println(“Spit too”);
}
Prob 1.
Snake var1 = new Python(); Prob 2.
Crawable Snake var2 = new Python();
var1.method1()
var2.method2()
Prob 3. Prob 4.
Crawable var3 = new Cobra(); Crawable var4 = new Cobra();
var3.crawl() var4.method2()
Prob 5. Prob 6.
Snake var5 = new Cobra(); Crawlable var6 = new Python();
((Python)var5).method1(); ((Cobra)var6).method3();
55
CSE 11 – Intro to Programming, Expedited
s.equals(s); A. 1
h.equals(t); B. 3
s.equals(t);
C. 4
t.equals(s);
D. 0
t.equals(null);
E. 6
h.equals(n);
s.equals(s);
A. 1
h.equals(t);
B. 3
s.equals(t);
C. 4
t.equals(s);
D. 0
t.equals(null);
E. 6
h.equals(n);
56
CSE 11 – Intro to Programming, Expedited
Fill in the blanks on what will be printed from that line.
Polymorphism rules
ref.method1( args );
Casting
Casting changes the compiler's view of the type of the reference, not the actual object
• Assigning a Sub class type to a Super class type
Super superRef = new Sub(); // Implicit (widening) upcast
• Assigning a Super class type to a Sub class type
57
CSE 11 – Intro to Programming, Expedited
Sub subRef = (Sub)superRef; // Explicit (narrowing) downcast
• Accessing a Sub class-specific member from a Super class reference
((Sub)superRef).subClassSpecificMember(); // Check op prec table
For explicit casts
Compile time check
Compiler requires explicit cast for any narrowing (downcast)
(Remember explicit narrowing casts for primitive data types?)
Equals method
In class Object
public boolean equals( Object o ) {//why Object o?
return this == o;
}
When we want to check for equality of our types
@Override
public boolean equals( Object o ) {//why Object o?
//check null, getClass(), and typecast
// Compare the internal state of this object to that of
// the object referenced by o. Deep vs. shallow check.
// Return true/false accordingly.
}
Exercise
Dragon is a subclass of Snake and it has an instance variable called numLegs (int), and also an instance variable
name (String). Please write the equals method for Dragon. You can assume that Snake has overridden its equals
method correctly.
58
CSE 11 – Intro to Programming, Expedited
Exceptions in Java
What happens if we accidently divide-by-zero (both with floating point and integer division)?
What happens if we expect an integer and enter a non-numeric string as input using Scanner's nextInt?
And if we were using Integer.parseInt() to convert a String into an int, we would get a
NumberFormatException
Put specific exception types first, then more general exception types when using multiple catch blocks.
Uncaught exceptions in a method propagate back to the method that invoked it.
59
CSE 11 – Intro to Programming, Expedited
public String readIt( String filename ) public String readIt( String filename )
throws IOException {
{ File sourceFile = new File( filename );
File sourceFile = new File( filename ); Scanner input = null;
Scanner input = new Scanner( sourceFile ); try {
String allText = ""; input = new Scanner( sourceFile );
while ( input.hasNextLine() ) }
VS
{ catch ( IOException e ) {
String s1 = input.nextLine(); System.out.println( e.getMessage() );
allText = allText.concat( s1 + ”\n” ); return null;
} }
System.out.println( allText); String allText = "";
return allText; while ( input.hasNextLine() )
} {
String s1 = input.nextLine();
allText = allText.concat( s1 + “\n”);
}
System.out.println( allText );
return allText;
}
What happens if we remove the return from within the catch block (and call the method with a bad
filename)?
60
CSE 11 – Intro to Programming, Expedited
Complete the code to prompt the user to enter a new filename until the file exists
}
Catch Block X
In what order should catch ( IOException e ) {
// get new input
you use the blocks to //
the right? }
A. X then Y
B. Y then X Catch Block Y
C. Either are fine catch ( Exception e ) {
D. Neither will work System.out.println( e.getMessage() );
System.exit(0);
}
61
CSE 11 – Intro to Programming, Expedited
Write a code that allows to check if two passed-in files can be opened for processing. Make sure you quit
your program gracefully.
public static void checkFile(String s1, String s2 ){
We can create our own Customized Exception class to support our own
import java.io.*;
public class ForbiddenOperationException extends Exception{
private String name;
//Ctor
public ForbiddenOperationException(String msg, String name){
super(msg);
this.name = name;
}
//getter
public String getName(){
return name;
}
}
62
CSE 11 – Intro to Programming, Expedited
public class ExceptionDemo{
public static boolean grade (String student) throws ForbiddenOperationException {
boolean found = false;
//Do code checking. Suppose that we have an issue and change found = true;
if (found == true){
throw new ForbiddenOperationException("Copied PA4 code", student);
}
Exception Exercises
public static void main(String[] args) throws Exception{
try{
1. What will happen if
int x=5; throws Exception
doSth(); is removed from the main header?
System.out.println(“Inside try"); A. Run time error
} B. Compiler error
catch(IOException ex1){ C. Nothing will happen
throw ex1;
}
catch(ArithmeticException ex2){ 2. If doSth doesn’t throw any exception,
throw ex2; what will be printed?
} A. Inside finally
finally{ All done
System.out.println("Inside finally"); B. All done
} C. Inside try
System.out.println("All done"); Inside finally
} All done
//doSth method here D. Inside try
E. None of the above. It’s something else
63
CSE 11 – Intro to Programming, Expedited
Exception Exercises
public static void main(String[] args) throws Exception{
try{
int x=5;
doSth();
System.out.println(“Inside try");
}
3. If doSth throws an IOException,
catch(IOException ex1){
what will be printed?
throw ex1;
A. Inside finally
All done
}
B. All done
catch(ArithmeticException ex2){
C. Inside try
throw ex2;
Inside finally
}
All done
finally{
D. Inside finally
System.out.println("Inside finally");
(then crash)
}
E. None of the above. It’s
System.out.println("All done");
something else
}
//doSth method here
64
CSE 11 – Intro to Programming, Expedited
Input and Output in Java
1. Input and Output Intro.
The two important components of a computer are:
● Central Processing Unit (CPU)
● Main Memory (RAM)
Secondary storage: Hard disk drive or SSD
Peripheral: I/O Devices
In order for a program to process a file, it must interact with the Operating System to get access to the file, to
then load it into memory, and to read from the file. This is done via libraries in the programming language (in
our case, Java)
- Scanner/PrintWriter: formatted IO
(our focus)
- BufferedReader/BufferedWriter:
buffered IO, byte by byte as there is no
format. It is primarily used to read data
from a server on the network etc.
65
CSE 11 – Intro to Programming, Expedited
import java.io.File;
import java.util.Scanner;
import java.io.IOException;
//Inside a Test class
public static String readIt( String filename ) throws IOException {
File sourceFile = new File( filename );
Scanner input = new Scanner( sourceFile );
String allText = "";
while ( input.hasNext()) {
String s1 = input.nextLine(); Haku.txt
allText = allText.concat( s1 );
} Rather than a beep
System.out.println( allText ); Rather than a beep
return allText;
Or a rude error message:
Or a rude error message:
These words: "File Not Found".
These words: "File Not Found".
}
public static void main(String[] args) throws IOException{
String result = readIt(“Haku.txt”)
System.out.println(result);
} What does this print?
A. The original file text, formatted exactly the same
B. The original file text, but slightly changed
C. Something else
Example: Read in a file with students’ name and their 3 PA scores, calculate each person’s average PA score
and print on the screen. The function, dispAve, takes a file name and prints out the averages. It doesn’t return
anything.
Discussion:
1. What is the basic unit of data when we try to process this file?
66
CSE 11 – Intro to Programming, Expedited
Complete the dispAve function
3. Formatted Output
The approach to write to a file is almost identical to print to the console using System.out.print.
- Create a File object and link to PrintWriter
(https://docs.oracle.com/javase/10/docs/api/java/io/PrintWriter.html)
- Write to the file
Example: Ask user to enter 2 numbers and write the max into a file. Assume it is in main
67
CSE 11 – Intro to Programming, Expedited
4. Command line arguments
In java, the command line arguments indicate the information you receive when you type in java ClassName to
run the code
Example
java Tester Bye 2 Hello
----------------They are command line arguments. First is “Bye”, second is “2”, last is “Hello”
Usually command line arguments are used to pass in information to main method.
public class Example{
public static void main(String[] args){
// args is the array to store each of the arguments in String format
What will happen when the following code runs when we run java Tester 4 ‘*’? This function takes a
width and a brush char from command line. It prints a row of brush characters whose width equals to the
width.
A. ****
public class Tester{ B. 4444
public static void main(String[] args){ C. Compiler error
int width = args[0];
char brush = args[1]; D. Runtime error
for (int i = 0; i < width; i++){
System.out.print(brush);
}
}
}
Note: Linux shells interpret special characters differently, so if you have to enter characters such as *% etc as
command line arguments, you should put them into single or double quotes.
68
CSE 11 – Intro to Programming, Expedited
Java Generics
The purpose of generics in Java is to separate data types from algorithms that apply on data types.
Generics is in general associated with data structures (CSE 12) and algorithms.
Motivation
public Integer max(Integer[] data){
Integer maxV = data[0];
for (int i = 0; i < data.length; i++){
if (maxV.compareTo(data[i])<0){
maxV = data[i];
}
}
return maxV;
}
public String max(String[] data){
String maxV = data[0];
for (int i = 0; i < data.length; i++){
if (maxV.compareTo(data[i])<0){
maxV = data[i];
}
}
return maxV;
}
The two methods are extremely similar but we have to overload them because they deal with different types of
arrays.
One proposal can be that we just write a method that takes an Object array. What is the potential
problem with this solution?
69
CSE 11 – Intro to Programming, Expedited
Note: To ensure that certain methods can be called, we can constrain the generic type to be subclass of an
interface or class
Generic Class
Create a class which has multiple generic methods (like our ArrayList, Set, HashMap classes)
70
CSE 11 – Intro to Programming, Expedited
Additional Topic: Binary search
Binary search
Motivation: Look up phone contact on your phone
public static int binarySearch( int[] theList, int toFind, int low, int high)
The method will return the position of the item if it is found. low will start at 0, high will start at
theList.length-1
Algorithm “pseudo-code”:
1. calculate the midpoint, mid, between low and high
2. If theList[mid] == toFind, return mid
3. if toFind is larger than theList[mid], recurse on the larger half of the list
4. else if toFind is smaller than theList[mid], recurse on the smaller half of the
list
Trace the values of high, low and mid when you call binarySearch with this list above and
searching for the value 8. Draw more stack frames if you need them.
binarySearch( a, 4, 0, 8 )
2 4 6 8 10 12 14 16 18
0 1 2 3 4 5 6 7 8
binarySearch( a, 5, 0, 8 )
2 4 6 8 10 12 14 16 18
0 1 2 3 4 5 6 7 8
71
CSE 11 – Intro to Programming, Expedited
public static int binarySearch( int[] list, int toFind, int low, int high )
{
return ________________________________
}
1. Is this the right way to calculate the midpoint?
A. No, it should be: (high-low)/2
B. No, it works most of the time but sometimes doesn’t
C. Yes
72