RoboRIO

Overview: 
Wrap up the method unit with references to other sources of information on Java methods.
Objectives: 

View some different explorations of Java methods.

Content: 

We are going to wrap-up the unit on methods with several resources for you to view:

Here is a video about methods. This video is a good introduction to methods. However the definition of the static keyword in this video is incorrect. Please ignore the discussion of static for now as we will explore static later in this curriculum.

Here is a detailed discussion of methods. Here is another discussion (stop at "Constructors").

Navigation:

Overview: 
Explore what "overloading" is and how it is used with methods.
Objectives: 

Understand the "overloading" concept and how it applies to methods and how to use it.

Content: 

Remember that we mentioned that a method's name and parameter list are called the method's signature and this signature is how Java identifies methods. So it follows that while methods with a different name are definitely not the same method, methods with the same name and different parameter lists are also not the same method. This allows you to use different parameter lists to create variations of a method single name. This is called overloading. Here is an example of overloading:

The calling code can call square() with a double or an integer and the correct method for the parameter data type will be used. Here is an example showing varying the number of parameters:

Calling code can use either method but the second has the option to return the area in meters. Note that the second method reuses the first method so that the basic area computation is only defined in one place. In effect, the second method "adds to" or "overloads" the functionality of the first.

Here is this example in CodingGround. Add new methods to compute volume (with and without the meters option) if a height parameter is supplied. In your new methods, reuse the computeArea() method.

 

Navigation:

Overview: 
Explore how the code that calls a method can pass variables (data) to the method for the method to process.
Objectives: 

Understand passing parameters to methods from the code that calls the method and how this input makes methods much more general and useful.

Content: 

Parameters (also called arguments) are the way in which we can send data (variables or constants) to a method for it to act on. While there are cases where methods may not need parameters, parameters make methods especially useful. Parameters allow a method to produce a different result each time it is called depending on the input values supplied. Parameters are said to be "passed" to the method.

A method parameter-list consists of one or more parameters (separated by commas) specified between the method definition parenthesis. A parameter is defined by a data type and a name. The data type can be any Java data type (primitive or reference) and the name any name you wish. The name creates a method local variable used to access the parameter's value inside the method. Here is a simple example:

Here two integer parameters will be passed to the method computeArea() when it is called. The method uses these parameters to compute the result which is returned to the calling code. Calling this method might look like this:

The variable area will contain 100. The computeArea() method can be reused to compute any area, any number of times for any height and width values passed on the call. Using a method to compute the area is also handy if the way you compute the area changes. You only have to change the method, not all the places it is called, which is what you would have to do if you had coded the area computation everywhere you needed it.

Parameter lists can contain variables or literal values. Note that variable names used on the method call do not have to match the names on the parameter list but the data types must match. In the example above, the method uses the parameter names height and width, but the calling program passed a literal value and a variable called x. At the same time, the method cannot use the variable x, it must use the variable width. In other words, I will call computeArea() with the variable x, but in the computeArea() method that value will be known as width.

In Java, primitive parameters are passed to methods by copying the parameter values from the calling code into the methods placeholder variables. This means that changing a parameter inside the method does not change that variable in the calling code. In our example, if you changed the width variable in the computeArea() method, that would not change the variable x in the calling code. This scheme is called passing parameters by value. Passing reference variables (objects) as parameters follows this same scheme but has important differences to be aware of. We will discuss this in it's own lesson in Unit 8.

Here is the example in CodingGround. Add code to the computeArea() method in the example to change the value of the width variable before the computation. Add code to the main() method to show that the variable x is unaffected by your change to width.

Using your knowledge of the switch statement, add a new method that takes an integer parameter from 1-7 that represents the day of the week and return the name of that day. Call that new method from the main() method and print out the day name.

Remember the main method from the Hello World! example? Here is the main() method definition again:

Now we can see that the main() method has a parameter list, which consists of one parameter, an array of String values. We will discuss arrays later, but for now the args parameter is a list of options (also called arguments) that are passed to the main method by the JVM when the program is started.

 

Navigation:

Overview: 
Explore how data can be returned from a method to the code that called the method.
Objectives: 

Understand returning data from a method and how this construct is used to communicate results from a method to the code that called the method.

Content: 

While methods can perform their function without returning any data to the calling code, a common use of methods is to perform some process or computation and return a result to the caller. When a method does not return a value, the return data type is called void. An example of a method that would have no return value would be a motor’s setPower(x) function. When we use that function, we aren’t looking for the code to compute something and give us the result, but we are asking the method to make some change in the robot hardware’s current running state. Void sounds like a negative connotation, but it only indicates that a method does not give us a value back. 

When we do want to return a value, the data type in front of the method name defines what kind of data we will return. The statement we use inside a method to send a data value back to the calling code is return. Return stops method execution and returns the value specified on the return statement. The data type of the value on the return statement must match the data type specified on the method definition. Here is an example:

We would call that method like  this:

This would place 2 into variable z. Note that the method does not require an input (hence the parentheses are empty). It will always return an integer value of 2. The variable x is defined inside the method so it is only visible inside the method.

We could also do this:

That would place 7 into z.

If you are returning a value, all return statements in the method must return a value of the correct data type. If the return type is void, all return statements in the method must not have a value on them.

You can return all data types including reference types (objects). Here is an example using the String data type:

We would call that method like  this:

This would print "my string" on the screen twice.

Note that a method can be called any place a data value that has the same type as the method returns. In the second println() statement, the JVM will execute the method which returns a string and then that string is passed into the println() method which can accept a string input.

When working with objects, methods can alter the internal variables of the object thus changing the object's state. This is the most common case of a method that does not return data to the caller. In this case, the result of the method's actions is the altered state of the object. This will be discussed in more detail in the unit on objects.

Here is the example in CodingGround. Add a new method that returns a double value of 22.7. Then modify the main method to call your new method and print the returned result.

A robotics example of a return value is getting information about the hardware. For example, lets say a touch sensor has a method getTouch() that returns a boolean, false if not touching anything, true if touching something. We might write this code:

Here the  sensor.getTouch() method returns a boolean, which is then tested by the if statement. A robotics example of a method with no return is controlling the behavior of a motor:

The power level is set to zero in the motor object and the method takes care of sending that power level to the actual motor on the robot.

 

Navigation:

Overview: 
Explore the structure of methods and how they are defined.
Objectives: 

Understand the structure of methods, the method header and how to write methods.

Content: 

The form of a method is:

The components are:

  • modifiers control access to methods and other special effects on methods. Modifiers will be discussed later. For now just use the word public.
  • return-type defines the data type of the method's return value if any. If there is no return value, use the word void. At a basic level, a return value is what the function will give back to us when it’s done running. We will discuss return values in the next lesson.
  • name is the name of the method. It is case sensitive.
  • parameter-list is an optional comma separated list of data values to be passed from the calling code to the method for its internal use. These are the inputs to the function, like the x in f(x). If no parameters use empty parenthesis. Parameters will be discussed shortly.
  • exception-list is a list of possible errors (called exceptions) the method might generate. We will discuss exceptions in an advanced lesson.
  • statements is one or more variable definitions or statements that make up the body of the method, and determine what the method actually does.

The name and parameter list are used by the compiler to determine which method is which and the two together are called the method signature. When called, the statements inside a method's curly braces (the method body) are executed one after another until the end of the method body is reached. You can end method execution prior to the end of  the body with the return statement.

Variables defined inside a method (called local variables) can only be accessed in that method. Global variables, that is variables defined in the class that contains the method, are accessible in the method.

Methods are called by using the method signature (name and any parameters) in a statement.

Lets look at an example (ignore the static modifier and args parameter for now):

This program will print out "Hello World! 15" two times. The JVM will start the program by calling the main() method. The main method calls myMethod() twice. myMethod() calls myMethod2() passing in the value in variable x and gets back the result of the computation in myMethod2(). That result is then stored in x in myMethod(). This is a pretty simple example but shows how the processing in the methods myMethod() and myMethod2() are easily used by calling code. As we learn more about methods we will see how useful they can be and how they are the cornerstone of object based programming.

Here is this example in CodingGround. Modify the example to add a new method whose name is your first name. Have that method print out Hello followed by your name.
 
 

Navigation:

Overview: 
Explore the concept of a Method, why they exist and why we need them.
Objectives: 

Understand the general concept of a Method and the use cases for Methods.

Content: 

Methods are reusable code blocks that are only executed when called from another location in your program. Methods are also called functions or subroutines. For our purposes, these names mean same thing. In other languages, the names may mean something a bit different.

In math, the parallel to a method is a function, like f(x). The function f takes in an input, x, and does something to it and optionally returns a result. Let’s say we want to square a number and then take three away from it. In math, we would write f(x) = x*x - 3. Then, we can later say f(2), and since we have defined what the function f(x) is, a reader would know that f(2) will give us 1 (4-3). This allows us to re-use a process that we may want to repeat throughout our code.

Methods help reduce complexity by taking code blocks that repeat and writing them in one place and then calling the blocks whenever we need them.

Methods streamline code by allowing us to break a complex algorithm into smaller sections of code, each easier to understand, but callable as part of the overall algorithm. That is, we can write a more complicated function by putting together smaller, simpler functions that each do a simpler step.

Methods allow objects to contain executable code (as well as data) which can be called by users of those objects. This is the basis of APIs in Java. We will ignore the object aspects of methods for the moment, looking only at method basics. For now, know that methods are defined inside Java classes and that a method cannot contain another method. In our example program Hello World, the block of code titled main is a method.

 

Navigation:

Overview: 
Explore how program statement execution sequence can be altered allowing decisions to be made based on data or user input.
Overview: 
Explore program flow control using the FOR statement.
Objectives: 

Understand how to alter program flow with the FOR statement.

Content: 

The for statement is used to execute a block of statements some specific number of times. The general form of the for statement is:

The initialization-expression is executed once at entry into the for block, and sets up the initial value of a numeric variable (also called the index) used to control how many times the for statement is repeated. The termination-comparison is evaluated on each repeat of the for loop and the statement is repeated until the condition is false. Typically the index variable is compared to some numeric value. The increment-expression is executed after each repeat of the statement before the termination-comparison is checked and typically increments the index value. If after the initialization-expression is evaluated the termination-comparison is already false, the for statement is not executed. Remember the statement executed by the for can be a single statement or a block of statements in curly braces. Here is an example showing the use of for to iterate a number of times and use the iteration count:

In this example we initialize the index variable i to the starting value of 1, we will test i to be less than 4 (for continues while the comparison is true) and when we loop around we will increment i by 1 before checking the comparsion to see if the loop should continue. Here we start at 1, incement by 1 until i reaches 4. Since i will equal 4 at the start of the for block, the comparison would be false and we would stop. This means we would execute the statements 3 times. You can use any starting value, any comparision and any increment action that is logically correct.

For is typically used to repeat (or loop) the statement(s) a specific number of times or to access arrays or collections (discussed later) that use numeric indexes. Notice in the for statement above we (optionally) defined a new variable i to hold our numeric count. Variables defined in this way are accessible only within the for block. You can use a variable defined outside the for statement. Each component of the for statement is optional so you could write the above example like this:

In this case, since the variable i is defined outside the for statement, it will be accessible after the for is completed and in our example it would contain 3. Also note that the iteration and exit test are manually done in the loop, since they are not defined within the for statement. This for is useful if the exit test or iteration are complex or require multiple steps to determine.

The break and continue statements can be used in for loops. Break will end the loop and continue will jump back to the for skipping any remaining statements in the for block.

Watch this video about the for statement. Here is a detailed discussion of for. Here is the code for these examples on CodingGround. Add a for loop to the example to count from 3 down to 1.

 

Navigation:

Overview: 
Explore program flow control using the WHILE statement.
Objectives: 

Understand how to employ comparisons to alter program flow with the WHILE statement.

Content: 

Another form of flow control allows us to have a statement (or block of statements) repeatedly executed while a comparison result is true. This is done with the while statement. The form of the while statement is:

Here are some examples, each using a comparison of the value of variable z to a constant to arrive at a boolean value. Assume z = 0 at the start of this code:

If the comparison result is false when the while is checked the first time, the block of statements is not executed. Typically the looping of the while statement is controlled by the comparison but it is possible to exit from the loop's block of statements with the break statement. The break statement ends the while and continues execution after the end of the while block. Here is an example, assume x = 0:

This while will loop 3 times, making x reach a value of 3. The if statement is checked on each loop. When the comparison of x and 3 gives true, the code will execute a ‘break’. This means that the code leaves the while loop, and will continue after the last }. The while condition is not checked again.
 
You can also modify loop execution with the continue statement. Continue causes the rest of the statements in a while block to be skipped and the while loop comparison to be checked again to see if the while block should be repeated. You can think of this as a jump back to the while statement.

Assuming autoMode is true to start, this loop will increment x to 3 then continue looping until autoMode (a boolean variable) becomes false, without further incrementing x. Remember the condition is tested first, so if autoMode was false when we first hit the while, the while block would be skipped.

The while statement loops on the comparision result being true. So far the examples loop on the result being true. You can also loop when the comparision result is false by changing the comparision or inverting (convert true/false to the opposite) the false result by preceding it with the ! (not) operator:

Assuming autoMode is false to start, this loop will increment x to 3 then continue looping until autoMode (a boolean variable) becomes true, without further incrementing x. We invert the false value of autoMode into a true so the while repeats. When autoMode goes true, the invert makes the result false and the while loop ends.

Watch a video about looping (stop after the while discussion). Here is a detailed discussion of the while statement. Here is more about break and continue statements. Here are the above examples in CodingGround.

Note that while and do-while are essentially the same. With the do-while, the comparison is done at the end of the loop, thus insuring the loop is executed at least once before the comparison is checked.

This do-while block is executed at least once with continued looping dependent on the result of the comparison.

In robotics, the while statement is often used to loop and monitor the input from joysticks or controllers and operate the robot in response to those inputs. For instance, a while loop could continue until the variable that indicates a match is in progress goes false.

 

Navigation:

Pages