Stanley Kurbrick's The Shining
Jack Nicholson explains the importance of the contract he has signed with his employer to watch over the Overlook Hotel until May the First in the classic film The Shining directed by Stanley Kubrick. Read about The Shining on IMDB and give yourself a Kubrick break during your practice.

Method Fundamentals and Switched blocks

CIT111: Java - Chunk 2, Module 1 [Last updated on 9 March 2018]

Start Here: Jump to a section

This module was engineered to be worked through sequentially: from top to bottom

wb_incandescentCore idea: What is a method?
check_boxLearning Objectives
bookModule resources & links
webSetup your workspace

movieMethod overview video
extensionCore Concept 1: Writing and calling simple method
motorcycleExercise 1: Fleshing out

extensionCore Concept 2: Switch-controlled blocks
motorcycleExercise 1.5: Scope practice
motorcycleExercise 2: Adding a switch to

extensionCore Concept 3: Passing data into methods
movieLive lesson video: Writing methods with inputs
movieLive lesson video: Calling methods with inputs
movieLive lesson video: The value of method-based coding

motorcycleExercise 3: Writing methods that require input parameters
motorcycleExercise 4: Writing methods that take TWO input parameters
motorcycleExercise 5: Calling displayPurchasableNumber with user-inputted data
movieLive lesson video: Adding user input to our class

buildMini Project: MysteryDoor machine
movieModule project overview video and Q&A with students

wb_incandescentConcept in Brief: Method Fundamentals

Methods are named blocks of code that do a single job or task. They are always named to convey the action that they perform: such as nextInt() which we've seen on our Scanner objects. When we call (i.e. invoke that method's name in a program) nextInt(), the Scanner comes to life and grabs an integer from the keyboard and passes it into our program. That's its one and only function in life: read integers. Method names always start with a lowercase letter.

calling the nextInt() method on a Scanner Object

The method we are most familiar with so far, the main(String[] args) method, has an unfortunate name since it's not an action. It does, however, do one important job: it sits there as the front door--or entryway--to our programs. It is also unusual because we never write code that calls main method. But! We can (and will often) call other methods from main, like this method named printSpecialStatement() which we write in the same Class as main, but right below main:

sample java code that implements a simple method

STOP and transfer the code above into a class in NetBeans called inside a new package called week6. Pause and study the connections between the code above and its output below. You'll then have the core concept down. We'll build on this.

sample java code that implements a simple method

arrow_upward back up to contents

check_boxLearning Objectives

  1. Call and write simple methods that take no input data and return nothing to the caller
  2. Build switch-controlled blocks and use that structure to call different methods in the same class
  3. Call and write medium complexity methods that require data input and return nothing to the caller
  4. Refactor (re-organize) code to use named methods instead of repeated code

arrow_upward back up to contents

bookExternal Resources

Oracle online tutorial on methods is a solid resource with sample code.

Consider the textbook, but perhaps wait until next module

bookYou may choose to study about methods Java: A Beginner's Guide (6th edition): Chapter 4 pages 103-123. If you are feeling full of new concepts, wait on the text until next week where we'll flesh out the whole concept of Class structure, which Chapter 4 opens with.

arrow_upward back up to contents

Module Hamburger Guide

Used only in Fall 2018 in-person sections

Language Structure 1 (LS1) Hamburger (*.pdf)

Learning Core 3 Hamburger (open document text *.odt)

back to top

webSet up your workspace

  1. Create a new package called week6 non bold
  2. Create the following classes inside your new package. You'll code them up in this module

arrow_upward back up to contents

extensionCore Concept 1: Writing and calling simple method

Core Concept overview video

This is an edited version of the introduction to methods that I delivered at West Hills on Monday. Enjoy!

Written procedure:

Let's dissect the SimpleMethod class we wrote in the brief overview section above. Here's the code again:

sample java code that implements a simple method

We can model how the methods in this class relate to another in a figure that traces the order of execution of the code in this program. Just like you were encouraged to do above: study this flow diagram carefully to determine how each step in the diagram is coded in Java. Tinker with your code to solidify your understanding.

Core Module Idea: Flow of execution during a method call

execution flow for a simple method call

The first line of a method is called its declaration which contains the method's name and several other important components that tell the compiler how the method should behave in our program. Study each keyword explanation carefully.

A simple method, dissected:

a method's declaration and structure dissected

Note that methods are stacked, not nested. Meaning, we'll always close a method with its } before we ever declare and write another method. Additionally, the order of the terms in the method declaration must conform to the specification above: public/private must always come before static, etc.

arrow_upward back up to contents

motorcycleExercise 1: Adding a method to SimpleMethod

Exercise type: Core Concept Practice

Study the following specification to write a new method in our SimpleMethod class:

highlightDesign Specification: Add a method to SimpleMethod called generateBigNumber(). Declare it to be public and static. It's return type is void. It takes no input parameters.

Inside that method, use the following code snippet to generate and print a very large number.

flow chart for java if and while statements

You'll need to import two Java library classes after your package declaration and before you start your class. NOTE: Your package and class names are different from these, since yours is not the Key code!

flow chart for java if and while statements

Call your new method from main in between the two calls to printStatement().

Call your new method a second time: from inside printStatement() itself.

Include calls to System.out.println() as needed to demonstrate the code flow for yourself.

Test your code to verify your method is executed exactly THREE times.

Studying output is a core way to learn to code to a specification. Code some, check the output, tweak the code, check the output, etc.

Sample program output that meets the exercise specification above

flow chart for java if and while statements

When you have given it a good shot...

The button below displays sample source code that meets the specification. Remember, this activity is not about reproducing my code, but generating your own. Only use this reference after you've tinkered and consulted your resources (like the diagrams above).

arrow_upward back up to contents

extensionExercise 1.5: Variable scope practice

A variable's scope describes the chunks of code that are allowed to access (read or write) its contents. In our exercise, we're only concerned with class scope and method scope: variables that are available to all code in the class, and variables that exist only while a single method is executed.

Download exercise worksheet [ as a pdf (printing only) | open document text (editable)]

Follow these steps to explore variable scope

  1. Inside your package dedicated to methods, create a class called ScopePractice
  2. Access our buggy code for the ScopePractice class on GitHub and transfer the code into your class. Be careful to only move the correct chunks of code, depending on whether or not you delete all of your skeleton code in NetBeans or not.
  3. This code has bugs: three big ones. Carefully read and study the code and make note on your worksheet of exactly what the three error messages are on each of our three bugs. Work with those around you to fix the issues. In the case of one
  4. One the bugs are fixed, execute the program, and carefully trace where EACH line of output comes from in the source code
  5. Now study the screen shot of the desired output below this list of instructions. Tinker with your code such that your output looks exactly like the sample. NOTE: you may only make THREE method calls in the main method. No more! No less!
  6. When you're all set, compute the statistics asked for on the bottom of your worksheet.
correct output

If you get stumped, here's the key

arrow_upward back up to contents

extensionCore Concept 2: switch-controlled blocks

switch Syntax

By structuring our coded into methods with sensible names we create modular programs which are easier to maintain and use as building blocks for larger projects. With methods in our toolkit, this core concept introduces a new control structure that makes chained if blocks less error-prone.

A close cousin of the if() controlled block is the switch control structure which we can use to run lines of code based on the comparison of a pair of values.

Basic switch statements

The switch system looks for a match between the value of SELCTOR and the value next to one of the case statements. In our case, 23 matches none of the cases, so the condition on case default will be executed, and the phrase Default case will be displayed;

bookswitch statements in Java: A Beginner's Guide (6th edition): The Schildt text has good coverage of switch statements from chapter 4: program control. 6th edition pages are: 69-75. In other editions, just check the TOC for "switch".

Get this code to compile and now try changing the value of SELECTOR to a value that matches one of the switch's cases, such as the integer 1 or 2 or 78.

The break; statement is back!

Tinker with this code by commenting out the break; statements on each line in the code we just wrote. Run the program. Note that break; works in switch systems just like in a while loop: as soon as a break; is seen by the compiler, execution jumps directly outside the enclosing loop or switch block, and in this case, we're working with switch. Without a break;, the code in the matching case is executed and then execution continues downward through all code in all following cases until the switch and or a break; is encountered.

Switches look strange in Java

Given the way we declare blocks for methods, classes, if() statements, etc., you might have expected the following curly brace syntax to be required in a switch system:

switch statements don't require block notation in the cases

The { and } however are not required to make a case block. We can program several lines of code in each case, and the compiler will assume that particular case continues until it finds a new case or a closing curly brace for the entire switch block. Note: the compiler allows you to declare unnamed blocks like in this code snippet above anywhere you want--so if you want consistency, you could put them in, but other Java coders will pause, curl their noses, and wonder: "Why the unnecessary curly braces?"

switch variations

Review the book chapter on switch statements: you'll learn that you can use variables of type char, short, byte, or an enumeration to control a switch block. You cannot compare using floats or doubles (numbers with decimal places) since their precision, by definition, is flexible, which is not great for using to find matching values to trigger a case. We can also use String values in switch blocks, and this is a new edition to Java SE 7

switch statements aren't really special

switch structures are not implementing some special logic or operation--they're just a convenient way to code chained if-else blocks. "Prove it, you say!" Okay, lets! Try refactoring (changing) the code in BasicSwitch that preserves exactly the same functionality but uses only if and else structures.

Give this little mini-task a try and check the reference code below if you get stuck.

arrow_upward back up to contents

motorcycleExercise 2: Building a switch control mechanism into

Exercise type: Core Concept Practice

In this exercise, we'll build a switch mechanism into the SimpleMethod program we've been working on in this module. Combined with user input functionality, we'll be able to create a program in which the user decides which of several possible methods to run. This is good programming practice since switch cases are not meant to contain complicated code. Rather, the cases's body should be as short as possible, calling methods as needed so the code is readable.

Let's see a snip of how we might combine method calls and switch control systems:

we can call methods from inside switch case statements

Study the following output and the flow chart to write code in your class called BasicSwitchWithMethodCalls.

we can call methods from inside switch case statements

highlightDesign Notes: on GitHub. Remember, please write your own code and only use the samples as a guide. If you copy directly from the key, please note this in your comments.

arrow_upward back up to contents

extensionCore Concept 3: Passing data into methods through parameters

Our tour of methods is just beginning. The next stop is adding data transmission from the calling method into the method we want to "do its thing". Let's start a new example to explore this concept that acts as a total purchase price calculator.

Follow along with real students!

The following segment is the recorded lesson when this core concept was introduced to our section at West Hills. It works through almost exactly what this core concept conveys. A good resource indeed.

Our first version of the program will consist of two methods: the standard main and a method of our own design called displayPriceWithTax. The job of main is to call displayPriceWithTax and during that call transfer the amount of the sale to the method so that value can be used in its computation.

Go ahead and code up our first method requiring input parameters using the following code snippet as a guide.

source code for passing parameter values down to methods

When we're done with the writing the method, we're ready to call it up. When functioning properly, the program's output is simple: main tells us the price amount that's about to be passed into our calculation method. The next line is printed inside the method displayPriceWithTax after it has added the tax to the price it was given by the calling method (in this case, main called displayPriceWithTax).

source code for passing parameter values down to methods

Calling methods with parameter values passed in

Companion video for calling methods with parameters

Study the source code carefully and read about its features. See if you can trace the flow of the ITEM_PRICE through the program and internalize how this code varies from our simple example above of methods that did not transfer data to the methods it called.

source code for passing parameter values down to methods

Flowchart of parameter movement from caller to method body

Grab a cup of tea and digest this diagram. If you digest nothing else this entire module, this is the figure for you.

source code for passing parameter values down to methods

mode_editCore Concept Explained: Method calls with parameters

In programming speak, we would describe what we're learning as follows: A method can specify one or more pieces of data required to carry out its tasks. These input values are called method parameters and are declared as typed variables when the method is written.

Soon to be made: Diagram of method declaration with parameters

When a method is called, any required input parameters must be supplied. We call the values passed into a method when arguments to that method. (This is a horribly confusing term that has nothing logically to do with a fight.) Java's data typing mechanism will require the values passed into a method to match the types specified in the method declaration.

Methods isolate responsibility of code

This video clip tinkers with our scanner-based version of the PurchaseCalculator and discusses four good reasons to write in methods instead of jamming all your code into main():

The job of displayPriceWithTax is to implement the simple but important math of adding a dollar value to an initial price based on the current tax rate (that's hard-coded into the method). By separating the mathematics of adding tax to a purchase price into its descriptively-named method, we can not only read code more clearly back in main but we have isolated program logic in a testable block of code.

Advantage 1: Ease of Debugging

Using methods to isolate the responsibility of blocks of code allows for easier debugging and more maintainability of the program. For example, in terms of debugging, if we are writing a more complex program that does all sorts of transaction-related operations, if we notice an error in the tax rate applied, we can jump to method whose job is to do that calculation and start debugging there.

Advantage 2: Maintainability

From a maintainability perspective, methods also earn their keep: if we ever needed to adjust the tax calculation (maybe a law changes and tax rates are graduated along a purchase amount), we'd know exactly where to make the change and could test that change without interfering with other code. Methods really are gloriously handy structures. Make good friends now and the relationship will bear fruit for your entire programming endeavor.

arrow_upward back up to contents

motorcycleExercise 3: Writing methods requiring input parameters

Exercise type: Core Concept Practice

Practice the process of writing methods with input parameters and calling those methods from a different method. Let's start by writing a third method for our PurchaseCalculator class with the name computePriceAfterDiscount(double price, double discount) which will take in a double value interpreted to be the before discount price, and a second double value interpreted to be the discount percent as a decimal.

Method declaration requiring two input parameters

Wait, what's all that funny looking comment stuff?

We're usually not the only ones who want to call our methods, so Java as a built-in code documentation system called JavaDoc which generates pretty HTML code for display in a web browser which describes what each class and method does and how to use it. For example, I used a program called javadoc built into each one of our Java Development Kits to generate this summary of our method computePriceAfterDiscount:

Method declaration requiring two input parameters

Now go back and re-read the blue text comments above the method body in the code snip above. Look to see how the @ tags and such turn into HTML that's nicely formatted.

Pretty slick, eh? You're invited to use this comment style as soon as you feel able to do so. You can read all about JavaDoc comments in the JavaDoc documentation (yes, documentation on writing documentation....welcome to programming!)

Now bring our method to life by calling it!

Now that we've written our method that takes input parameters, we're ready to call that method from main, giving it the information it requires, in our case, a double value. The following clip from our in-person class should be a great guide.

Specification 3.1: Wire up your computePriceAfterDiscount to be called into action by a line of code in main. To do so, create a double type variable called discount in main and initialize its value to 0.15 for a 15 percent discount. THEN, when you call computePriceAfterDiscount, pass in the value of both ITEM_PRICE and discount into the method by putting them in the parentheses following the method name, separated by a comma.

Sample output that meets specification 3.1

Method declaration requiring two input parameters

Check your work for Specification 3.1

arrow_upward back up to contents

motorcycleExercise 4: Writing methods that take TWO input parameters

Add a fourth method to our PurchaseCalculator!

Let's keep building our PurchaseCalculator class by adding a method that takes in the item price and a spending limit and tells the user how many of that item can be purchased. Code up the method with the following Specification 3.2:

Specification 3.2: Write a method called displayPurchasableNumber that takes in two input parameters: a double-type value stored in a variable price and a double-type value stored in a variable called limit. This method should use the following line of code to calculate the maximum whole number of units that can be purchased within the supplied spending limit.

int numPurchasable = (int) Math.floor(limit / price);

After the maximum whole number of units is calculated, print out the result to the console along with a print out of what limit was supplied. (See sample output)

Check your work

Click the following button to check the source code of the displayPurchasableNumber method. Please only check after you've given it a good go.

Note that we'll write the call to this new method in the next exercise.

arrow_upward back up to contents

motorcycleExercise 5: Calling displayPurchasableNumber with user-inputted data

In-Class video example of adding Scanner input

The following video clip shows how we can add user input into our PurchaseCalculator class. Note that the way the Scanner is added to the program in this video is slightly different from the specification in this exercise--that's good! You can learn to adapt.

Finally, let's write some code in main(String[] args) that calls up displayPurchasableNumber. Better yet, let's allow the user to input their purchase limit into the program and send this user-entered data down to the method. Code to the following specification:

Specification 3.3: Write code in main to call up displayPurchasableNumber. In order to supply the method with the two double-type arguments it requires, create a Scanner object and use it to read in a double value from the user representing their spending limit. Pass the value the user enters down to the method.

Review the following screen shot of a program's output that meets this specification.

Method 	declaration requiring two input parameters

View completed code for PurchaseCalculator on GitHub on GitHub. Remember, please write your own code and only use the samples as a guide. If you copy directly from the key, please note this in your comments.

Extension ideas!

If you're open to some more Java, the sky's the limit with this PurchaseCalculator class. Use the following suggestions to embellish your program:

arrow_upward back up to contents

buildModule Mini-Project MysteryDoors

Exercise type: Culminating Activity

Project overview video and techie Q&A

This clip from class introduces our module project and shows off some cool work of other students. The end of the video even features some "random" questions and answers relating to programming in general.

Synthesize this module's core concepts by creating a program whose structure consists of a main method and three methods you write, each one representing the contents behind a "door" chosen by the user. The contents of the doors in this program is boring, so get creative!

flow chart for java if and while statements

highlightMysteryDoor Program Specification:

Requirement 1: Write a program in a descriptively named class that presents the user with a menu of doors to open. (You may replace doors with any other object you'd like to be creative.) Use a switch statement to process the choice from the user. The switch's case statements should only contain calls to one or more methods you've written. Avoid writing program functionality in case statements.

Requirement 2: Write three methods of your design that implement some interesting functionality, such as random number generation, user input processing, controlled looping behavior, etc. The method names should be action-oriented and descriptive. They will all be declared with public static void for now.

You might design a program in which the functionality of the three methods are somehow related but slightly different from one another.

Requirement 3: One of your methods should require an input parameter value of some sort from the calling method. This may mean that you need to gather some input from the user in main so you can pass it into one of your methods. For example, maybe a method you write calculates the cubed value of any input. Ask the user for a value to cube and pass that down to the method as a double or int type value.

Requirement 4: Comment your code--particularly, the comments before each of the methods you write. The comment should complete a sentence that starts with "The single job of this method is to...".

Submission steps:

  1. Complete your code and debugging process. Test it against the specifications above after re-reading them.
  2. Comment and clean up your code since we're sharing these are becoming part of your public coding portfolio. Add println() calls to help the user know what to do.
  3. Upload your code to your GitHub account.
  4. Make a detailed entry in our java project upload index spreadsheet, including capturing and pasting in a direct link to your source code file.

Extension ideas:

  1. Build in a while()-controlled block such that the user can repeatedly interact with your door choosing system. You'll want to use the do...while() flavor of the while() system which ensures that the body of the block runs at least once. You'll want this since one option might be to exit at which case your while looping condition can just escape the while() and end the program.
  2. Creatively refactor your code so that all of your methods require input parameters. Then chain a method or two together, and pass the input parameters through a method to a second method to see how tough your method-writing skills really are. I would imagine, for example, you could have a while() loop in one of your methods that computes a value over and over. This while() loop might actually call a fifth method you write that implements a computation, say, with the Pythagorean theorem or something cool like that.
  3. Write a method that interactively asks the user for some basic information. Each time the program loops back through your menu, redisplay the basic user information but don't ask them for their details again.

arrow_upwardback up to contents