
In the example program in the previous discussion, we only wrote the instruction code for the function
main()
.
Function
main()
is the main function in a Java program. All the code we write in it will be executed immediately.
But the problem now:
"What if we make a large enough program, can we still write all the code in the function
main()
?"
It's possible, but it's less effective and will consume a lot of energy to type the code.
Not to mention if there is an error ...
"Then what is the solution?"
The solution is to use procedures / functions.
Procedures / functions can break the program into sub-programs, so that we can make the program more efficient.
The use of procedures / functions can reduce repeated typing of code.
On this occasion, we will learn to use procedures / functions in Java to create programs.
First, we first acquaint with procedures and functions. After that, continue with the sample program.
Understanding Procedures, Functions, and Methods
Don't be confused ... because all three are the same.
The procedure, function, and method are the same.
Procedure is a term for a function that does not return a value. This function is usually indicated by keywords
void
.
A function is a term for a function that returns a value.
Method is a function that is inside a class. This term, usually used in OOP.
For simplicity, let's call all functions .
How to Make Functions in Java
Functions must be created or written in the class .
The basic structure is like this:
static TypeDataKembalian namaFungsi(){
// statemen atau kode fungsi
}
Explanation:
- Keywords
static
, meaning we create functions that can be called without having to create an object instance.Confused? I'll explain later. TypeDataKembalian
is a data type of value returned after the function is executed.namaFungsi()
is the name of its function. Usually written in small letters at first. Then, if there are more than one syllable, the first letter in the second word is written in capital.
Example:
static void ucapSalam(){
System.out.println("Selamat Pagi");
}
The data type
void
means empty, the function does not reverse the value of anything.How to Call / Execute Functions
After we create a function, then we will execute its function.
Functions can be called from functions
main
or from other functions.
Examples of function calls in in funsgi
main
:public static void main(String[] args){
ucapSalam();
}
Then it will produce output:
Selamat Pagi
The complete code, please try it yourself:
class BelajarFungsi {
// membuat fungsi ucapSalam()
static void ucapSalam(){
System.out.println("Selamat Pagi");
}
// membuat fungsi main()
public static void main(String[] args){
// memanggil/eksekusi fungsi ucapSalam()
ucapSalam();
}
}
Functions with Parameters
Parameters are variables that hold values for processing in functions. Parameters act as inputs for functions.
The basic structure is like this:
static TipeData namaFungsi(TipeData namaParameter, TipeData namaParameterLain){
// kode fungsi
}
Explanation:
- Parameters are written between parentheses
(...)
; - Parameters must be given a data type;
- If there are more than one parameter, then separated by a comma.
Examples of functions that have parameters:
static void ucapin(String ucapan){
System.out.println(ucapan);
}
In this example, we create a named parameter
ucapan
with type String
. So we can use variables ucapan
in functions.
How to call a function that has parameters:
ucapin("Hallo!");
ucapin("Selamat datang di pemrograman Java");
ucapin("Saya kira ini bagian terakhir");
ucapin("Sampai jumpa lagi, ya!");
The output results:
Hallo!
Selamat datang di pemrograman Java
Saya kira ini bagian terakhir
Sampai jumpa lagi, ya!
Function that Returns Value
After the function processes the data entered through the parameters, then the function must return the value so that it can be processed in the next process.
Returns values for functions using keywords
return
.
Example:
static int luasPersegi(int sisi){
int luas = sisi * sisi;
return luas;
}
In this example, we make a parameter named
sisi
. Then the function will return a value of type int
(integer) from the variable luas
.
Example caller:
System.out.println("Luas Persegi dengan panjang sisi 5 adalah " + luasPersegi(5));
Output Results:
Luas Persegi dengan panjang sisi 5 adalah 25
Calling Functions in Other Functions
Functions can call each other to process data.
For example, a program Build Space Calculator has functions:
luasPersegi()
, luasPersegiPanjang()
, luasSegitiga()
, luasBalok()
, luasKubus()
etc.
These functions can help each other, examples of functions
luasKubus()
need functions luasPersegi()
.
Formula:
Luas Kubus = 6 * luasPersegi;
Luas Persegi = sisi * sisi;
Then the program can be made like this:
public class BangunRuang {
public static void main(String[] args) {
int s = 12;
int luas = luasKubus(s);
System.out.println(luas);
}
// membuat fungsi luasPersegi()
static int luasPersegi(int sisi){
return sisi * sisi;
}
// membuat fungsi luasKubus()
static int luasKubus(int sisi){
// memanggil fungsi luasPersegi
return 6 * luasPersegi(sisi);
}
}
Output results
864
Static and Non-Static Functions
In the examples above, we use keywords
static
before creating a function.
The keyword
static
will make the function directly executable, without having to create an instance of the object from the class.
Example:
public class FungsiStatic {
// Fungsi non-static
void makan(String makanan){
System.out.println("Hi!");
System.out.println("Saya sedang makan " + makanan);
}
// fungsi static
static void minum(String minuman){
System.out.println("Saya sedang minum " + minuman);
}
// fungsi main
public static void main(String[] args) {
// pemanggilan fungsi static
minum("Kopi");
// mambuat instansiasi objek saya dari class FungsiStatic
FungsiStatic saya = new FungsiStatic();
// pemanggilan fungsi non-static
saya.makan("Nasi Goreng");
}
}
In this example, the function
makan()
is a non-static function . While the function minum()
is a static function .
The output results from the program above:
Saya sedang minum Kopi
Hi!
Saya sedang makan Nasi Goreng
If we don't create an object to call a non-static function , an error will occur.
Global Variables and Local Variables in Java
Global variables are variables that can be accessed from all functions. While local variables are variables that can only be accessed from within the function where the variable is located.
Confused?
Let's look at an example:
class ProgramKu{
// ini variabel global
static String nama = "Programku";
static String version = "1.0.0";
static void help(){
// ini variabel lokal
String nama = "Petani Kode";
// mengakses variabel global di dalam fungso help()
System.out.println("Nama: " + nama);
System.out.println("Versi: " + version);
}
public static void main(String args[]){
// panggil fungsi help()
help();
System.out.println("Nama: " + nama);
System.out.println("Versi: " + version);
}
}
The output results:
Nama: Petani Kode
Versi: 1.0.0
Nama: Programku
Versi: 1.0.0
When the function call
help()
we recreate the variable nama
. So the name variable becomes a local variable in the function help()
and its value changes to "Petani Kode"
.
Whereas, when we access the variable name again through the function the
main()
value remains the same as defined.Examples of Programs with Functions and Procedures
This program is a simple program with the following features:
- Read data from ArrayList
- Save data to ArrayList
- Change data
- Delete Data
- Exit
Don't know about ArrayList?
Please read the details: Getting to know arrays in Java
Alright, please create a new class named
FungsiProsedur
. Then import the required classes.import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
After that, create global variables in the class
FungsiProsedur
:static ArrayList listBuah = new ArrayList();
static boolean isRunning = true;
static InputStreamReader inputStreamReader = new InputStreamReader(System.in);
static BufferedReader input = new BufferedReader(inputStreamReader);
Explanation:
- Variables
listBuah
are global variables for storing fruit names. - Variables
isRunning
are global variables for creating loops. - Then
inputStreamReader
andinput
are the objects we need to take input from the keyboard.
After that, make each function.
Function for displaying menus :
static void showMenu() throws IOException {
System.out.println("========= MENU ========");
System.out.println("[1] Show All Buah");
System.out.println("[2] Insert Buah");
System.out.println("[3] Edit Buah");
System.out.println("[4] Delete Buah");
System.out.println("[5] Exit");
System.out.print("PILIH MENU> ");
int selectedMenu = Integer.valueOf(input.readLine());
switch(selectedMenu){
case 1:
showAllBuah();
break;
case 2:
insertBuah();
break;
case 3:
editBuah();
break;
case 4:
deleteBuah();
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Pilihan salah!");
}
}
The function is tasked to display the menu and specify which functions will be called based on the menu number entered.
What is it
throws IOException
?
Later I will discuss it next time. For now it's just ignored first. This is because we use Buffereader, so it
throws IOException
must be written.
Function to display data :
static void showAllBuah(){
if(listBuah.isEmpty()){
System.out.println("Belum ada data");
} else {
// tampilkan semua buah
for(int i = 0; i < listBuah.size(); i++){
System.out.println(String.format("[%d] %s",i, listBuah.get(i)));
}
}
}
The function is tasked with displaying the contents of
listBuah
. If listBuah
empty, a message will be displayed "Belum ada data"
.
Functions for adding fruit data :
static void insertBuah() throws IOException{
System.out.print("Nama buah: ");
String namaBuah = input.readLine();
listBuah.add(namaBuah);
}
In this function, we use methods
listBuah.add(namaBuah);
to add data into listBuah
based on namaBuah
the given.
Function for changing fruit data :
static void editBuah() throws IOException{
showAllBuah();
System.out.print("Pilih nomer buah: ");
int indexBuah = Integer.valueOf(input.readLine());
System.out.print("Nama Baru: ");
String namaBaru = input.readLine();
// ubah nama buah
listBuah.set(indexBuah, namaBaru);
}
First we need to display the fruit list first, then we ask the user to choose which fruit to edit.
After that, we update the fruit with the method
listBuah.set(indexBuah, namaBaru);
.
Function for removing fruit :
static void deleteBuah() throws IOException{
showAllBuah();
System.out.print("Pilih nomer buah: ");
int indexBuah = Integer.valueOf(input.readLine());
// hapus buah
listBuah.remove(indexBuah);
}
It's almost the same as fruit editing, to delete our fruit also needs the fruit index number to be deleted.
Then delete it using the method
listBuah.remove(indexBuah);
.
Main function :
public static void main(String[] args) throws IOException {
do {
showMenu();
} while (isRunning);
}
Complete, here is the complete code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class FungsiProsedur {
static ArrayList listBuah = new ArrayList();
static boolean isRunning = true;
static InputStreamReader inputStreamReader = new InputStreamReader(System.in);
static BufferedReader input = new BufferedReader(inputStreamReader);
static void showMenu() throws IOException{
System.out.println("========= MENU ========");
System.out.println("[1] Show All Buah");
System.out.println("[2] Insert Buah");
System.out.println("[3] Edit Buah");
System.out.println("[4] Delete Buah");
System.out.println("[5] Exit");
System.out.print("PILIH MENU> ");
int selectedMenu = Integer.valueOf(input.readLine());
switch(selectedMenu){
case 1:
showAllBuah();
break;
case 2:
insertBuah();
break;
case 3:
editBuah();
break;
case 4:
deleteBuah();
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Pilihan salah!");
}
}
static void showAllBuah(){
if(listBuah.isEmpty()){
System.out.println("Belum ada data");
} else {
// tampilkan semua buah
for(int i = 0; i < listBuah.size(); i++){
System.out.println(String.format("[%d] %s",i, listBuah.get(i)));
}
}
}
static void insertBuah() throws IOException{
System.out.print("Nama buah: ");
String namaBuah = input.readLine();
listBuah.add(namaBuah);
}
static void editBuah() throws IOException{
showAllBuah();
System.out.print("Pilih nomer buah: ");
int indexBuah = Integer.valueOf(input.readLine());
System.out.print("Nama Baru: ");
String namaBaru = input.readLine();
// ubah nama buah
listBuah.set(indexBuah, namaBaru);
}
static void deleteBuah() throws IOException{
showAllBuah();
System.out.print("Pilih nomer buah: ");
int indexBuah = Integer.valueOf(input.readLine());
// hapus buah
listBuah.remove(indexBuah);
}
public static void main(String[] args) throws IOException {
do {
showMenu();
} while (isRunning);
}
}
After that, please run and pay attention to the results.
========= MENU ========
[1] Show All Buah
[2] Insert Buah
[3] Edit Buah
[4] Delete Buah
[5] Exit
PILIH MENU> 1
Belum ada data
========= MENU ========
[1] Show All Buah
[2] Insert Buah
[3] Edit Buah
[4] Delete Buah
[5] Exit
PILIH MENU> 2
Nama buah: Apel
========= MENU ========
[1] Show All Buah
[2] Insert Buah
[3] Edit Buah
[4] Delete Buah
[5] Exit
PILIH MENU> 1
[0] Apel
========= MENU ========
[1] Show All Buah
[2] Insert Buah
[3] Edit Buah
[4] Delete Buah
[5] Exit
PILIH MENU>
Please try to insert, edit, and delete.
0 Komentar untuk "Learning Java: Using Procedures and Functions to Create Sub-programs"
Silahkan berkomentar sesuai artikel