Week 7 CS 302 Jim Williams
This Week Lab: Static Methods P2: Milestone 1, Partners due Thursday P1 Feedback regrade requests Exam 1 results review, discuss
Lecture More methods multiple files Constants static memory area Debugging exam review
What is print out? two one two main main two one two two two one main one two two main static void one() { System.out.print( "one "); } static void two(int num) { System.out.print("two "); one(); public static void main( String []args) { two( 3); System.out.print("main "); try it.
What do a and b have in common? public static void main(String []args) { mA(); mB(); } static void mA() { int a = 10; static void mB() { int b; System.out.println( b); may be the exact same memory location looking at b will reveal a (unintentially) nothing Error A is the best answer. This example is typically discussed with a memory diagram intended to illustrate how local variables are allocated on the stack. Local variables are a part of the stack frame that are allocated when a method is called and discarded when the method ends. Since mA() has 1 int variable allocated (pushed on stack) and then discarded (popped off stack) then mB() can reuse that same memory area. Thinking through this possibility is intended to help develop a deep understanding of local variables.
Constants
static Memory area
What is the value of num? num: 10 Stuff.num: 6 Stuff.num: 10 class Stuff { final static int MAX_VALUE = 10; //allowed static int num = 6; //NOT allowed in P2 static void change( int n) { num = n + 1; } public static void main( String [] args) { int num = MAX_VALUE; change( num); System.out.println("num:" + num); System.out.println("Stuff.num:" + Stuff.num); num: 10 Stuff.num: 6 Stuff.num: 10 Stuff.num: 11 error
What are values of x and y? static int x; static int y = 2; static int methodA( int y) { x = y + 1; return x + y; } public static void main(String []args) { int x = 5; y = methodA( x); System.out.println("x="+x+ " y="+y); x=5 y=11 x=3 y=2 x=5 y=2 x=3 y=11
Instance methods
What is print out? ling Future lin error String str = "Falling Off a Cliff " + "by Eileen Dover"; System.out.println( str.substring(3,6)); String str2 = "The Future of Robotics " + " by Cy Borg and Anne Droid"; System.out.println( str2.substring( str2.indexOf('e') + 1, str2.indexOf('o')).trim()); try it Strings courtesy of Boy Scouts
What kind of methods? max: class nextInt: instance Math.max( 10, 20); max: instance nextInt: class Math.max( 10, 20); Random randGen = new Random(); randGen.nextInt( 5); class methods (static) instance methods (non-static) A is the best answer
Instance vs. Class (static) Methods method definition has “static” modifier use name of class when calling Math.max( 10, 20); Instance (non-static) Methods method definition does Not have “static” modifier use instance of class when calling Random randGen = new Random(); randGen.nextInt( 5);
Where is memory allocated? name: heap new String("fido"): heap name: stack new String("fido"): stack public static void main( String []args) { String name; new String("fido"); name = new String("spot"); } B is the best answer A, C and D are not true
Debugging with Print statements See what is going on. Divide and conquer. import java.util.Scanner; public class Factorial { public static int factorial(int n) { int result = 1; while( n-- > 0) { result *= n; } return result; public static void main( String []args) { Scanner scnr = new Scanner( System.in); System.out.print("Find factorial of what number? "); int num = scnr.nextInt(); int factorial = factorial( num); System.out.println( "The factorial of " + num + " is " + factorial); scnr.close(); //////////////////////////////////////////////////////////////////////////////// // Title: PascalTriangle // Files: PascalTriangle.java // // Author: Zhicheng Gu // Email: zhichenggu@cs.wisc.edu /////////////////////////////// 80 COLUMNS WIDE /////////////////////////////// import java.util.Arrays; /** * This class is used to print first five rows of Pascal's Triangle. https://en.wikipedia.org/wiki/Pascal%27s_triangle * The output of this class(without bugs) should be: * * 1 * 1 1 * 1 2 1 * 1 3 3 1 * 1 4 6 4 1 * * @author Zhicheng Gu * */ public class PascalTriangle { // The number of rows we want to print. private static final int MAX_LEVEL = 5; /** * * Main class will first initialize and print 'nums' array, * which contains first row of Pascal's Triangle. * Then it will get and print numbers of next level iteratively. * * @param args : not used. */ public static void main(String[] args) { // Array stores numbers on each level. // Numbers on tree levels are mapping to the smallest array indexes. // For example, for the first three rows, // nums should be: [1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0]. int[] nums = new int[MAX_LEVEL]; nums[0] = 1; // Get and print the numbers on each level. for (int level = 1; level <= MAX_LEVEL; level++) { if (level > 1) { getNextLevel(nums, level); } // TODO: Part 1. Use print to help you debug. // This print statement helps determine whether the problem is in // getNextLevel or printOneLevel. // System.out.println("Main method, nums: " + Arrays.toString(nums)); printOneLevel(nums, level); } } /** * This method is used to print one level of Pascal's Triangle. * * @param nums : Array stores numbers. * @param level : The current level. */ private static void printOneLevel(int[] nums, int level) { // Print the spaces at the beginning of each line. for (int i = 0; i < MAX_LEVEL - level; i++) { System.out.print(' '); } for (int i = 0; i < level; i ++) { System.out.print(nums[i] + " "); } System.out.println(); } /** * This method is used to calculate numbers on next level * based on current level. * * @param nums : Array stores numbers. * @param nextLevel : The number of next level. */ private static void getNextLevel(int[] nums, int nextLevel) { int[] nextNums = new int[MAX_LEVEL]; // Array stores numbers on next level. nextNums[0] = nums[0]; // Each number at position i on the next level equals to the sum of // number at position i and i - 1 on the current level, // except the first one and the last one. for (int i = 1; i < nextLevel - 1; i++) { nextNums[i] = nums[i - 1] + nums[i]; } nextNums[nextLevel - 1] = nums[nextLevel - 2]; // TODO: Part 2. Use print to help you debug. // With the print statement in main we figured out the problem must be in this method. // This print statement is to see if this method is working correctly to this point. // System.out.println("getNextLevel method, nextNums: " + Arrays.toString(nextNums)); nums = nextNums; } }
Recall Fibonacci Sequence 1 1 2 3 5 8 13 21 … Each is the sum of the previous 2. https://en.wikipedia.org/wiki/Fibonacci_number
Iterative solution public static void main(String[] args) { int n = 10; int [] fib = new int[n]; fib[0] = 1; fib[1] = 1; for (int i = 2; i < n; i++) { fib[i] = fib[i-1] + fib[i-2]; } System.out.println("fib "+n+"= " + fib[n-1]); {
How many times is fib method called? 1 3 9 Error static int fib(int num) { if ( num <= 1) return 1; else return fib( num -1) + fib( num -2); } public static void main(String[] args) { System.out.println("fibonacci 4: " + fib(4)); try it.