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

Week 2

cs

Uploaded by

deane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Week 2

cs

Uploaded by

deane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

CSE 11 – Intro to Programming, Expedited

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

1
CSE 11 – Intro to Programming, Expedited
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.*;
public class Test{
How many variables are created in the stack?
public static void main(String args[]){ A. 2
Scanner key = new Scanner(System.in); B. 3
String input = key.nextLine(); C. 4
int length = input.length(); D. 5
for (int i = 0; i < length; i++){
String tmp = input.substring(0, i); E. None of the above
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
1
CSE 11 – Intro to Programming, Expedited
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)

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

1
CSE 11 – Intro to Programming, Expedited
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) { ... }

2
CSE 11 – Intro to Programming, Expedited
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);
}}

3
CSE 11 – Intro to Programming, Expedited
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;
System.out.print(name1 + " "); C. Christine Paul Paul
System.out.print(name2 + " "); D. Christine Christine Paul
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

4
CSE 11 – Intro to Programming, Expedited
Note 7 – 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

1
CSE 11 – Intro to Programming, Expedited
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.*;
public class Test{
How many variables are created in the stack?
public static void main(String args[]){ A. 2
Scanner key = new Scanner(System.in); B. 3
String input = key.nextLine(); C. 4
int length = input.length(); D. 5
for (int i = 0; i < length; i++){
String tmp = input.substring(0, i); E. None of the above
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
2
CSE 11 – Intro to Programming, Expedited
Note 8 and 9 – Memory Models in Java
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;
System.out.print(name1 + " "); C. Christine Paul Paul
System.out.print(name2 + " "); D. Christine Christine Paul
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

3
CSE 11 – Intro to Programming, Expedited
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!


}

4
CSE 11 – Intro to Programming, Expedited

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

5
CSE 11 – Intro to Programming, Expedited
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


public class Order {

6
CSE 11 – Intro to Programming, Expedited
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);
}}

7
CSE 11 – Intro to Programming, Expedited
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();
}
}

8
CSE 11 – Intro to Programming, Expedited
Note 11 – 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;
}

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


public static void foo(int x)
{
if (x>1) A. Prints out 5
foo(x-1); B. Prints out the numbers from 5 down to 1
System.out.println(x); C. Prints ouf the numbers from 1 up to 5
}
public static void main(String[] args){ D. I have NO IDEA! I am LOST!
foo(5);
}

9
CSE 11 – Intro to Programming, Expedited

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


public static void foo(int x)
{
System.out.println(x); A. Prints out 5
if (x>1) B. Prints out the numbers from 5 down to 1
foo(x-1); C. Prints ouf the numbers from 1 up to 5
}
public 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.

10
CSE 11 – Intro to Programming, Expedited

11
CSE 11 – Intro to Programming, Expedited
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!


}

1
CSE 11 – Intro to Programming, Expedited

2
CSE 11 – Intro to Programming, Expedited
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();
}
}

3
CSE 11 – Intro to Programming, Expedited
Exercise
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; }

4
CSE 11 – Intro to Programming, Expedited
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;
}

1
CSE 11 – Intro to Programming, Expedited
Math version of recursion

A. 6 B. 7 C. 8 D. 9 E. 12

2
CSE 11 – Intro to Programming, Expedited

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


public static void foo(int x)
{ A. Prints out 5
if (x>1)
foo(x-1); B. Prints out the numbers from 5 down to 1
System.out.println(x); C. Prints ouf the numbers from 1 up to 5
} D. I have NO IDEA! I am LOST!
public static void main(String[] args){
foo(5);
}

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


public static void foo(int x)
{
System.out.println(x); A. Prints out 5
if (x>1) B. Prints out the numbers from 5 down to 1
foo(x-1); C. Prints ouf the numbers from 1 up to 5
}
public 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

3
CSE 11 – Intro to Programming, Expedited
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.

4
CSE 11 – Intro to Programming, Expedited
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

You might also like