0% found this document useful (0 votes)
32 views

allNotes_blank

The CSE 11 - Intro to Java, Expedited notes packet outlines the syllabus, course components, and key Java programming concepts including variables, control structures, and object-oriented programming. It emphasizes problem-solving, debugging, and the use of Java libraries, while also detailing the academic integrity policy and support for diversity and inclusion. The document serves as a comprehensive guide for students to navigate the course and understand essential Java programming principles.

Uploaded by

dsylviaaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

allNotes_blank

The CSE 11 - Intro to Java, Expedited notes packet outlines the syllabus, course components, and key Java programming concepts including variables, control structures, and object-oriented programming. It emphasizes problem-solving, debugging, and the use of Java libraries, while also detailing the academic integrity policy and support for diversity and inclusion. The document serves as a comprehensive guide for students to navigate the course and understand essential Java programming principles.

Uploaded by

dsylviaaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

CSE 11 - Intro to Java, Expedited – Notes Packet

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.

- Instructor and staff


Paul Cao, Office CSE 2102, [email protected] , In person office hours (details on canvas)
Staff: TA office hours and tutor hours, autograder.ucsd.edu

- 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)

Must pass 50% on overall PA to pass the class.


Reading, quizzes, PA, midterm and final are all accessed through gradescope.com

- Academic integrity

All work must be done individually


Only high-level discussions are allowed
No outside help other than staff from CSE 11
Sign honor pledge through the AI form linked from canvas

- Diversity and inclusion


Everyone should feel safe and comfortable to learn in CSE 11. We support academic freedom and freedom of
speech. No discrimination or harassment on the basis of anything is tolerated.

- OSD students

- Basic needs and food insecurity


http://thehub.ucsd.edu/

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

What is a programming language? What is machine language?

Java is a fully object-oriented programming language


- you must create objects and send messages to objects
- you can think of objects as reusable software components that model items in the real world

Learning a language like Java involves learning:


- the Java language itself to design your own classes and methods
- how to use the existing classes and methods in the Java libraries/packages

Typical Java program development includes


- edit, compile, run, class loader, bytecode verifier, interpreter

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,

public class Foo {

public static void main( String[] args ) {


System.out.println(“Hello world”);
}

Compile: javac Foo.java

Run: java Foo

Submit code to gradescope: upload the required .java file and check the response from the autograder

How are you feeling about the class so far?

A. Excited B. Anxious/fearful C. Indifferent D. Curious E. Tired

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)

boolean true or false value

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

- mixed mode arithmetic and assignment

- no notion of multiple aliases for the same primitive type variable

- changes made by assignment to a primitive variable only affects that variable

Integer division trap

What will the values of x, y, z, and p? A. 3 1.5 1.5 1.5


int x = 3; B. 3 2 1.5 1.5
int y = x/2; C. 3 1 1.5 1.5
double z = x/2;
double p = x/2.0; D. 3 1 1 2
E. None of the above

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

int meaningOfLife = 42;

Java Language Keywords


Here is a list of keywords in the Java programming language. You cannot use any of the following as
identifiers in your programs. The keywords const and goto are reserved, even though they are not
currently used. true, false, and null might seem like keywords, but they are actually literals; you
cannot use them as identifiers in your programs.

abstract continue for new switch


assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while

3. Assignment operation

lvalue = rvalue;

- lvalue must be evaluated to a memory location


- rvalue can be an expression
- the value at lvalue’s location is changed to rvalue

int first = 20;


int second = first;

What’s the value of var1 after the code executes?


int var1 = 42;
int var2 = 420; A. 0
var1 = var2; B. 42
var2 = 100; C. 100
D. 420
E. This will cause a compile error

5
CSE 11 - Intro to Java, Expedited – Notes Packet

What is the output of the following code snippet?


public class FunWithChar01 { A. A, 65, 66, 66
public static void main(String[] args) { B. 65, 65, 66, 66
char ch = 'A';
System.out.print(ch + ", " + (int)ch + ", "); C. A, A, B, B
ch += 1; D. A, 65, B, 66
System.out.print(ch + ", " + (int)ch);
}
E. Compiler error
}

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

What will be printed out?


A. hello world
System.out.print(“hell”); B. hello
System.out.println(“o”); world
System.out.println(“worl”); C. hello
System.out.print(“d”); worl
d
D. none of the above

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
}

Relational Operators used in an expression evaluate to a boolean value of true or false

< >=
> <=
== !=

x = 2, y = 4, z = 15

z – 3 * x != y + 5

A. True
B. False

7
CSE 11 - Intro to Java, Expedited – Notes Packet

boolean Data Type


- can hold the value true or false

Methods can have a return type of boolean


boolean variables can be used directly without a relational operator as a conditional expression
- default relation is != false if ( var ) -> if ( var != false )

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

&& logical AND


|| logical OR (Inclusive)
! logical NOT

Short-Circuit Evaluation of && and ||

if ( value >= 0 && value <= 100 ) // Check if value is in the range 0 – 100

if ( ch == ' ' || ch == '\n' || ch == '\t' ) // Check for whitespace char

if ( year % 4 == 0 && year % 100 != 0 || year % 400 == 0 )


System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");

Implementing Logical Exclusive OR


Note: Bitwise AND &
(bool1 || bool2) && !(bool1 && bool2) Bitwise OR |
Bitwise XOR ^

if (!( x >= y )) is better written as the equivalent if (x < y)


if (!( x == y )) is better written as the equivalent if (x != y)

Nested if statements
- always use { } to associate an else with the appropriate if
- indentation means nothing to the compiler

Pre- and Post-Increment/Decrement

++var --var var++ var--

9
CSE 11 - Intro to Java, Expedited – Notes Packet
2. for loops, while loops, and do while loops

General structure of for loop:

for ( initialization exp; loop condition; loop exp )


statement;

for ( initialization exp; loop condition; loop exp ) {


statement;
statement;
}
- { } define the body of the loop (loop block)
- initialization exp executed once
- loop condition executed before loop body is executed
- loop will not execute if loop condition is false
- loop exp executed after loop body and before loop condition is checked again with next iteration

General structure of while loop:

while ( loop condition )


statement;

while ( loop condition ) {


statement;
statement;
}
- { } define the body of the loop (loop block)
- loop condition executed before loop body is executed
- loop will not execute if loop condition is false

A while loop that is (basically) equivalent to a for loop:

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 );

- { } define the body of the loop (loop block)


- loop condition executed after loop body is executed
- loop body always executed at least once

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

}
}

For loop flow:

1. initialization exp evaluated first


2. loop condition evaluated; if false goto next statement after loop block
3. execute loop body
4. execute loop exp; goto 2.

11
CSE 11 - Intro to Java, Expedited – Notes Packet

Nested For Loops

public class MultiplicationTables { Output:


public static void main( String[] args ) { 1 x 1 = 1
//complete me 1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10
------------
2 x 1 = 2
} .
} .
.

------------

For loop variants

for (i = 0, j = 10; i < j; i++, j--) {


statements;
}

for ( ; k-- > j; ) { for ( ; ; ) { while ( true ) {


statements; statements; statements;
} } }
- this is a good candidate for a while loop - forever loop - forever loop

Do While Loops

/*
* Program to display the square of integers from 1 to 10.
*/

public class Squares1 {

public static void main( String[] args ) {

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
}

2. String in Java (https://docs.oracle.com/javase/10/docs/api/java/lang/String.html)


String is a data type in Java that is used to store a sequence of characters. It is an Object type, not a primitive
- string concatenation operator ( + )
- only object type with which Java provides literals "Hello World"
- equals() [vs. ==], length(), charAt(), and many more
What is the output of the following code snippet?
String name = "Hazel";
System.out.println("name = " + name);
System.out.println("length = " + name.length());

//substring is left inclusive, right exclusive


System.out.println(“substring = “ + name.substring(2, 4));
System.out.println("name starts with = " + name.charAt(0));
System.out.println(“loc for a = “ + name.indexOf(‘a’));
System.out.println("name ends with = " + name.charAt(name.length() - 1));

StringBuilder: Another type to represent string information but it is mutable.


public class Tester{
public static void main(String[] args){
//Code A: What does the code print?
StringBuilder b=new StringBuilder(“hello”);
b.append(“ there!”);
System.out.println(b.toString());
A. Both print hello there!
//Code B B. Both print hello
String s=new String(“hello”); C. A prints hello and B prints hello there!
s.concat(“ there!”); D. A prints hello there! and B prints hello
System.out.println(s); E. Compiler error for A as we need to import
}
} StringBuilder

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.

If user inputs "Hello“, you print "He"


If user inputs "abcdefg“, you print "ab"
If user inputs "ab“, you print "ab"

Step 1: Understand the problem


• Understand what the code is supposed to do
• Give 5-10 examples

Step 2: Design your algorithm on paper.


• Make sure your algorithm is listed step by step
• Make sure your algorithm produces correct outputs for each of the examples you came up in step 1
• Redesign your algorithm if necessary.

Step 3: Code it up and fix any bugs you may have.

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.

if user inputs "abc“, you print "bca"


if user inputs "tca“, you print "cat"
if user inputs "tcagdo“, you print "catdog“
if user inputs “1234567890“, you print “231564897“

2. Operator Precedence

Java Operator Precedence Table


Operator Description Associativity
() method invocation left-to-right
public class Evaluation1 { [] array subscript
public static void main( String[] args ) { . member access/selection
++ unary postfix increment right-to-left
int b = 9; -- unary postfix decrement
b = b + (b = 3); ++ unary prefix increment right-to-left
System.out.println( "b = " + b ); -- unary prefix decrement
+ unary plus
} - unary minus
} ! unary logical negation
~ unary bitwise complement
( type )
What gets printed? new
unary cast
object creation
A. b = 3 *
/
multiplication
division
left-to-right

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

E. Compile Error >>> logical/unsigned right shift (zero shifted in)


< less than left-to-right
<= less than or equal to
> greater than
>= greater than or equal to
public class Evaluation2 { instanceof type comparison
== is equal to (equality) left-to-right
public static void main( String[] args ) { != is not equal to (inequality)
int a = 1; int b = 2; int c = 3; & bitwise AND left-to-right
System.out.println(a+b+c+”:”+a+(b+c)); boolean logical AND (no short-circuiting)
^ bitwise exclusive OR left-to-right
} boolean logical exclusive OR
} | bitwise inclusive OR left-to-right
boolean logical inclusive OR (no short-circuiting)
&& logical/conditional AND (short-circuiting) left-to-right
|| logical/conditional OR (short-circuiting) left-to-right
What gets printed? ?: conditional/ternary (if-then-else) right-to-left
= assignment right-to-left
A. 123:123 += addition assignment
-=
B. 123:15 *=
subtraction assignment
multiplication assignment
C. 6:123 /=
%=
division assignment
modulus/remainder assignment
D. 6:15 &= bitwise AND assignment
^=
E. 6:6 |=
bitwise exclusive OR assignment
bitwise inclusive OR assignment
<<= bitwise left shift assignment
>>= bitwise arithmetic/signed right shift assignment
>>>= bitwise logical/unsigned right shift assignment

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

- Go through the string and find the pattern


e.g. count the number of sequence “aaa” in a string

- Shuffle the characters in a string


e.g. view a string as a collection of pair of characters and swap the two characters in each pair

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

import java.util.*; How many variables are created in the stack?


public class Test{ A. 2
public static void main(String args[]){ B. 3
Scanner key = new Scanner(System.in);
String input = key.nextLine();
C. 4
int length = input.length(); D. 5
for (int i = 0; i < length; i++){ E. None of the above
String tmp = input.substring(0, i);
System.out.println(tmp); How many objects are created if I enter "ab"
}
}
A. 2
} B. 3
C. 4
D. 5
E. None of the above
18
CSE 11 - Intro to Java, Expedited – Notes Packet
Memory Models in Java, Methods
1. Memory Model Principles
Memory Model:
• A conceptual model on where variables and objects are stored in memory
• Properties of variables: name, type, value
• Life span: from creation to being destroyed for a variable or object
• Scope: when we can use an object or variable

Principles (so far):


• Location
o Variables declared in main: reside in the stack
o Objects created: reside in the heap
• Type
o primitive: simple types (double, int, char, etc)
o reference type: holds the leash for objects
• Value
o Primitive: value itself
o reference: address of the object (aka arrow)

public class Test{


public static void main(String args[]){
String name1 = new String("Christine"); What get printed by the code
String name2 = name1; A. Christine Christine Christine
String name3 = new String("Paul"); B. Paul Paul Paul
name2 = name3; C. Christine Paul Paul
System.out.print(name1 + " "); D. Christine Christine Paul
System.out.print(name2 + " ");
System.out.print(name3);
}
}

public class Test{


public static void main(String args[]){
StringBuilder name1 = new StringBuilder("Christine");
StringBuilder name2 = name1;
name2.append(" Mia");
StringBuilder name3 = new StringBuilder("Paul");
name2 = name3;
name2.append(" Rick");
System.out.print(name1 + " ");
What get printed by the code
System.out.print(name2 + " "); A. Christine Mia Christine Mia Christine Mia
System.out.print(name3); B. Christine Christine Mia Christine Rick
} C. Christine Paul Rick Paul
} D. Christine Mia Paul Rick Paul Rick

19
CSE 11 - Intro to Java, Expedited – Notes Packet
2. Methods/Functions/Procedures in Java

They let us break down our programs into a bunch of sub-steps


- Makes it easier to think of a solution to a complex problem
They let us independently debug each component of a program
- It’s easier to debug a small component (input → expected output vs. actual output)
They allow us to reuse code instead of rewriting it over and over again
- e.g. what if I want to check if a number is prime at multiple parts of my program?

public class Definition {

private int instanceVariable; // one per object instance

private static int classVariable; // one per class

private final int INSTANCE_CONSTANT = 42; // can optimize inline

public static final int CLASS_CONSTANT = 42;


// can access as Definition.CLASS_CONSTANT outside this class

public Definition() { // new Definition();


int localVar; // one localVar per constructor invocation/stack frame
}

public Definition( int param ) { // new Definition( ... );


// one param per constructor invocation/stack frame
int localVar; // one localVar per constructor invocation/stack frame
}

public Definition( Definition param ) { // new Definition( defRef );


// one param per constructor invocation/stack frame
int localVar; // one localVar per constructor invocation/stack frame
}

public void instanceMethod( int param ) { // ref.instanceMethod( ... );


// one param per method invocation/stack frame
int localVar; // one localVar per method invocation/stack frame
}

public static void classMethod( int param ) { // Definition.classMethod( ... );


// one param per method invocation/stack frame
int localVar; // one localVar per method invocation/stack frame

} // can access only other static members directly!


}

20
CSE 11 - Intro to Java, Expedited – Notes Packet

Methods (and Constructors)


Formal Parameters
Local Variables
Parameter(s): the variables that are part of the function being called.
Argument(s): the values that are passed in when a function call happens

public static int multiply(int a, int b){


return a * b;
}

public static void main(String args[]){


int x = 5;
int y = 10;
int product = multiply(x, y);
}

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)

Examples include Math.abs(), Math.max(), Math.min()


public static int max(int a, int b) { ... }
public static long max(long a, long b) { ... }
public static float max(float a, float b) { ... }
public static double max(double a, double b) { ... }

How to write/test a method

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

A. public static String xyzMiddle()


Step 1: design method prototype B. public static void xyzMiddle(String input)
C. public static boolean xyzMiddle()
D. public static boolean xyzMiddle(String input)

Step 2: Come up with test cases (5-8 of them)

Step 3: Design on paper

Step 4: Write your tester

Step 5: Write your code

22
CSE 11 - Intro to Java, Expedited – Notes Packet
Scope of variables, Call tracing
public class Order {

public static void main( String[] args ) {


int x;
x = one() + two() + three() + four() * five();
System.out.println( "x = " + x );
}

public static int one() { System.out.println( "1" ); return 1; }


public static int two() { System.out.println( "2" ); return 2; }
public static int three() { System.out.println( "3" ); return 3; }
public static int four() { System.out.println( "4" ); return 4; }
public static int five() { System.out.println( "5" ); return 5; }

}
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

public class StringPlay {


public static void changeIfEqual(String a, String b, String c) {
if( a == b ) {
b = c;
}
} What is printed?
A. a= Bob b= Bob c= Robert
public static void main(String[] args) {
B. a= Bob b= Robert c= Robert
String a = new String("Bob");
C. Error
String b = new String("Bob");
String c = new String("Robert");
changeIfEqual(a,b,c);
System.out.println("a= " + a + " b= " + b + "c= "+c);
}}

public class StringPlay {


public static void changeIfEqual(String a, String b, String c) {
if( a.equals(b) ) {
b = c;
} What is printed?
} A. a= Bob b= Bob c= Robert
B. a= Bob b= Robert c= Robert
public static void main(String[] args) { C. Error
String a = new String("Bob");
String b = new String("Bob");
String c = new String("Robert");
changeIfEqual(a,b,c);
System.out.println("a= " + a + " b= " + b + "c= "+c);
}}

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

Draw Stack Frames!!!


Factorial Problem
n! = n * (n – 1)! 0! = 1 and 1! = 1 Recurrence relation:

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;
}

Iteration vs. Recursion


public static long factorial(int num) {
long result = 1;
while (num > 1) {
result = result * num--;
}
return result;
}

25
CSE 11 - Intro to Java, Expedited – Notes Packet

What is printed from the following code in Tester.java?


What isstatic
public printedvoid
from the following
foo(int x) code in Tester.java?
{ public static void foo(int x) A. Prints out 5
{if (x>1)
System.out.println(x);
foo(x-1);
A.B.Prints
Printsout
out5 the numbers from 5 down to 1
if (x>1)
System.out.println(x); B.C.Prints
Printsout
oufthethe
numbers
numbersfrom 5 down
from 1 up toto51
} foo(x-1); C.D.Prints
I haveouf
NOtheIDEA!
numbers from
I am 1 up to 5
LOST!
}
public static void main(String[] args){
public
foo(5);static void main(String[] args){
} foo(5);
}

Exercise 1: Write a code that will generate the 200th Fibonacci number. Fibonacci sequence is as follows:

𝐹(𝑛) = 𝐹(𝑛 − 1) + 𝐹(𝑛 − 2) 𝑖𝑓 𝑛 ≥ 2


𝐹(0) = 1, 𝐹(1) = 1
Please use both the iterative approach and the recursive approach

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)

First array element is referred to using subscript 0


array[0]
• beware of "off-by-one" errors

Every array object in Java knows its own length


array.length

Forward iteration
for( int i = 0; i < array.length; ++i ) {
...
}

Backward iteration

Neighbor check

1. If an array is non-decreasing

2. if any of the three neighboring elements in the array is 1 2 3

27
CSE 11 - Intro to Java, Expedited – Notes Packet
Declaring and Allocating Arrays

final int ARRAYSIZE = 10;


int[] array; // declares a reference to an array object
array = new int[ARRAYSIZE]; // creates a new array object

or
0 1 2 3 4 5 6 7 8 9
int[] array = new int[ARRAYSIZE]; array

or
length
int array[] = new int[ARRAYSIZE];

• if ARRAYSIZE = 0, the array is said to be empty

• when arrays are allocated, the elements are automatically initialized


- to zero for the numeric primitive data type variables
- to false for boolean variables
- to null for references

• an array's length is not part of its type


- a single array variable (reference) may reference arrays of different lengths

int[] a;
a = new int[10];
...
a = new int[20];

• elements of an array can be initialized in the array declaration


- this implicitly creates an array object
- array size is determined by the number of elements in the initializer list

int[] a = { 1, 2, 3, 4, 5 };
or
int[] a = new int[] { 1, 2, 3, 4, 5 };

what is the memory model for the following code?


int[] array1 = {1, 2, 3};
int[] array2 = array1;
array2[1] = 5;
array2 = new int[4];

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

Follow up: How about this doSth function?


public static int[] doSth(int[] inputArray) {
int[] result = inputArray;
return result;
}

Array Access

- all arrays are 0-origin


- arrays must be accessed by int index values
- array accesses are checked at run time
- 0 > index >= array.length causes an IndexOutOfBoundsException to be thrown (runtime
exception)

1. public class IOOBEx {


2. public static void main( String[] args ) {
3. System.out.println( "IndexOutOfBoundsException example" );
4. int[] a = new int[3];
5. for( int i = 0; i <= a.length; ++i ) { // should be i < a.length
6. a[i] = i;
7. }
8. }
9. }

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.

• Java does not support the C/C++ notion of a multidimensional array


• Java supports arrays of arrays
int[][] a = new int[2][3]; a 0 1

Exercise: print elements of a 2d array using nested for loops


int[][] data = new int[2][3];
//put values into the 2D array
//Now print everything out

30
CSE 11 - Intro to Java, Expedited – Notes Packet

public class TwoD{

public static void print(int[][] array, int i, int j){


System.out.println(array[i][j]);
}
public static void main(String[] args){
int[][] data = new int[4][2];
for (int i = 0 ; i < 4; i++){
for (int j = 0; j < 2; j++){
data[i][j] = i + j;
}
}
System.out.println("First round");
System.out.println(data.length);
System.out.println(data[0].length);
System.out.println(data[1].length);

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

It is a utility class that can help processing arrays in Java.


import java.util.Arrays;

public class ArraysDemo {


public static void main(String[] args) {

//1. copyof to make a deep copy

int[] arr = new int[] { 1, 3, 5, 7, 9, 10, 8, 6, 4, 2, 0 };


arr={4,5,6}
// this is deep copy
int[] intcopy = Arrays.copyOf(arr, arr.length);

StringBuilder [] names = new StringBuilder[3];


names[0] = new StringBuilder("Paul");
names[1] = new StringBuilder("Christine");
names[2] = new StringBuilder("Rick");
//this is deep copy of the reference
StringBuilder[] namescopy = Arrays.copyOf(names, 3);

//2. copyofRange from to. It is allowed to have a bigger range


int [] part1 = Arrays.copyOfRange(arr, 0, 3);//not including 3
System.out.println(Arrays.toString(part1));

31
CSE 11 - Intro to Java, Expedited – Notes Packet

//3. fill - fill in the array with some value


int [] empty = new int[10];
Arrays.fill(empty, -1);
System.out.println(Arrays.toString(empty));

//4. equals - deep comparison


int [] arr1 = new int[]{1, 3, 5};
int [] arr2 = new int[]{2, 4, 6};
System.out.println(Arrays.equals(arr1, arr2));

//5. sort - change the array itself

int [] orig = new int[]{2, -4, 5, 6, -1, -1, -3};


String[] classes = new String[]{"cse11", "bio101", "Zoology121", "Anth202"};

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?

A – Just resize the array, in place, as needed


B – Start with a array, but when you run out of space, create new, larger
arrays, and copy over all the elements
C – Make an array the size of MAXINT, it should have enough space
D – None of the above

Conventional arrays are fixed in size

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:

ArrayList<Type> list = new ArrayList<Type>();

Example:
ArrayList<String> list = new ArrayList<String>();
ArrayList<int> intList=new ArrayList<int>(); (error)

Useful methods (http://docs.oracle.com/javase/10/docs/api/java/util/ArrayList.html)


boolean add(E e)
Appends the specified element to the end of this list

void add(int index, E element)


Inserts the specified element at the specified position in this list

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

// Fill ArrayList with 10 ints in Integer wrapper objects


for (int i = 0; i < 10; ++i )
list.add( new Integer( i ) ); // boxing. Can do list.add(i);
// Display ArrayList's size and capacity
System.out.println( "ArrayList's size = " + list.size());

// Enumerate ArrayList using standard indexing


for (int i = 0; i < list.size(); ++i ){
System.out.print( ( list.get( i ) ).intValue() + " " );
}
System.out.println();
}
}

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)

Objects provide information hiding by


separating implementation and interface
• implementation details are hidden within
the object (how the class implements
state/messages)
- private instance variables and methods
• interfaces allow objects to know how to
communicate with one another (what
messages can be sent)
- public methods and constructors

The class is the OO unit of programming defining types


• encapsulates data (instance variables) and behavior (methods) that manipulate the data
• an object is instantiated (created usually with new) and initialized (by a constructor) at runtime
• the class name is a new type specifier (user-defined type)

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

1. The name of the Student object


2. The age of the Student object
3. How many Student objects have been created by the Student class.
How many static variables should I have for this class?
A. 1 B. 2 C. 3 D. None E. It depends

Local Variables and Formal Parameters


• local variables are defined in a method body or within a code block - { } define a code block
• local variables cannot be public, private, protected, or static
• formal parameters are also considered local to the method block (block scope)

• duration/lifetime (period during which an identifier exists in memory)


- created when the block in which they are defined is entered
- they exist while the block is active
- they are destroyed when the block is exited

• scope (where an identifier can be referenced in a program)


- block scope — from the point of definition to the end of the block ( } )
- hiding the name of a local variable or formal parameter is not permitted (unlike C/C++)
int i;
for ( int i = 0; ... ) { … } // Will give a compile error
----------------------------------------------------------------------------------
int i;
for ( i = 0; ... ) { … } // Okay - only one definition of i
// i is accessible here after the loop block
----------------------------------------------------------------------------------
// int i;
for ( int i = 0; ... ) { … } // Okay since no local variable i
for ( int i = 0; ... ) { … } // Separate blocks

• 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 {

private int instanceVariable; // one per object instance

private static int classVariable; // one per class

private final int INSTANCE_CONSTANT = 42; // can optimize inline

public static final int CLASS_CONSTANT = 42;


// can access as Definition.CLASS_CONSTANT outside this class

public Definition() { // new Definition();


int localVar; // one localVar per constructor invocation/stack frame
}

public Definition( int param ) { // new Definition( ... );


// one param per constructor invocation/stack frame
int localVar; // one localVar per constructor invocation/stack frame
}

public Definition( Definition param ) { // new Definition( defRef );


// one param per constructor invocation/stack frame
int localVar; // one localVar per constructor invocation/stack frame
}

public void instanceMethod( int param ) { // ref.instanceMethod( ... );


// one param per method invocation/stack frame
int localVar; // one localVar per method invocation/stack frame
}

public static void classMethod( int param ) { // Definition.classMethod( ... );


// one param per method invocation/stack frame
int localVar; // one localVar per method invocation/stack frame

} // can access only other static members directly!


}

38
CSE 11 - Intro to Java, Expedited – Notes Packet
Object-Oriented Design
- designing software with objects that often mimics the real world

Identify the objects to be modeled in your program

For each type of object identified:

- 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)?

- public ctors and methods define the object's public interface


- what messages can be sent to this object; how other objects can use this object

- private ctors and methods are for internal use only

public class Student{


public String name;
public double grade;
public Student (String name, double grade){ Should this compare method be static or non-
this.name = name; static?
this.grade = grade; A: It should be static
} B: It should be non-static
C: It depends on how you design this method
//Want to write a compare method to compare D: I really have no idea.
//two students based on their grade. It returns the
//name of the student with the higher grade
}

Case Study: Game of


Nim Design the class (variables and methods)

39
CSE 11 - Intro to Java, Expedited – Notes Packet

public class Nim {


private int[] board;
private int turn;

public Nim(){//create board to be {7, 5, 3, 1} and set turn to be 1

}
public Nim(int[] b, int t){//copy b to board and t to turn

}
}

public class Nim {



public static void main( String[] args )
{
Nim game1 = new Nim(); What is printed by the above code? (Hint:
Nim game2 = new Nim();
game1.board[2] = 100; Draw the memory model.)
game2 = game1; A. 3
System.out.println( game2.board[2] ); B. 100
} C. Nothing, there is a compile error
} D. Nothing, there is an array out of
bounds exception
E. I don’t know

Complete the remaining methods from the Nim class

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

All of this leads to


Abstraction – factoring out details so an object can be easily used without knowledge of how it works

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;
} }

public final class String{


//provided by Java
......
}

public class Student{


public Student(){
id = 0;
name = new String(“Jane Doe”);
addr = new Address(“9500 Gilman Dr”, “La Jolla”, “CA”, “92093”);
}
//other methods If in another tester file’s main code, we have
}
Student s = new Student();

How many objects are created?


A. 1
B. 2
C. 3
D. 4
E. None of the above

When we write the Address class, do we have to know how Student class will use it? A. Yes B. No

How about the reverse?


41
CSE 11 - Intro to Java, Expedited – Notes Packet
Write the constructors and getters/setters. Include no-arg ctor, basic ctor,
and copy ctor.
public class Address {
//Our own class
private String street;
private String city;
private String state;
private String postalCode;

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

OO Programming involves encapsulation/data hiding, inheritance, and polymorphism


- inheritance
- classes are created from existing classes (extends keyword)
- implicit extends Object in the absence of an explicit extends
- inherit attributes and behaviors of an existing class (superclass)
- superclass should provide functionality useful in many subclasses
- embellish these with new/different capabilities in new classes (subclass)
- inheritance of interface (implements) / inheritance of implementation (extends)
- is-a relationship

- 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)

indirect superclass class Indirect_Superclass

single inheritance

superclass class Superclass extends Indirect_Superclass

single inheritance

subclass class Subclass extends Superclass

- Java does support multiple inheritance of interfaces


- achieves many of the advantages of multiple inheritance without the associated problems
- pure inheritance of interface

superclass interface1 interface2 ...

subclass class Subclass extends Superclass


implements Interface1, Interface2

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

Composition vs. Inheritance


- inheritance
- is-a relationship
- create new classes by extending existing classes (below is not a good example for other reasons)

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

Which ones are true?


A. 1, 2, 3, 4 B. 1, 2, 4 C. 2, 3, 4 D. 2, 4 E. 3, 4

Student

GraduateStudent UndergraduateStudent

Masters PhD Freshman Sophomore Junior Senior

class UndergraduateStudent extends Student


class GraduateStudent extends Student
class Masters extends GraduateStudent
...
What You Can Do in a Subclass
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is
in. If the subclass is in the same package as its parent, it also inherits the package-private members of the
parent. You can use the inherited members as is, replace them, hide them, or supplement them with new
members:
• The inherited fields can be used directly, just like any other fields.
• You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it
(not recommended).
• You can declare new fields in the subclass that are not in the superclass.
• The inherited methods can be used directly as they are.
• You can write a new instance method in the subclass that has the same signature as the one in the
superclass, thus overriding it.
• You can write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it.
• You can declare new methods in the subclass that are not in the superclass.
44
CSE 11 – Intro to Programming, Expedited
• You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or
by using the keyword super.
Private Members in a Superclass
A subclass does not inherit the private members of its parent class. However, if the superclass has public or
protected methods for accessing its private fields, these can also be used by the subclass.
public class Base{
public void foo(int x){ If the code runs, what is the output?
System.out.println(“foo1"); A. foo1
} B. foo2
public int foo(int x){ 2
System.out.println(“foo2"); C. Compiler error
return x; D. Run time error
}
public static void main(String [] args){
Base b=new Base();
System.out.println(b.foo(2));
}
}

public class Derived extends Base{


public class Base{ public int foo(){
public void foo(int x){ int answer=super.foo(8.5);
System.out.print("foo1 "); System.out.print("foo3 ");
} return answer;
public int foo(double x){ }
System.out.print("foo2 "); public int foo(double x){
return (int)x; foo(2);
} System.out.print("foo4 ");
} return (int)x;
}
public static void main(String [] args){
If the code runs, what is the output? Derived d=new Derived();
A. foo2 foo3 8 System.out.print(d.foo());
B. foo4 8 foo3 }}
C. foo4 foo3 8
D. Compiler error
E. Run time error

How about System.out.print(d.foo(2.5))?

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.

Member Access Modifiers (for variables and methods)

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

None — friendly-access / package-access / default-access


- access is permitted only from within the same package

Java Access Modifiers Visibility

Package P

Superclass Class within


same package P
public A
protected B Sees public A
default C protected B
private D default C

Subclass Subclass Class


within package P outside package P outside package P

Sees public A Sees public A Sees public A


protected B protected B
default C

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)

Constructor rules related to inheritance


1. If a class contains no constructor definitions, compiler will automatically insert a default (no-arg) ctor
public class Point extends Object {
public class Point { private int x, y;
public Point() {
private int x, y; implies super();
}
}
2. In the constructor body, first line of code may }be either
this( argsopt ) - same class ctor call
or
super( argsopt ) - super class ctor call
else compiler automatically inserts as first statement
super(); - super class ctor call

abstract class SuperClass{ class SubClass extends SuperClass{


private int x; private int y;
public SuperClass(int x){ public SubClass(){
this.x = x; super(8);
System.out.print("1"); y = 10;
} System.out.print("3");
public abstract void foo(); }
} public SubClass(int x, int y){
super(x);
this.y = y;
System.out.print("4");
If in a test we have }
SubClass ref = new SubClass(); public void foo(){
System.out.println("foo");
}
What is the output?
A. compiler error.
B. Runtime error.
C. 3
D. 13

47
CSE 11 – Intro to Programming, Expedited

class SuperClass{ class SubClass extends SuperClass{


private int x; private int y;
public SuperClass(){ public SubClass(){
x = 5; y = 10;
System.out.print("1"); System.out.print("3");
} }
1. Relationship between Superclass
public SuperClass(int x){ Objects and Subclass
publicObjects
SubClass(int x, int y){
this.x = x; this();
System.out.print("2");
It is possible to treat superclass objects and subclass objectsthis.y
similarly
= y;
} System.out.print("4");
- 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
What is theisoutput
not true
for the following statements?

Implicit
1. Subclass-Object-to-Superclass-Object
SuperClass s1 = new SuperClass();Conversion
2. SuperClass s2 = new SuperClass(9);

3. SubClass s3 = new SubClass(); 4. subClass s4 = new SubClass(4, 5);

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

Classes may implement multiple interfaces


- multiple inheritance of interface
public class Circle implements Resizable, Movable, Colorable

Extending Interfaces
public interface SubInterface extends SuperInterface1, SuperInterface2

Program to an Interface, Not an Implementation


- Implementation inheritance (extends) is best for small numbers of tightly coupled classes
- Interface inheritance (implements) is best for flexibility

public interface OperateCar {


// constant declarations, if any
49
CSE 11 – Intro to Programming, Expedited
public static final int numWheels = 4;

// method signatures. Can omit public abstract


public abstract moveForward(double speed);
int turn(Direction direction, double radius, double startSpeed, double endSpeed);
int changeLanes(Direction direction, double startSpeed, double endSpeed);
int signalTurn(Direction direction, boolean signalOn);
int getRadarFront(double distanceToCar, double speedOfCar);

//default method.
default int getRadarRear(double distanceToCar, double speedOfCar){
return distanceToCar / speedOfCar;
}
......
// more method signatures or default methods
}

By default, all interface method headers are public and abstract

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.

public class OperateBMW760i implements OperateCar { OperateCar

// the OperateCar method signatures, with implementation --


// for example:
int signalTurn(Direction direction, boolean signalOn) {
// code to turn BMW's LEFT turn indicator lights on
OperateBMW760i OperateToyota
// code to turn BMW's LEFT turn indicator lights off
// code to turn BMW's RIGHT turn indicator lights on
// code to turn BMW's RIGHT turn indicator lights off
} Type Hierarchy
// other members, as needed -- for example, helper classes not
// visible to clients of the interface
}

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

class keyword in definition class keyword in definition interface keyword in definition

extends keyword extends keyword implements keyword


- pure inheritance of implementation - mixture of inheritance of interface - pure inheritance of interface
and inheritance of implementation

is-a relationship is-a relationship is-a relationship

Defines a new type Defines a new type Defines a new type

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

2. Suppose A is an abstract class.


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

3. It is possible that an interface has a concrete method. A. True B. False


4. An abstract class may not have an abstract method. A. True B. False
5. An abstract class may implement multiple interfaces. A. True B. False
6. An interface can extend from an abstract class. A. True B. False
7. An abstract class cannot be a child of another class, whether the parent is abstract or not.
A. True B. False
8. We can have multiple layers of inheritance on interfaces.
A. True B. False

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

Implicit Subclass-Object-to-Superclass-Object Conversion

- subclass object is a superclass type


- but the subclass type and the superclass type are different types

- 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

superclassRef.subclassSpecific() // Error — no subclassSpecific() in SuperClass

((SubClass) superclassRef).subclassSpecific() // OK, but should check at runtime

- 4 ways to mix/match superclass/subclass references with superclass/subclass objects


1) superclass reference —> superclass object ( superRef = new SuperClass(); )
2) subclass reference —> subclass object ( subRef = new SubClass(); )
3) superclass reference —> subclass object ( superRef = subRef; )
- can only refer to superclass members (members common to superclass and subclasses)
- referring to subclass-only members through superclass reference is a syntax error
3a): if you need to access subclass-specific members via the superclass reference, must cast
See above example accessing subclass-specific members with superclass reference

4) subclass reference —> superclass object ( subRef = superRef; )


- this is a compile-time error
4a): if superclass reference refers to a subclass object (not a superclass object), must cast to the
subclass type before assignment. Then runtime check to guarantee object really is a SubClass type.

superRef = new SubClass();


if ( superRef instanceof SubClass )
{
subRef = (SubClass) superRef;
}

- if we want to manipulate subclass objects through superclass references [Key Point]

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)

Software Engineering with Inheritance

- use inheritance to customize existing software


- add attributes and behaviors or override superclass behaviors to customize the class
- super.overriddenMethod() to incorporate superclass's behavior with subclass's behavior

- superclass specifies commonality in attributes and behavior


- all classes derived from a superclass inherit the capabilities of that superclass
- subclasses are then customized

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

- each class has a draw() method to draw itself (specific implementation)

- want to treat all shapes generically as objects of the superclass Shape


- superclass Shape reference can reference any of these specific shape objects
- want to be able to draw any of these objects generically through a superclass reference

Shape shape;

shape = circle; shape = square; ...

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

- a final method cannot be overridden in a subclass


- methods that are declared static or private are implicitly final
- compiler can optimize final method calls by inlining the code
- static (compile-time) method binding

- a final class cannot be a superclass


- final class cannot be inherited/extended
- all methods in a final class are implicitly final

public abstract class Snake{


public class Cobra extends Snake{
private double length;
private boolean king;
public Snake( double length ){
public Cobra( double length, boolean king ) {
this.length = length;
super(length);
}
this.king = king;
public boolean isHungry( int daysWOFood ){
}
return daysWoFood >=4;
public boolean isHungry( int days ){
}
return days >=10;
public double getLength(){ }
return this.length; public String toString(){
} String result = super.toString();
public String toString(){ return result + ": "+
return Double.toString(this.getLength()); (king==true?" ":"not ") + "a king cobra"; }}
}
public void status( int days ){
if ( this.isHungry( days ) )
System.out.println( "Watch Out : " + this );
else
System.out.println( "No Worry: " + this );
}
}

What will this code print?


1. What is printed with if we have the following code?
Cobra c; A. No Worry: 2.5: a king cobra
c = new Cobra( 2.5, true ); B. Watch Out: 2.5: not a king cobra
c.status( 5 ); C. No Worry: a king cobra
D. Watch Out: not a king cobra
2. What is printed with if we have the following code? E. Other (or error)
Snake s;
s = new Cobra( 2.5, true );
s.status( 5 );

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()

Snake A. Compiler error


B. Runtime error A. Compiler error
C. Python 1 B. Runtime error
D. Slither C. Snake 2
Python Cobra E. Something else D. Cobra 2
E. Something else

Prob 3. Prob 4.
Crawable var3 = new Cobra(); Crawable var4 = new Cobra();
var3.crawl() var4.method2()

A. Compiler error A. Compiler error


B. Runtime error B. Runtime error
C. Spit too C. Cobra 2
D. Slither D. Snake 2
E. Slither Spit too E. Something else

Prob 5. Prob 6.
Snake var5 = new Cobra(); Crawlable var6 = new Python();
((Python)var5).method1(); ((Cobra)var6).method3();

A. Compiler error A. Compiler error


B. Runtime error B. Runtime error
C. Python 1 C. Python 3
D. Snake 1 D. Cobra 3
E. Something else E. Slither Spit too

55
CSE 11 – Intro to Programming, Expedited

public boolean equals(Object o){


return age == ((Human)o).age;
}

public boolean equals(Object o){


return super.equals(o) && units == ((Student)o).units;
}

public boolean equals(Object o){


return super.equals(o) && classes.equals(((Tutor)o).classes);
}

//In a tester file


Student s = new Student();
Tutor t = new Tutor();
Human h = new Human();
String n = new String(“Paul”);

Part 1, Out of the following


statements, how many
compiler errors do we have?

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);

Part 2, Out of the following


statements, how many runtime
errors do we have?

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.

abstract class Snake {


public void meth( Snake other ) {
System.out.print( "#1, " );
}
}

class Cobra extends Snake {

public void meth( Snake other ) {


System.out.print( "#2, ");
}
public void meth( Cobra other ) {
System.out.print( "#3, " );
}
}

public class Ultimate {

public static void main(String[]args){


Cobra cobra = new Cobra();
Snake snake_ref_cobra = new Cobra();

snake_ref_cobra.meth( snake_ref_cobra ); ___________

snake_ref_cobra.meth( cobra ); _________

cobra.meth( snake_ref_cobra ); __________

cobra.meth( cobra ); ___________


}
}

Key points summary

Polymorphism rules
ref.method1( args );

Compile time rules


• Compiler only knows the type of the reference
• Can only look in the class definition for that type
• Resolves the signature for that method call based on what methods are known in that type
• Emits code for that method signature it finds
Run time rules
• Follow the reference to determine the exact type of the actual object being referenced at run time
• Execute the code for the method signature determined at compile time as defined in that actual object
type being referenced

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?)

Run time check


The run time checks that the type of the actual object is compatible with the type cast (is-a relationship)
Sub subRef = (Sub)superRef;
((Sub)superRef).subClassSpecificMember();

What if superRef references a Super type (vs. a Sub type) at runtime?


ClassCastException: Super cannot be cast to Sub

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)?

FP divide by zero produces the FP value Infinity

Integer divide by zero produces a Runtime Exception:


Exception in thread "main" java.lang.ArithmeticException: / by zero
at GradeBook.determineClassAverage(GradeBook.java:72)
at GradeBookTest.main(GradeBookTest.java:14)

What happens if we expect an integer and enter a non-numeric string as input using Scanner's nextInt?

Exception in thread "main" java.util.InputMismatchException


at java.util.Scanner.throwFor(Scanner.java:819)
at java.util.Scanner.next(Scanner.java:1431)
at java.util.Scanner.nextInt(Scanner.java:2040)
at java.util.Scanner.nextInt(Scanner.java:2000)
at GradeBook.determineClassAverage(GradeBook.java:55)
at GradeBookTest.main(GradeBookTest.java:14)

And if we were using Integer.parseInt() to convert a String into an int, we would get a
NumberFormatException

Exception in thread "main" java.lang.NumberFormatException: For input string: "123b5"


at java.lang.NumberFormatException.forInputString(NumberFormatException.java:63)
at java.lang.Integer.parseInt(Integer.java:490)
at java.lang.Integer.parseInt(Integer.java:531)
at ExceptionTest1.main(ExceptionTest1.java:18)

Basic Exception Handling


try {
// method calls or expressions which may throw exceptions
}
catch( ExceptionType1 e1 ) {
// exception1-handling code
}
catch( ExceptionType2 e2 ) { // optional
// exception2-handling code
}
finally { // optional
// code that will always be executed
// whether an exception occurs or not
}

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)?

A. The method will throw a NullPointerException


B. The method will return null
C. Nothing different will happen (it will still return null and print the error
message)

Checked vs. Unchecked Exceptions


- Runtime exceptions and Errors are
unchecked exceptions
- all others are checked exceptions
"catch-or-declare" requirement

60
CSE 11 – Intro to Programming, Expedited

Complete the code to prompt the user to enter a new filename until the file exists

public String readIt( String filename ) {


File sourceFile = new File( filename );
Scanner input = null;
Scanner userInput = new Scanner( System.in );
//insert codes here

String allText = "";


while ( input.hasNextLine() )
{
String s1 = input.nextLine();
allText = allText.concat( s1 );
}
return allText;
}

Multiple Catch Blocks


public void myMethod( ) {
try {
// code can produce an IOException or runtime Exception. For
// the IOException, we’d like to print an error to the
// console, but not quit. For the runtime exception,
// we’d like to quit gracefully.
}
<<Catch Block 1>>
<<Catch Block 2>>

}
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 ){

Throwing Exceptions (https://docs.oracle.com/javase/10/docs/api/java/lang/Exception.html)


Common exceptions you may encounter:
NullPointerException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
NumberFormatException
InputMismatchException

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);
}

//If there is no cheating, just return true when done


return true;
}
public static void main(String[] args){

boolean result = false;


//... Other codes...
try{
result = grade("Paul");
}
catch(ForbiddenOperationException e){
System.out.println(e.getName() + " did: " +e.getMessage());
}
//continue to do other stuff
}
}

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

4. If doSth throws an ArithmeticException, 5. If doSth throws an IndexOutOfBoundsException,


what will be printed? what will be printed?
A. Inside finally A. Inside finally
All done All done
B. All done B. All done
C. Inside try C. Inside try
Inside finally Inside finally
All done All done
D. Inside finally D. Inside finally
(then crash) (then crash)
E. None of the above. It’s E. None of the above. It’s
something else something else

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)

In CSE 11, we use two sets of Input/Output tools.


One is Scanner/PrintWriter and the other one is
BufferedReader/BufferedWriter.

- 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.

2. Formatted File Input


When reading a file, the most important steps are
- Know the format of the file (type of data and layout)
- Determine how the data will be used (i.e what kind of variables we use to store the data)
- Create objects to read the file

If the data is formatted (e.g. csv files etc),


then use Scanner: https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html
Scanner has two groups of functions:
- hasNext, hasNextInt, hasNextDouble, etc: They look ahead and return true if there is data of the
right type to read.
- next, nextInt, nextDouble, nextLine, etc: They read the next token.
- Tokens are separated by white spaces (space, tab, and new line)

- Note: To read from the keyboard, use new Scanner(System.in)


- Should always close the scanner once you are done using it.

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 everything from a file in the original format

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.

Sample input file Sample console output format


Paul Cao,98,96,40 Paul Cao 78.00
Mia Minnes,100,20,100 Mia Minnes 73.33
Christine Alvarado,100,100,100 Christine Alvarado 100.00
Gary Gillespie,10,20,100 Gary Gillespie 43.33

Discussion:
1. What is the basic unit of data when we try to process this file?

2. What is the type of variable we should use to store the data

3. How should we calculate the average and print it out.

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

File file = new File(“output.txt”)


PrinterWriter output = new PrinterWriter(file);
Scanner input = new Scanner(System.in);
System.out.println(“Please enter two integers: “);
int num1 = input.nextInt();
int num2 = input.nextInt();
int max = (num1 > num2? num1:num2);
output.println(“Max of “ + num1 + “ and “ + num2 + “ is “ + max);
output.close();

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

for (int i = 0; i < args.length; i++){


System.out.println(args[i]);
}
}
}

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?

public Object max(Object[] data)

A - The algorithm won’t be generic enough


B - We have to do a lot of type casting
C - It can’t take any primitive type array
D - AC
E - BC

69
CSE 11 – Intro to Programming, Expedited

Syntax: use type identifier in the diamond shape


public <E> E max (E[] data){
E maxV = data[0];
for (int i = 0; i < data.length; i++){
if (maxV.compareTo(data[i])<0){
maxV = data[i];
} What is the potential problem with the generic solution?
}
A – We have to name our type variable T instead of E
return maxV; B - We have to do type casting
} C - It can’t take any primitive type array
D - AC
E - BC

Where you can’t use generic variables


- In creating an object of that type: new T() // error
- In creating an array with elements of that type: new T[100] // error
- As an argument to instanceof: someref instanceof T // error

Note: To ensure that certain methods can be called, we can constrain the generic type to be subclass of an
interface or class

public <E extends Comparable> E max (E[] data){

Generic Class
Create a class which has multiple generic methods (like our ArrayList, Set, HashMap classes)

public class MyGList<T> { @Override


private T[] nums; public String toString() {
public MyGList() { String str = "";
nums=null; for (T n : nums) {
} if (n instanceof Object){
public MyGList(int size) { str += (n.toString() + ", ");
this.nums = (T[])new Object[size]; }
} }
public int size() { return str;
return this.nums.length; }
} public static void main(String[] args){
public void update(int ind, T data) { MyGList<Integer> vals = new
nums[ind] = data; MyGList<Integer>(3);
} System.out.println(vals);
vals.update(2, 7);
vals.update(0, 4);
vals.update(1, 3);
System.out.println(vals);
}
}

70
CSE 11 – Intro to Programming, Expedited
Additional Topic: Binary search
Binary search
Motivation: Look up phone contact on your phone

Limitation: only works on “ordered” data


Look in the middle of the data list (array).
• If that element is what you are looking for, return its index
• If not
o If what you are looking for “comes before” in the ordering, look in the half
on the left
o Else (what you are looking for “comes after” in the ordering), look in the
half on the right

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 )
{

int mid = (low+high) / 2;


if ( toFind < list[mid] )

return ________________________________

else if ( toFind == list[mid] )


return __________________________________

else // toFind is > list[mid]


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

2. Fill in the blanks above?

3. When will this method not work?


A. When the element you are looking for is the first element in the list
B. When the element you are looking for is the last element in the list
C. When the element you are looking for is not in the list
D. When the element you are looking for is less than 0
E. It will always work

72

You might also like