Week 2
Week 2
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
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)
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
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);
}
}
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
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
3
CSE 11 – Intro to Programming, Expedited
2. Methods/Functions/Procedures in Java
4
CSE 11 – Intro to Programming, Expedited
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)
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
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 );
}
}
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
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
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;
}
9
CSE 11 – Intro to Programming, Expedited
Exercise 1: Write a code that will generate the 200th Fibonacci number. Fibonacci sequence is as follows:
Exercise 2: Given a number n, you should print the length of the 3n+1 sequence starting with n. The sequence is
constructed as follows:
• If the number n is odd, the next number will be 3n+1.
• If the number n is even, the next number will be n/2.
For example, the 3n+1 sequence of 3 is {3,10,5,16,8,4,2,1} and its length is 8.
Please use both the iterative approach and the recursive approach to solving this problem.
10
CSE 11 – Intro to Programming, Expedited
11
CSE 11 – Intro to Programming, Expedited
Methods/Functions/Procedures in Java
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 );
}
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
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;
}
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
Exercise 1: Write a code that will generate the 200th Fibonacci number. Fibonacci sequence is as follows:
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