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 }
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
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
● 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 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
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 ?