Fภาษาจาวา แบ่งเมธอดออกเป็น 2 ประเภท
Fstatic method
•เป็นเมธอดที่มี keyword “static” หน้าชื่อ method
•method ที่เป็น static จะสามารถเรียกใช้งานได้ทันที โดยไม่ต้องสร้าง object ก็ได้ มีรูปแบบ
Classname.methodname
Finstance method
•เป็นเมธอดที่ไม่มี keyword “static” อยู่หน้าชื่อ method
•ถ้าต้องการจะเรียกใช้เมธอดนี้ ต้องทำการสร้าง object ก่อน แล้วจึงเรียกใช้ตามรูปแบบ
Objectname.methodname
Return value type
Fถ้าเมธอดนั้นไม่มีการส่งค่ากลับมา(ไม่มีประโยด return อยู่ในบรรทัดสุดท้ายของ method) return value type ต้องกำหนด keyword void
Fถ้าเมธอดนั้นมีการส่งค่ากลับ(มีประโยด return อยู่ในบรรทัดสุดท้ายของ method) ค่าที่จะส่งค่ากลับต้องกำหนดให้ตรงกับ return value type
Parameter List
Fเป็นชื่อของตัวแปรที่ใช้รับข้อมูลที่ argument ของ methodส่งออก เมื่อมีการเรียกใช้ method นั้น
Fถ้าไม่มีการส่งค่า argument มาจาก method ก็ไม่ต้องมี parameter list
Fกรณีมี parameter list มากกว่า 1 ตัว ใน method ต้องขั้นด้วย , (comma) ระหว่าง parameter list
FExample
static viod min(int a, int b)
static int min(int a, int b)
static void max()
Overloading Methods
Overloading the max Method
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
method substring()
Fการดึงข้อความบางส่วน(substring)
Fรูปแบบ msg.substring(n,m);
•เป็นการดึงข้อความตำแหน่งที่ n (เริ่มตำแหน่งแรกจะเริ่มนับที่ 0)โดยดึงมาจนถึงตำแหน่งที่ m - 1
•msg คือชื่อตัวแปร String Object ที่ต้องการดึงข้อความ
•substring คือชื่อของ method substring ซึ่งอยู่ใน class String
FExample
String message = “Technic Bangkok”;
String msg = message.substring(8,15)+”Campus”;
String msg = message.substring(0,7)+”Campus”;
Method length()
Fmethod length()
Fใช้หาความยาวของตัวแปร String
•รูปแบบ msg.length();
•msg คือตัวแปร String ที่ต้องการหาค่าความยาวของตัวแปร
•length() เป็น method ที่อยู่ใน class String
•Example
String input = “Campus”; //กำหนดค่าตัวแปร String ชื่อ input
int n = input.length(); //return n = 6
System.out.println(n);
Rounding Methods
Fdouble ceil(double x)
x rounded up to its nearest integer. This integer is returned as a double value.
Fdouble floor(double x)
x is rounded down to its nearest integer. This integer is returned as a double value.
Fint round(float x)
Return (int)Math.floor(x+0.5).
Flong round(double x)
Return (long)Math.floor(x+0.5).