Java Lab 3
Java Lab 3
Java Lab 3
Lab Outlines
Java Functions introduction
Function parameters and function overloading
Java recursion
Practice programs of Java Arrays and Functions
Function
A Function or method is a block of code which only runs when it is called.
Methods are used to perform certain actions, and they are also known
as functions.
Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses ().
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class and not an object
of the Main class.
void means that this method does not have a return value.
Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
myMethod();
Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
Practice Programs
1. (Print a table) Write a program that displays the following table:
a a^2 a^3
1 1 1
2 4 8
3 9 27
4 16 64
4. (Game: scissor, rock, paper) Write a program that plays the popular
scissor-rockpaper game. (A scissor can cut a paper, a rock can knock
a scissor, and a paper can wrap a rock.) The program randomly
generates a number 0, 1, or 2 representing scissor, rock, and paper.
The program prompts the user to enter a number 0, 1, or 2 and
displays a message indicating whether the user or the computer wins,
loses, or draws. Here are sample runs:
Write a program that prompts the user to enter a password and displays
Valid Password if the rules are followed or Invalid Password otherwise.