0% found this document useful (0 votes)
20 views28 pages

Java Methods Overview and Examples

method

Uploaded by

Thet Myat Noe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views28 pages

Java Methods Overview and Examples

method

Uploaded by

Thet Myat Noe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java SE Developer Course

Lecture 7: Methods

Prep red by
Pyi Soe
a
Methods
Methods we used before

readDataType("Prompt Text")

print("some text")

println("some text")
[Link](true/false)
[Link](n) // n is double data type
turnLeft()
pickBeeper()
Method that Returns a Value
Quite simil r to m th functions
import [Link].*;

public class RightTriangle extends ConsoleProgram {

public void run() {


while (true) {
println("This program calculates the length of one side of a right triangle.");
println("Assume h is hypotenuse and a and b other the other sides.");
double a = readDouble("Enter a: ");
double b = readDouble("Enter b: ");
double h = getLenOfHypotenuse(a, b);
println("Len of hypotenuse: " + h);

double h1 = readDouble("Enter h: ");


double aOrB = readDouble("Enter a or b: ");
double otherSide = getLenOfOtherSide(h1, aOrB);
println("Len of the other side: " + otherSide);
}
}

private double getLenOfHypotenuse(double a, double b) {


double h = [Link](a * a + b * b);
return h;
}

private double getLenOfOtherSide(double h, double a){


double b = [Link](h * h - a * a);
return b;
}
}
a
a
Input Output

a
getLenOfHypotenuse h

b
Method that Returns a Value
Decl r tion

visibility type methodName(type paramName1, type paramName2, ..., type paramNamen) {


// Statements
return exp;
}

visibility - private public ြဖ င်တယ် (ဒီ စ်ခုမပါတာလဲ ြဖ င်တယ်။ visibility and access modi ers အ င်းမှာ အေသးစိတ်ပါမယ်)။

type - ရလဒ်တန်ဖိုး၏ အ အစား ( method က ြပန်ထုတ်ေပးသည့် တန်ဖိုး၏ အ အစား)။ return exp မှ ၏ exp ရလဒ်တန်ဖိုး င့် အ အစား တူရတယ်။

type paramName - တစ်ခုစီ၏ အမ င့် အ အစား


return exp - expression ကို evaluate လု ရလာတဲ့ တန်ဖိုးကို ြပန်ထုတ်ေပးတယ် (method ကို တဲ့ေနရာမှာ expression ရလဒ်တန်ဖိုးကို ရေစတယ်)

a
a
သို့
မျိုး
ည်နှ
သို့
စ်နို
ပ်လို့
မျိုး
နှ
စ်နို
မျိုး
ခေါ်သုံး
fi
ကြော
ရဲ့
နှ
မျိုး
import [Link].*;

public class MathFunctions extends ConsoleProgram {


public void run() {

private int abs(int n) {


if (n < 0) {
return -n;
} else {
return n;
}
}

private double min(double x, double y) {


if (x < y) {
return x;
} else {
return y;
}
}
private int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

}
Method with No Return Value
Side effect
import [Link].*;

public class PrintAmtInCurrency extends ConsoleProgram {


public void run() {
centsToFmtCcy(2245);
println("done!");
}

private void centsToFmtCcy(int cents) {


int dollars = cents/100;
int remCents = cents % 100;
String dispStr = "$" + dollars + "." + remCents;
print(dispStr);
return; // optional
}
}
Input
No output value
centsToFmtCcy
cents

Si
de
e
ec eth
Text appear on console output

t t od
m

o
ou
ts
id
e
of
ff
Method with No Return Value
Decl r tion

visibility void methodName(type paramName1, type paramName2, ..., type paramNamen) {


// Statements
return; // optional return statement
}

visibility - private public ြဖ င်တယ် ( စ်ခုမပါတာလဲ ြဖ င်တယ်။ visibility and access modi ers အ င်းမှာ အေသးစိတ်ပါမယ်)။

void - ဒီ method ဟာ တန်ဖိုးတခုခုကို ြပန်ထုတ်မေပးဘူး ဆိလ


ု တ
ို ယ်။ completely empty.

type paramName - တစ်ခုစီ၏ အမ င့် အ အစား


return; method တစ်ခုဟာ သူလပ


ု ်စရာ အ င်တစ်ခုခုကို လုပ်ေဆာ ။ တဲ့ ေနရာကို ြပန်သွား ေြပာတ အ မ်းဖျ ယူဆ ရတယ်။

a
a
သို့
ည်နှ
စ်နို
က်ရှ
မျိုး
နှ
လို့
စ်နို
င်ပြီး
ပြီ
ခေါ်သုံး
ဖို့
fi
ကြော
ယ်လို့
ကြ
ဉ်း
လို့
import [Link].*;
import [Link].*;

public class DrawAtCenter extends GraphicsProgram {


public void run() {
drawRectAtCenter(200, 100);
drawOvalAtCenter(200,100);
}

private void drawRectAtCenter(double width, double height) {


double x = (getWidth() - width) / 2.0;
double y = (getHeight() - height) / 2.0;
GRect rect = new GRect(x, y, width, height);
add(rect);
}

private void drawOvalAtCenter(double width, double height) {


double x = (getWidth() - width) / 2.0;
double y = (getHeight() - height) / 2.0;
GOval oval = new GOval(x, y, width, height);
add(oval);
}

}
import [Link].*;
import [Link].*;

import [Link].*;

public class RectAndOvalAtCenter extends GraphicsProgram {


public void run() {
GRect rect = createRectAtCenter(200, 100);
[Link](true);
[Link]([Link]);
add(rect);
}

private GRect createRectAtCenter(double width, double height) {


double x = (getWidth() - width) / 2.0;
double y = (getHeight() - height) / 2.0;
GRect rect = new GRect(x, y, width, height);
return rect;
}

private GOval createOvalAtCenter(double width, double height) {


double x = (getWidth() - width) / 2.0;
double y = (getHeight() - height) / 2.0;
GOval oval = new GOval(x, y, width, height);
return oval;
}
}
return statement

method de nition ထဲကေန method ကို ထားတဲ့ ေနရာကို ြပန်ေရာက်သွား return



statement ကို သံုးတယ်။

ပံုစံ ရတယ်

return exp; ကို တန်ဖိုးြပန်ေပးတဲ့ method ေတွမှာ သံုးတယ်။


return; ကို တန်ဖိုး ြပန်ထုတ်မေပးတဲ့ method (void methods) ေတွမှာ သံုးတယ်။


void methods ေတွ က်ဆးံု အ င်းက return statement ကို မထည့်ေရးလဲ ရတယ်။

နှ
စ်မျိုး
နဲ့
တွေ့
fi
ရဲ့
နော
ကြော
ခေါ်သုံး
ဖို့
Predicate Methods
import [Link];

public class PredicateMethods extends ConsoleProgram {


public void run() {
println(isNormalYear(2022));
println(isNormalYear(2024));
println(isLeapYear(2024));
}

private boolean isEven(int n) {


return (n % 2 == 0);
}

private boolean isOdd(int n) {


return !isEven(n);
}

private boolean isLeapYear (int year)


{
return(((year % 4 == 0)&&(year % 100 != 0)) || (year % 400 == 0));
}

private boolean isNormalYear(int year) {


return !isLeapYear(year);
}

}
Other terms for methods

တ programming language ေတွမှာ

‣ subroutine/routine
‣ procedure
‣ function
စတာေတွဟာ method ေတွ သေဘာတရား ခပ်ဆင်ဆင်တူတယ်။ အတိအကျ အဓိ ယ် သတ်မှတ်ရင်

တစ်ခု ကွားြခားချက်ေတွ ေပမဲ့ အေြခခံသေဘာတရားေတာ့ တူတူပဲ ေြပာ င်တယ်။


ချို့
နဲ့
နဲ့
ရှိ
လို့
ပ္ပါ
နို
Distinguishing Methods
static method

‣ [Link]()
‣ [Link]()
‣ [Link]()
public class MyMathFuns {
public static double abs(double val) {
double absVal = val < 0 ? -val : val; import [Link];
return absVal;
} public class MyMathFunsApply extends ConsoleProgram
{
public static double getLenOfHypotenuse(double a, double b) { public void run() {
double h = [Link](a * a + b * b); println([Link](-3));
return h; println([Link](10));
} }
}
public static double getLenOfOtherSide(double h, double a){
double b = [Link](h * h - a * a);
return b;
}

public static double min(double x, double y) {


if (x < y) {
return x;
} else {
return y;
}
}

public static int factorial(int n) {


int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
method call on objects

‣ GRect rect = new GRect(. . .);


‣ [Link]();
‣ [Link]();
‣ [Link]();
‣ [Link]();
method call on self

‣ Method declaration inside the class body (non static method)


‣ Call the method in the another method declaration in the same class
‣ Methods inherited from extended class
‣ add() method from GraphicsProgram class
Avoiding Deep Nesting
Think wh t e ch level of nesting does!

import [Link];

public class WedgeOfStars extends ConsoleProgram {

public void run() {


int initNumStars = readInt("Enter number of stars in 1st row: ");

int numStarsInTheRow = initNumStars;


for (int i = 0; i < initNumStars; i++) {
drawRowOfNStars(numStarsInTheRow);
println();
numStarsInTheRow--;
}
}

private void drawRowOfNStars(int n) {


for(int i = 0; i < n; i++) {
print("*");
}
}
}
a
a
Avoiding Deep Nesting
Think wh t e ch level of nesting does!
/*
* File: [Link]
* -----------------------
* This program draws a checkerboard. The dimensions of the
* checkerboard are specified by the constants N_ROWS and
* N_COLUMNS, and the size of the squares is chosen so
* that the checkerboard fills the available vertical space. */

import [Link].*;
import [Link].*;

public class Checkerboard extends GraphicsProgram {


public void run() {
double size = getHeight()/N_ROWS;
boolean isFilledFirst = false;
for(int i = 0; i < 8; i++) {
drawRow(size, i * size, N_COLUMNS, isFilledFirst );
isFilledFirst = !isFilledFirst;
}

private void drawRow(double size, double y, int cnt, boolean isFilledFirst) {


boolean isFilled = isFilledFirst;
for (int i = 0; i < cnt; i++) {
GRect rect = new GRect(i * size, y, size, size);
[Link](isFilled);
isFilled = !isFilled;
add(rect);
}
}
private static final int N_ROWS = 8;
private static final int N_COLUMNS = 8;
}
a
a
Calling Mechanism
with primitives parameters and arguments

import [Link].*;

public class IncNotWorking extends ConsoleProgram {

public void run() {


int x = 0;
increment(x);
println(x);
}

private void increment(int x) {


x++;
}
}
Calling Mechanism
with primitives parameters and arguments
import [Link].*;

parameters variables are also local


public class IncNotWorking extends ConsoleProgram {
to the method

public void run() { Parameters

x
int = 0;
int x
increment(x);

println(x);

}
x++
private void increment(int x) {

x++;
}
all variables inside the method
} declaration has local scope
Calling Mechanism
with primitives parameters and arguments
import [Link].*;

parameters variables are also local


public class IncNotWorking extends ConsoleProgram {
to the method

public void run() { Parameters


x
int = 0; value of x in run copied to x in increment
int x = 0
increment(x);

println(x);

}
x++
private void increment(int x) {

x++;
}
all variables inside the method
} declaration has local scope
Calling Mechanism
with object references param and arguments

public class RefAsParam extends GraphicsProgram {


public void run() {
double width = 200; parameters variables are also local
double height = 100; to the method
double x = (getWidth() - width)/2.0;
double y = (getHeight() - height)/2.0; Parameters

GRect rect = new GRect(x, y, width, height); Grect rect


setRedColor(rect);
add(rect); [Link](true)
} [Link]([Link])

private void setRedColor(GRect rect) {


[Link](true);
[Link]([Link]);
}
} all variables inside the method
declaration has local scope
Calling Mechanism
with object references param and arguments

public class RefAsParam extends GraphicsProgram {


public void run() {
double width = 200; parameters variables are also local
double height = 100; to the method
double x = (getWidth() - width)/2.0;
double y = (getHeight() - height)/2.0; Parameters

GRect rect = new GRect(x, y, width, height); Grect rect = rect


setRedColor(rect);
add(rect);
[Link](true)
value of rect in run copied to rect in setRedColor [Link]([Link])
}

private void setRedColor(GRect rect) {


[Link](true);
[Link]([Link]);
}
} all variables inside the method
declaration has local scope
x
y
Both rect and rect refer to the width
same rectangle object. height
setFilled
[Link]() and illColor
[Link]() will a ect the
same object.

public class RefAsParam extends GraphicsProgram {


public void run() {
... Parameters
GRect rect = new GRect(x, y, width, height);
Grect rect = rect
setRedColor(rect);
add(rect);
[Link](true)
}
[Link]([Link])
private void setRedColor(GRect rect) {
[Link](true);
[Link]([Link]);
}
}
f
ff

You might also like