You are on page 1of 50

Java Fundamentals

Understanding Recursion,
Recursion the Static Modifier,
Modifier and Nested Classes

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Overview
This lesson covers the following topics:
Create static variables
Use
U static
t ti variables
i bl
Create static methods
Use static methods
Create static classes
Use static classes

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Overview
This lesson covers the following topics:
Create linear recursive methods
Create
C t non-linear
li
recursive
i methods
th d
Compare the pros and cons of recursion

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Modifier
Using instance variables, each instance of a class created
with the keyword new creates a copy of all instance
variables in that class.
For example,
p in the Employee
p y class below, a unique
q copy
py
of lastname and firstname is created for each new
Employee object that is created in a Driver Class.
public class Employee{
private String lastname;
private String firstname;
...more code
}
//create
//c
eate t
two
o Employees
p oyees in a main
a
method:
et od:
Employee e1 = new Employee(Smith, Mary);
Employee e2 = new Employee(Jones, Sally);
4

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Keyword
Static is a keyword in Java that modifies the association of
an item to a class.
Contents of a class that are identified as static are
shared across all instances of the class.
This means all instances of the class share one copy
py of
the static items, and each have their own unique copies
of instance items, or non-static items.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Example
Consider initializing a static String with the value Oracle
called myCompany that represents the employer's
company. Each instance of Employee would still have
their unique instance variables, but would share the static
variable.
e2

e1

Instance Variable

Static Variable

Instance Variable

Mary Smith

Oracle

Sally Jones

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Variables
Static variables
Are also known as class variables.
Are
A declared
d l d with
ith th
the static
t ti kkeyword.
d
Have only one copy in memory, as opposed to instance
variables which hold one copy per instance
variables,
instance.
Are shared by object instances.
Hold the same value for all class instances.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Variables (cont.)


Public access for static variables:
If public, they can be modified directly by other classes.
Consider
C
id making
ki th
the variable
i bl a constant
t tb
by using
i th
the
keyword final to prevent modifications.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Programming Practices and Static Variables


Good programming practice initializes static variables with
values, rather than relying on the default null and 0
values.
The values initiallyy assigned
g
can be changed
g as long
g as
the class is active in JVM memory. Garbage collection
removes it from memory and the initial values assigned
will return the next time you use itit.

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Declaring a Static Variable


To declare a static variable, include the keyword static as
shown below.
Can be public
public, protected
protected, default
default, or private
private.
Should have assigned values, but automatically are
assigned
g
null values for class instances: an empty
p y string
g
or 0 for primitive numbers.
Should act as constants with the final keyword when
they use a public,
public protected
protected, or default access
access.
public class Nesting {
// Declare public static variable.
public static final int MODEL_NUM = 883;
...
}
10

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Changes to a Static Variable


Static variables that are not final can be read or assigned
new values by using the optional keyword this in instance
methods.
Changes by instance methods are changed for all
instances.
A change to a static variable may indicate that the class
should be limited to only one object. This is known as
the Singleton pattern
pattern.
...
private static String myCompany = Oracle;
public void setMyCompany(String s) {
this.mycompany = s;
}
...
11

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Variable Example


Create a class called Turtle that contains a variable
named food. This variable is static since all of our turtles
eat the same food. The Turtle class will have one more
variable named age. Since each turtle is a different age, it
is best to make this variable a private instance variable
rather than a static one
one.
public class Turtle {
public static String food = "Turtle Food";
private int age;
age
public Turtle(int age){
this.age = age;
}
}

12

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Accessing Static Variables


Instance variables require an instance of the class to exist
before access is possible.
public class Turtle {
public static String food = "Turtle Feed";
private int age;
...
}

You can access static variables without creating an


instance of the class. In a main method, this statement
would print out the variable food without any instance
reference.
System out println(I
System.out.println(
I feed + Turtle.food
Turtle food + to
to all of my turtles!);
turtles! );

13

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Notation to Access Static Variables


Generally, static variables are accessed by the notation:
ClassName.variableName

14

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Modifier and Methods


Static or class methods exist once and are shared by all
class instances.
May be used by other class methods or instance
methods based on their access modifier.
Cannot access non-static, or instance, variables. Static
methods can only access static variables.
Cannot access non-static, or instance, methods. Static
methods can only access other static methods
methods.
Can be redefined in subclasses.
Can be public
public, protected
protected, default
default, or private
private.
15

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Modifier and Methods


There are differences between calling an instance method
versus a class (static) method.
For example,
example you must first create an instance and then
use a dot notation to call an instance method; whereas,
the class name, a dot notation, and static method name
calls a static method.

16

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Modifier and Methods (cont.)


The static method provides a wrapper to construct an
instance of a class.
When the class has a private access constructor
constructor, a static
method is one of two approaches to creating an instance
of the class.

17

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Turtle Class Example


The Turtle class has a static variable that identifies the
number of tanks we have available (numTanks) and an
instance variable (tankNum) that tells us which tank the
Turtle is in.
public class Turtle {
public static String food = "Turtle Feed";
tankNum variable
public
bli int
i
age;
public int tankNum;
public static int numTanks = 3;
public Turtle(int age){
numTanks variable
this.age = age;
tankNum = (int)((Math.random()
(int)((Math random()*numTanks)+1);
numTanks)+1);
}
public void swim(){//implementation}
public int getAge(){return age;}
public int getTankOfResidence(){return tankNum;}
public static String fishTank() {return "I have " + numTanks + "
fish tanks.";
}
}
18

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Methods in Turtle Class Example


Review the methods in the Turtle class.
public class Turtle {
public static String food = "Turtle Feed";
swim()
() is a instance method.
public
bli int
i
age;
Although each turtle can
public int tankNum;
swim, the turtles may swim
public static int numTanks = 3;
public Turtle(int age){
differently depending on
this.age = age;
g
tankNum = (int)((Math.random()
(int)((Math random()*numTanks)+1);
numTanks)+1); their age.
}
public void swim(){//implementation}
public int getAge(){return age;}
public int getTankOfResidence(){return tankNum;}
public static String fishTank() {return "I have " + numTanks + "
fish tanks.";
getAge() and
}
getTankOfResidence() are
}

fishTank()
() is a static method
and it accesses a static variable
(numTanks).
19

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

instance, non-static, methods


because they access non-static
non static
variables. Static methods
cannot access non-static items.

Recursion, the Static Modifier, and Nested Classes

Creating Class Instances Using Static Methods


Another use of static methods is for creating class
instances when the class constructor access is private,
and the method is part of the same class.
This is p
possible because the static method is p
publicly
y
accessible with private access to the class.
...
private Nesting() {implementation}
...
public static Nesting getInstance() {
Nesting nesting = new Nesting();
return nesting; }
...
// Instantiate a private class with a method.
Nesting n1 = Nesting.getInstance();
...
20

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Modifier and Classes


Static or nested classes:
Can exist as nested classes.
Cannot
C
t exist
i t as independent
i d
d t classes.
l
A nested class is a class that is created inside another a class.

21

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Nested Classes


Static classes are implemented inside other classes, and
the other classes are known as container classes.
Can extend the behavior of the container class
class.
Can be overloaded like ordinary constructors.
The super() method call calls the parent class in a class
hierarchy. The static nested class can extend the behavior
of the containing class.

22

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Nested Classes (cont.)


The static nested class also provides the means for
instantiating a containing class when it's constructor is
configured with private access.
This is the second wayy to instantiate a class that has a
restricted or private access qualifier for its class
constructors.

23

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Static Nested Classes Example


public class Space {
//Space class variables
public static class Planet{
//planet class variables and constructors
public Planet() {...implementation...}
public Planet(String name, int size)
{...implementation...}
}
//more space class implementation
}

24

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Understanding Recursion
A recursive program is one that calls itself one or more
times with each execution until it satisfies the base case
arguments, then discontinues calling itself. It contains:
A base case: A segment of code that tells the program
when to stop calling itself and return a value or void.
A recursive case: A call out to another copy of itself.
A pattern of convergence: The process of working
backward through a problem's data set
set.

25

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Understanding Recursion (cont.)


The types of recursion are:
Linear: Only one call to itself in the recursive case.
Useful and frequently used
used.

Non-Linear: Two or more calls to itself in the recursive


case.
Used less frequently because of its impact on system,
specifically JVM memory.

26

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Understanding Recursion (cont.)


The base case means the program does not need to
recursively call itself any more. It returns the default value
(or does nothing) at the bottom most activity.
The recursive case occurs when the p
program
g
cannot
resolve the problem without a recursive call to itself.
Convergence means that you recursively call the method
until you reach the base case, and then you return values
or go bac
o
back up the
e cchain
a to
o the
eo
original
g a p
program
og a u
unit.
27

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Recursion Process
Recursion looks backward through a chain of events,
while traditional loops look forward through events.
Recursion works backward through convergence on a
base case, where the base case occurs when yyou are
back to the beginning.

28

Forward Thinking:
Process of adding a
number to itself.

Backward Thinking:
Process of subtracting a
number from itself.

Given: t1 = 5
Then: t(n+1)
(
) = tn + 5
Sequence: 5, 10, 15, ...

Given: t1 = 5
Then: tn = t(n-1)
( ) + 5
Sequence: 15, 10, 5

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Forward and Recursive Sequences


Forward Thinking (Loop)
public static double forward(double d) {
// Declare local variables.
double n = 5;
d bl r = 0;
double
// Add n to r, d times.
for (double i = 0; I < d; i++) {
r += n;
}
return r;
}

Backward Thinking (Recursion)


public static double backward(double d) {
// Declare local variable.
double n = 5;
if (d <= 1)
//base case
return n;
else
return backward(d - 1) +
n
n;
}
}
29

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Forward Sequence Explained


The variable r in the forward thinking program is the
result variable.
It is defined initially and incremented with each iteration
through the loop.
This type
yp of variable is essential when we navigate
g
forward without recursion.

30

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Recursive Sequence Explained


There is no variable r in the recursive example because
it's not required.
The return result from each recursive method call
passes back the solution, the version of the method that
called it increments and returns the result to the prior
level.
This continues until you reach the top most method call.
In a sense
sense, the return value of the method call in
conjunction with the recursive calling statement
manages r (the result) value without explicit declaration
or management.
31

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Tracing Through Linear Recursion


Trace through this recursive example using the backwards
thinking process. Call recur(4) and keep track of n with
each new call.
public static int recur(int n){
//base case
if (n <
<= 1) {
return 1;
} else {
//recursive case
return 3 * recur(n - 1);
}
}

32

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Tracing Through Linear Recursion (cont.)


Initially, n=4. Since n>1, there is another call made to
recur. This means the return value of recur(4) will be
equivalent to 3*recur(3).
3 recur(3). When we follow through recur(3),
we see the return value will be equal to 3*recur(2). This
pattern is continued until the base case is reached.
public static int recur(int n){
//base case
if (n <= 1) {
return 1;
;
} else {
//recursive case
return 3 * recur(n - 1);
}
}

33

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Keeping Track of Trace


Keeping track of the trace through in a table can aid in
retrieving the final result of the original call, recur(4).
The table shows step by step what is being called and
what the return value of each recursive call is.
Recursion requires
q
backwards thinking.
g Once a value
given by the base case is reached, fill in the values for
the previous calls.

34

Call

Results

recur(4)

3*recur(3)

recur(3)

3*recur(2)

recur(2)

3*recur(1)

recur(1)

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Replace Calls with Actual Values


The returned value for recur(1) is 1. With this information,
replace the call of recur(1) with 1, which gives a value of 3
for a call of recur(2).
Replace the call of recur(2) with its actual value.
Continue this p
pattern to find the final value of what is
returned when recur(4) is called, which is 27.

35

Call

Results

Actual Value

recur(4)

3*recur(3)

3*(3*(3*1)) = 27

recur(3)

3*recur(2)

3*(3*1) = 9

recur(2)

3*recur(1)

3*1 = 3

recur(1)

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Linear Recursion Factorial Problem


The following factorial problem:
Calls one copy of itself.
Calls
C ll ititself
lf until
til th
the b
base case.
Returns values from the lowest recursive call to original
call.
call
public static double factorial(double d) {
// Sort elements by title case.
case
if (d <= 1) {
return 1;
} else {
return d * factorial(d - 1);
}
}
36

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Demonstration of Linear Recursion Factorial


Problem
Assuming the subscript (zero-based numbering) is the
number of calls to the recursive function, where zero is the
first call:
Calls to the method: do = 5, d1 = 4, d2 = 3, d3 = 2, d4 = 1
It returns: 5 * ((4 * ((3 * ((2 * (1))))
( )))) or 120

37

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Non-linear Recursion Fibonacci Problem


The following Fibonacci problem:
Calls two or more copies of itself.
Calls
C ll fifirstt copy until
til th
the b
base case, th
then second
d copy.
Returns values from the lowest recursive call to original
call for each series of calls.
calls
public static double fibonacci(double d) {
// Sort elements by title case.
if (d < 2) {
return d;
} else {
return fibonacci(d - 1) + fibonacci(d - 2);
}
}

38

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Tracing Through Non-Linear Recursion


Tracing through a non-linear recursive method is slightly
more complex than linear recursive methods.
Although the concept of backward thinking is the same
same,
it may be difficult to use a chart for keeping track of your
calls.
Using a tree diagram is more practical for tracing this
type of recursion.

39

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Trace a Call to fibonacci(4)


Trace a call to fibonacci(4) to find out what the returned
value is. When you make a call where d = 4, you get this
result: fibonacci(4) = fibonacci(3) + fibonacci(2).
public static double fibonacci(double d) {
// Sort elements by title case.
if (d < 2) {
return d;
} else {
return fibonacci(d - 1) + fibonacci(d - 2);
}
}

fibonacci(4)
fibonacci(3)
40

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

fibonacci(2)

Recursion, the Static Modifier, and Nested Classes

Continue to Trace Through to Base Case


Continuing the trace through until you reach the base
case for all branches, which will give you a tree that looks
like this:
fibonacci(4)
fibonacci(3)
fibonacci(2)

fibonacci(1) + fibonacci(0)
1
41

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

fibonacci(2)

fibonacci(1)

fibonacci(1)

fibonacci(0)
1

Recursion, the Static Modifier, and Nested Classes

Continue to Trace Through to Base Case


(cont.)
The new tree looks like this:
fibonacci(4)
fib
fibonacci(3)
i(3)
fibonacci(2)
1

fib
fibonacci(2)
i(2)
1

Since fibonacci(2) = 1+1 = 2,


2 change it in the tree:
fibonacci(4)
fibonacci(3)
2
42

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

+
1

Recursion, the Static Modifier, and Nested Classes

Fibonacci Problem Conclusion


Next, replace fibonacci(3) with it's value (2+1 = 3).
fibonacci(4)
3

Finally, replace fibonacci(4) with its return value (3+2=5)


Finally
(3+2=5).
The conclusion is that fibonacci(4) = 5.

43

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Recursion Pros and Cons


Pros:
Once understood, often more intuitive.
Simpler,
Si l more elegant
l
t code.
d
Cons:
Uses more function calls.
Can cause performance issues
issues.
Uses more memory.

44

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Recursion Pros and Cons (cont.)


Even if you do not use recursion in your programs, you
still need to understand it since other programmers code
may use recursion.

45

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Terminology
Key terms used in this lesson included:
Base case
Class
Cl
method
th d
Class variable
Convergence
Inner class
Linear recursion
Nested class

46

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Terminology
Key terms used in this lesson included:
Non-linear recursion
Recursion
R
i
Recursive case
Static modifier
Static method
Static nested class
Static variable

47

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Summary
In this lesson, you should have learned how to:
Create static variables
Use
U static
t ti variables
i bl
Create static methods
Use static methods
Create static classes
Use static classes

48

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Summary
In this lesson, you should have learned how to:
Create linear recursive methods
Create
C t non-linear
li
recursive
i methods
th d
Compare the pros and cons of recursion

49

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

Recursion, the Static Modifier, and Nested Classes

Practice
The exercises for this lesson cover the following topics:
Implementing and accessing static variables
Implementing
I l
ti and
d using
i static
t ti methods
th d
Implementing and using static nested classes

50

Copyright 2013, Oracle and/or its affiliates. All rights


reserved.

You might also like