RoboRIO

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:

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

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

Content: 

The switch statement allows you to compare a value to a list of possible matching values and so select from multiple possible statements or blocks. A key difference from the if statement is that the value compared is not boolean, but instead numeric, enumeration (discussed later) or String. The form of the switch statement is:

This basic form of switch evaluates an expression resulting in a numeric value. That value is checked against the case statement values and if there is a match, the statement(s) following the case are executed. Note that execution continues into the following case statements unless the list of statements to execute is terminated by a break statement. The break statement ends a case block and execution continues with the first statement after the switch block. Most of the time each case will end with a break but there may be situations where you want case 2 executed in addition to case 1 (for example). If no case statement is matched, the default case is executed (if present). Here is an example switch block:

With x = 2, the second case is executed and execution stops with the break resulting in z = 5. If x = 1, then the first case is executed, setting z = 1, and the second case would also be executed (no break after first case) setting z = 5 and then ending there. If x = 3, then the third case and the default case (no break after third case) would be executed and z would be = 11 at the end of the execution. If x = 5, no case is matched so the default case would be executed and z would = 11. Here is the example code in CodingGround. Try changing the value of x as discussed here and prove that it works. Modify the code so that setting x = 3 results in z = 9.
 
There is a use-case where you have multiple case statements in a row with no intervening code:

Here we want to call method doSomething() if foo is 0 or 1.
 
Using Strings with switch statements is similar. Assuming day is a String variable = "tuesday", here is an example:

In this example, dayNumber will  be 2 after the switch is done. Using enumerations on switch statements is another powerful form but will be discussed in a later section.

Here is a video about switch. Here is a detailed discussion of switch. Here is this example in CodingGround. Complete and test the example in CodingGround for the full 7 days of the week.

In robotics, switch can be useful to match information from controllers and sensors that is numeric in nature to actions to be taken. For instance, joysticks may return which button is pressed as a numeric value. A switch statement can match the button numbers to actions.

 

Navigation:

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

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

Content: 

Once we are able to compare values (variables) and arrive at a boolean true/false (or yes/no) value, we need a way to act on that boolean value. With comparisons we are essentially asking a question and will change program flow based on the answer. We ask questions with flow control statements, the first of which is if. The general form of the if statement is:

Here we are asking if the boolean-value (comparison result) is true and if so execute the statement. If the answer is false, don't execute the statement. The boolean-value that is the result of a comparison expression also called a condition. Note that only one statement my follow the if, but you may use a statement block { } (curly braces) to control multiple statements. With curly braces all of the statements between the two braces are executed. Here are some examples (assume x = y = 0):

So far we are just choosing to execute the statement conditioned by the if or not. What if we want to choose between two actions, one if the boolean-value is true and another if it is false. That is where else comes in. Here is the form of the if else statement:

Here, if the boolean-value is true, statement-1 is executed and if boolean-value is false, statement-2 is executed. One of the statements will be executed. Assuming x = y = 0, here are some examples:

The final form if the if statement is if else if. This form allows us to ask another question on the else branch to further decide which statement to execute. The form of the if else if is:

Assuming x = y = 0, here are some examples:

Watch this video for more about flow control with if (stop at the switch statement, we will cover it later). Here is a detailed discussion of if.

Whenever there are multiple options on an if statement you are trying to write (if I see blue I will do this, if I see red I will do that, if I see green I will do a third thing, if I see nothing I will stop), note that while we can use multiple if statements in a row, we should to use else if statements to link them together. Using multiple simple if statements can result in incorrect behavior. Do not just stack if statements together.
 
In robotics, the if statement is used to check the status of controller buttons, sensors or other input devices and decide what the robot should do in response.
 
Here is the example code in CodingGround.

Click Next for a quiz on if statements.

 

Navigation:

Overview: 
Explore comparing variable values and making decisions based on the results.
Objectives: 

Understand what comparison is, what the Java comparsion operators are and how to use them.

Content: 

A simple program, like Hello World, just flows from start to finish, one statement after another until done. Solving real problems always involves evaluating data or user input and making decisions about what to do next, when to do it and what to do when things go wrong and much more. Handling these possibilities is called Flow Control.

Flow control is based on comparison. This means taking two variables and comparing them resulting in a boolean (true/false) value. We then use that boolean result to decide what to do next in a flow control statement.

Comparison is taking two values separated by a comparison operator and replacing them (internally) with the boolean result of the comparison. For instance, if  X = 5 and Y = 5, then the comparison  X == Y  results in true. Remember that = by itself is not comparison, it is assignment. Compare equal is ==.  Using X from above,  X == 7  results in false. The Not equal comparison operator is !=, so  X != 7  results in true.

Java supports an extensive list of comparison operators. Here is a detailed discussion of comparison operators. Note that comparison operators are divided into several types. Relational operators are used when you are comparing two non-boolean values. When comparing boolean values, the operators are called conditional. There are also bitwise operators but we will leave that for you to investigate in the resources noted earlier in this paragraph.

Relational operators are pretty easy to understand, the two values (also called operands) are compared and are either equal or not equal, with not equal split into greater or less than. Conditional operators are different. When we have two boolean values, we can AND (&& operator) them, meaning if both values are true, the result is true. If either value is false, the result is false. We can also OR (II operator) the values, meaning if either value is true, the result is true.

Watch these videos (video1, video2, video3, video4) for more information.

The ! operator prefixed to a boolean inverts the value of the boolean. Thus (from above) if  X == Y is true, !( X == Y) is false. If we have a boolean variable, B equal to true, then B by itself evaluates to true, but !B evaluates to false.

Comparison can be combined with parenthesis:  ( X == 5 ) && ( Y > 3 )  results in true, since both terms are true and then they are and'ed together in a third comparison. By the same token, ( X == 5 ) && ( Y != X ) results in false, since one term is true and one is false

Click Next for a quiz on comparsions.

 

Navigation:

Pages