Anda di halaman 1dari 54

HALTEGH 

IT LEARNING CENTER

Java Method/Metode Java


Overview
HALTEGH 
IT LEARNING CENTER

Method di Java
● A Java method is suatu kumpulan statement , logika, operasi ,
varibel , parameter dan lain sebagainya
● Method di Java
HALTEGH 
IT LEARNING CENTER

Membuat Method

Syntax
public static int methodName(int a, int
b) {
// body }

•public static − modifier


•int − return type
•methodName − name of the method
•a, b − formal parameters
•int a, int b − list of parameters
HALTEGH 
IT LEARNING CENTER

Membuat Method
● Method definition consists of a method header and a
method body. The same is shown in the following
syntax −
Syntax
/** the snippet returns the minimum
modifier returnType between two numbers */
nameOfMethod (Parameter public static int minFunction(int n1,
List) { // method body } int n2) {
int min;
•modifier − It defines the access type of the
method and it is optional to use.
if (n1 > n2) min = n2;
•returnType − Method may return a value. else min = n1;
•nameOfMethod − This is the method name. return min; }
The method signature consists of the method
name and the parameter list.
•Parameter List − The list of parameters, it is
the type, order, and number of parameters of a
method. These are optional, method may
contain zero parameters.
Memanggil Method
● Cara memanggi l method yakni dengan memanggi nama
methodnya, terlepas dia ada return atau tidaknya
● Jika ada retuntn di method yang di panggil, maka akan
memanggil return valuenya
● return statement di eksekusi
// Method BIASA
public static int normalMethod(int n1, int n2) {
int min; //Ini parameter

// buat var c ,
// nilai n1= a =11,
// n2 = b= 6

if (n1 > n2) // Jika n1 lebih besar dari n2 yang mana kondisinya 11>6
min = n2; // Terpenuhi kondisi IF maka kode ini yang jalan

else // Jika kondisi IF terpenuhi , maka else tidak akan jalan


min = n1; // Tidak jalan saat Else tidak jalan

return min; //return buat simpen value, disini value min nya adalah 6
}
}
public class MethodIfElse {

// MAIN method
public static void main(String[] args) {
int a = 11; // Ini Variabel a
String z = "Welcome"; // Ini Variabel z
String y = "Gabung"; // Ini Variabel y
int b = 6; // Ini Variabel b
int c = normalMethod(a, b); // Ini Variabel C yang isinya
// memangggil method biasa dengan
diberikan
// parameter yakni a bernilai 11 dan
b bernilai 6
int d = a+b; // Ini Variabel d
int e = a+8; // Ini Variabel e

System.out.println("Nilai Saat c ini = " + c); // Mencetak nilai


variabel c
System.out.println("nlai d = " + d); // Mencetak nilai variabel d
System.out.println("nlai d = " + e); // Mencetak nilai variabel e
System.out.println("nlai z = " + z +" "+y); // Mencetak nilai
variabel z dan y
}
Keyword Void
● Void pada method menunjukan bahwa method tersebut tidak memiliki return value,
sehingga tidak akan menypan apapun

public class ExampleVoid {


public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
} else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
}
Transfer Parameters dengan Value/Nilai
● Cara melakukan transfer nilai parameter dengan suatu value baru bisa dengan contoh
dibawah,
public class swappingExample {

public static void main(String[] args) {


int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);

// Invoke the swap method


swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will
be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " +
b);
// Swap n1 with n2 int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " +
b); }
}
Java Overloading
Method Overloading in Java
● Jika suatu kelas di java memiliki banyak method dengan nama yang sama namun memiliki
parameter atau return yang berlainan , maka method tersebut dikenal dengan isyilah Method
Overloading.
Keuntungan method overloading
● Method overloading menambah readability suatu program
Cara Mengoverload Method
There are two ways to overload the method in java:

● Memodifikasi parameter
● Mengganti Tipe Data
Different? Let us check it
out by the programs
Method Overloading: changing no. of
arguments
 
class TestOverloading1{  
public static void main(String[] args){  
System.out.println(add(11,11));  
System.out.println(add(11,11,11));  
}

static int add(int a,int b){return a+b;}  
static int add(int a,int b,int c){return a+b+c;}   Guess
}   what is the
output?
Method Overloading: changing no. of
arguments
class Adder{  
static int add(int a,int b){return a+b;}  
static int add(int a,int b,int c){return a+b+c;}  
}  
class TestOverloading1{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));  
System.out.println(Adder.add(11,11,11));  
}}  
22
33
Method Overloading: mengganti tipe data
class Adder{  
static int add(int a, int b){return a+b;}  
static double add(double a, double b){return a+b;}  
}  
class TestOverloading2{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));  
System.out.println(Adder.add(12.3,12.6));  
}}  
Guess
what is the
output?
Method Overloading: mengganti tipe data
class Adder{  
static int add(int a, int b){return a+b;}  
static double add(double a, double b){return a+b;}  
}  
class TestOverloading2{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));  
System.out.println(Adder.add(12.3,12.6));  
}}  
22
24.9
Contoh Soal
Buat sebuah kelas dengan nama Gue, kelas Gue punya “main” method,
dan 2 method biasa “Temen” dan “Sahabat”
Main akan panggil method Temen dan Sahabat didalamnya
Overloading kedua method Temen dan Sahabat sebanyak mungkin
Jawaban
public class Gue { // Mendeklarasikan suatu kelas dengan nama = Gue

//ini Main Method


public static void main(String[] args){
Temen(); //panggil Method Normal "Temen" tanpa parameter
Temen(10); //panggil Method Normal "Temen" dengan parameter a =10
Temen(20, 30); //panggil Method Normal "Temen" dengan parameter 20
dan 30

Sahabat();//panggil Method Normal "Sahabat" tanpa parameter


Sahabat("tes 1"); //panggil Method Normal "Sahabat" dengan parameter
c= "tes 1"
Sahabat( "tes 2", "tes 3");//panggil Method Normal "Sahabat" dengan
parameter d = "tes 2", dan e = "tes 3"
Sahabat("tes 4", "tes 5", "tes 6");//panggil Method Normal "Sahabat"
dengan parameter f = "tes 4", g="tes 5" dan e = "tes 6"
}
Jawaban
//Ini Method Normal "Temen" tanpa parameter
private static void Temen()
{
System.out.println("Method Temen tanpa parameter"); // menanpilkan
"Method Temen tanpa parameter"
}

//Ini Method Normal "Temen" dengan parameter a , tipe nya int atau angka
private static int Temen(int a)
{
System.out.println(a); // menanpilkan nilai a
return a; //menyimpan nilai a
}

//Ini Method Normal "Temen" dengan parameter a dan b, keduanya nernilai int
atau angka
private static int Temen(int a, int b){
System.out.println(a+" "+b); // menanpilkan nilai c dan b yang tidak
dijumlah
System.out.println(a+b); // menanpilkan nilai c dan b yang dijumlah
return a+b; //menyimpan nilai a dan b
}
Jawaban
//Ini Method Normal "Sahabat" dengan parameter
private static void Sahabat()
{
System.out.println("Method Sahabat tanpa parameter");
}

//Ini Method Normal "Sahabat" dengan paameter c, tipenya String atau hurufangka
private static String Sahabat(String c) {
System.out.println(c); // menanpilkan nilai c
return c; //menyimpan nilai c
}

//Ini Method Normal "Sahabat" dengan paameter d dan e, tipenya String atau
hurufangka
private static String Sahabat(String d, String e){
System.out.println(d+" "+e); // menanpilkan nilai d dan e
return d+e; //menyimpan nilai d dan e
}

//Ini Method Normal "Sahabat" dengan paameter f,g dan h tipenya String atau
hurufangka
private static String Sahabat(String f, String g, String h){
System.out.println(f+ " " +g+ " " +h); // menanpilkan nilai f,g,dan h
return f+g+h; //menyimpan nilai e,f,dan g
}

}
Assignment in the class:
Create Method Overloading like I
‘ve shown above, create a simply
one?
Question from me
Why Method Overloading is not
possible by changing the return
type of method only?

Abdu.halim@haltegh.id
In java, method overloading is not possible by changing
the return type of the method only because of ambiguity.
Let's see how ambiguity may occur:
Apa Output Programnya?
class Adder{  
static int add(int a,int b){return a+b;}  
static double add(int a,int b){return a+b;}  
}  
class TestOverloading3{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));//ambiguit
y  
Compile Time Error: method add(int,int) is already defined in class Adder

}}  
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?
Can we overload java main() method?
● Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only.
● Let's see the simple example:

class TestOverloading4{  
public static void main(String[] args)
{System.out.println( "main with String[]"); }  
public static void main(String args){System.out.println("
main with String "); }  
public static void main(){System.out.println(" main without
args ");}  

main with String[]
Method Overloading and
Type Promotion
One type is promoted to another implicitly if no matching
datatype is found. Let's understand the concept by the figure
given below:
● As displayed in the above diagram, byte can be promoted to
short, int, long, float or double. The short datatype can be
promoted to int,long,float or double. The char datatype can be
promoted to int,long,float or double and so on.
Example of Method Overloading with
TypePromotion
class OverloadingCalculation1{  
  void sum(int a,long b){System.out.println(a+b);}  
  void sum(int a,int b,int c){System.out.println(a+b+c);}  
  
  public static void main(String args[]){  
  OverloadingCalculation1 obj=new OverloadingCalculation1();  
  obj.sum(20,20);
//now second int literal will be promoted to long  
  obj.sum(20,20,20);  
  
  }  
}  
Example of Method Overloading with Type Promotion if matching
found
If there are matching type arguments in the method, type
promotion is not performed.
class OverloadingCalculation2{  
  void sum(int a,int b)
{System.out.println("int arg method invoked");}  
  void sum(long a,long b)
{System.out.println("long arg method invoked");}  
  
  public static void main(String args[]){  
  OverloadingCalculation2 obj=new OverloadingCalculation2();  
  obj.sum(20,20);//now int arg sum() method gets invoked  
  }  
}  
How Method Overloading with Type
Promotion in case of ambiguity?
• Hint:
If there are no matching type arguments in the method, and each
method promotes similar number of arguments, there will be
ambiguity.
Flow statements
Java If-else Statement
Java if statement digunakan untuk melakukan cek kondisi.
Nantinya akan menggunkan Boolean untuk hasil pengecekan
kondisinya, apakah benar/true atau slaah/false. Ada beebrapa
jenis if di Java :

● if statement
● if-else statement
● if-else-if ladder
● nested if statement
Java IF Statement
● Test dengan IF, jika konsidi IF terpenuhi, maka blok kode { }
yang ada di IF yang di jalankan
Syntax:
if(condition){  
//code to be executed  
}   public class IfExample {  
public static void main(String[] args) {  
    int age=20;  
    if(age>18){  
        System.out.print("Age is greater than 18");  
    }  
}  
}  
Java IF-else Statement
● IF-ELSE diapakai jika kondisi ada lebih dari 1 , dan IF tidak terpenuhi, maka yang
dihalankan adalah ELSE nya.
Syntax:
if(condition){  
//code if condition is true  
}else{  
//code if condition is false  
}  

public class IfElseExample {  
public static void main(String[] args) { 
 
    int number=13;  
    if(number%2==0){  
        System.out.println("even number")
;  
    }else{  
        System.out.println("odd number");
  
    }  
}  
}  
Java IF-else-if ladder Statement
● Jika ada banya kondisi yang terjadi , maka penggunaaan if else if else dapat dilakukan
Syntax:
if(condition1){  
//code to be executed if condition1 is tr
ue  
}else if(condition2){  
//code to be executed if condition2 is tr
ue  
}  
else if(condition3){  
//code to be executed if condition3 is tr
ue  
}  
...  
else{  
//code to be executed if all the conditio
ns are false  
}  
Your Assignment, try to create simply
code of if else if
Java Switch Statement
● Swith dipakai jika ada beberapa konsidi yang harus di cek, mirip seperti if-else-if ladder
statement.
Syntax:
switch(expression){    
case value1:    
 //code to be executed;    
 break;  //optional  
case value2:    
 //code to be executed;    
 break;  //optional  
......    
    
default:     
 code to be executed if all cases are
 not matched;    
}    
Java Switch Statement
public class SwitchExample {  
public static void main(String[] args) {  
    int number=20;  
    switch(number){  
    case 10: System.out.println("10");break;  
    case 20: System.out.println("20");break;  
    case 30: System.out.println("30");break;  
    default:System.out.println("Not in 10, 20 or
 30");  
    }  
}  
}  
Java Switch Statement is fall-through
● Jika tidak ada kondisi yang match, maka default akan otomatis berjalan

public class SwitchExample2 {  
public static void main(String[] args) {  
    int number=20;  
    switch(number){  
    case 10: System.out.println("10");  
    case 20: System.out.println("20");  
    case 30: System.out.println("30");  
    default:System.out.println("Not in 10, 20 or 30");  
    }  
}  
}  
Java For Loop
Loop digunakan untuk meng iterasi suatu program, Jika iterasinya memiliki batas, maka loop
adalah solusi

● Ada 3 jenis loop


● Simple For Loop
● For-each or Enhanced For Loop
● Labeled For Loop
Java Simple For Loop
Syntax:
for(initialization;condition;incr/de
cr){  
//code to be executed  
}  

public class ForExample {  
public static void main(String[] args) 
{  
    for(int i=1;i<=10;i++){  
        System.out.println(i);  
    }  
}  
}  
Java For-each Loop
● The for-each loop digunakan untuk menggeluarkan isi-isi dari suatu data yang banyak

Syntax:
for(Type var:array){   public class ForEachExample {  
//code to be executed   public static void main(String[] args) { 
}    
    int arr[]={12,23,44,56,78};  
    for(int i:arr){  
        System.out.println(i);  
    }  
}  
}  
Java Labeled For Loop
Label pada Loop berguna untuk melakukan break program, sehingga cukup dengan menuliskan suatu
hal dan dapat di break

Syntax: public class LabeledForExample {  
labelname:   public static void main(String[] args) {  
for(initialization;condition;incr/decr)     aa:  
{           for(int i=1;i<=3;i++){  
//code to be executed               bb:  
}                   for(int j=1;j<=3;j++){  
                    if(i==2&&j==2){  
                        break aa;  
                    }  
                    System.out.println(i+" "+j); 
 
                }  
        }  
}  
}  
Break bb dialkukan untuk menghentikan inner loop, meskipun tanpa break
bb program sudah berheni/ dapat di stop di inner loopnya(for kedua)

public class LabeledForExample2 {  
public static void main(String[] args) {  
    aa:  
        for(int i=1;i<=3;i++){  
            bb:  
                for(int j=1;j<=3;j++){  
                    if(i==2&&j==2){  
                        break bb;  
                    }  
                    System.out.println(i+" "+j);  
                }  
        }  
}  
}  
Java While Loop
● While loop mirip seperti for, hanya saja jika lamanya iterasi tidak dikathui, leih baik menggunakan
while loop.
Syntax:
while(condition){  
//code to be executed  
}  
public class WhileExample {  
public static void main(String[] 
args) {  
    int i=1;  
    while(i<=10){  
        System.out.println(i);  
    i++;  
    }  
}  
}  
Java Break Statement
● Break dilakukan untuk menghentikan suatu program yang sedang berjalan

Syntax:
jump-statement;    
public class BreakExample {  
break;
public static void main(String[] args)
 {  
    for(int i=1;i<=10;i++){  
        if(i==5){  
            break;  
        }  
        System.out.println(i);  
    }  
}  
}  
Break di inner loop (di dalam for j)
● It breaks inner loop only if you use break statement inside the inner loop.

public class BreakExample2 {  
public static void main(String[] args) {  
            for(int i=1;i<=3;i++){    
                    for(int j=1;j<=3;j++){    
                        if(i==2&&j==2){    
                            break;    
                        }    
                        System.out.println(i+" "+j);    
                    }    
            }    
}  
}  
Java Continue Statement
● Continue diapakai untuk menjalankan program tetapi dengan menggambil poin yang di set /
sijadikan parameter continuenya

Syntax: public class ContinueExample {  
jump-statement;    
continue; 
public static void main(String[] args) { 
 
    for(int i=1;i<=10;i++){  
        if(i==5){  
            continue;  
        }  
        System.out.println(i);  
    }  
}  
}  
HALTEGH 
IT LEARNING CENTER

End
HALTEGH 
IT LEARNING CENTER

Questions ?

Anda mungkin juga menyukai