JavaJava · Chapterبەش 8 · Lectureوانە 8.1
Methods, Parameters and Return Valuesمیتۆدەکان، پارامیتەرەکان و نرخە گەڕاوەکان
Write your own static methods in Java: define and call them, pass arguments into parameters (in order, as copies), return values with return and a return type, use the result in expressions, write boolean methods, trace a call by hand, and read the real javac messages for missing returns, void results, wrong arguments and missing static.
staticـی خۆت لە Javaـدا بنووسە: بیانناسێنە و بانگیان بکە، بنێرە بۆ (بە ڕیزبەندی و وەک کۆپی)، بە return و بگەڕێنەوە، ئەنجامەکە لە بەکار بهێنە، بنووسە، بانگکردنێک بە دەست بەدوادا بچۆ و پەیامە ڕاستەقینەکانی javac بخوێنەوە بۆ returnـی ونبوو، ئەنجامی void، هەڵە و staticـی ونبوو.
What you will learnچی فێر دەبیت
- Define a static method with a return type, a name and parameters, and call it from main.
- Tell parameters from arguments and pass arguments in the right order and types.
- Return values with return, use them in expressions, and make every path return.
- Trace a method call step by step and fix the usual javac errors about methods.
-
staticبە ، ناو و بناسێنیت و لە main بانگی بکەیت. - لە جیا بکەیتەوە و بە ڕیزبەندی و جۆری دروست بنێریت.
- بە
returnبگەڕێنیتەوە، لە بەکاریان بهێنیت و وا بکەیت هەموو ڕێگایەک بگەڕێتەوە. - بانگکردنی هەنگاو بە هەنگاو بەدوادا بچیت و هەڵە ئاساییەکانی javac لەبارەی چاک بکەیت.
Why methods?بۆچی میتۆدەکان؟
A is a block of code with a name. It does one job, and it runs only when you call it by its name. You have used methods since your first program: System.out.println(...) prints, Math.max(a, b) finds the larger number (Calling a Math method) and input.nextInt() reads a number. In this lesson you write your own.
کە ناوێکی هەیە. یەک کار دەکات و تەنیا کاتێک جێبەجێ دەبێت کە بە ناوەکەیەوە بانگی بکەیت. لە یەکەم بەکار دەهێنیت: System.out.println(...) چاپ دەکات، Math.max(a, b) ژمارە گەورەترەکە دەدۆزێتەوە (بانگکردنی میتۆدێکی Math) و input.nextInt() ژمارەیەک دەخوێنێتەوە. لەم وانەیەدا خۆت دەنووسیت.
Why bother? A method lets you name a job, write it once and reuse it from many places. main becomes short and easy to read, and when the job must change you change it in one place. In Java every method lives inside a class. Python calls the same idea a function (Defining and calling functions), and so does MATLAB (Function files).
بۆچی؟ ڕێگەت پێ دەدات ناو لە کارێک بنێیت، جارێک بینووسیت و لە چەندین شوێنەوە دووپاتە بەکاری بهێنیتەوە. main کورت و ئاسان دەبێت بۆ خوێندنەوە و کاتێک کارەکە دەبێت بگۆڕێت، تەنیا لە یەک شوێندا دەیگۆڕیت. لە Javaـدا هەموو لە ناو دەژی. Python هەمان بیرۆکە بە ناو دەبات (ناساندن و بانگکردنی کردارەکان) و MATLABـیش هەروەها (فایلی کردار).
Why methods?بۆچی میتۆدەکان؟
Small jobs: decompositionکاری بچووک: پارچەکردن
A big program is easier to write as many small methods, each with one clear job. This is : split the problem into parts, solve each part, then join the parts (Decomposition: divide and conquer). In a marks report, main only gives orders; three methods do the work:
گەورە ئاسانتر دەنووسرێت ئەگەر بکرێتە چەندین بچووک، هەریەکەیان بە یەک کاری ڕوون. ئەمە : کێشەکە بکە بە چەند بەشێک، هەر بەشێک چارەسەر بکە و پاشان بەشەکان پێکەوە ببەستە (پارچەکردن: دابەشی بکە و زاڵ بە). لە ڕاپۆرتێکی نمرەدا main تەنیا فەرمان دەدات؛ سێ کارەکە دەکەن:
Good method names say what the job is: a verb in camelCase, such as printHeader, average or isEven (Java's naming conventions).
ناوی باشی دەڵێت کارەکە چییە: وشەیەکی کاری بە ، وەک printHeader، average یان isEven (ڕێککەوتنەکانی ناونانی Java).
Your first methodیەکەم میتۆدی خۆت
A function that belongs to an or . PHP calls it with -> ($result->fetch_assoc()); Python uses a dot (frontier.append(node)).
بریتییە لە کە سەر بە یان دەبێت. PHP بە -> بانگی دەکات ($result->fetch_assoc())؛ Python خاڵ بەکاردەهێنێت (frontier.append(node)).
Here is a complete program with one method of our own. static void printWelcome() defines the method; the statement printWelcome(); inside main calls it:
ئەمە تەواوە بە یەک خۆمان. static void printWelcome() دەناسێنێت؛ printWelcome(); لە ناو mainـدا بانگی دەکات:
public class FirstMethod {
public static void main(String[] args) {
System.out.println("Start of main");
printWelcome();
System.out.println("End of main");
}
static void printWelcome() {
System.out.println("Welcome to Java methods!");
System.out.println("A method is a named block of code.");
}
}$ java FirstMethod Start of main Welcome to Java methods! A method is a named block of code. End of main
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
The call: the method's name, brackets and a semicolon.
بانگکردنەکە: ناوی ، کەوانە و .
- Lineدێڕی 8
static: the method belongs to the class, somaincan call it without an object.void: it gives nothing back.(): it takes no values.static: سەر بە ، بۆیەmainبەبێ بانگی دەکات.void: هیچ ناگەڕێنێتەوە.(): هیچ وەرناگرێت.- Lineدێڕی 9-10
The body: the statements between
{and}.: هەموو نێوان
{و}.
The method stands after main, and that is fine: the compiler reads the whole class before anything runs, so the order of methods in a class does not matter. (In Python a function must be defined before the line that calls it runs — Define first, then call.)
دوای main نووسراوە و ئەمە کێشە نییە: پێش جێبەجێبوونی هەر شتێک هەموو دەخوێنێتەوە، بۆیە ڕیزبەندیی لە گرنگ نییە. (لە Pythonـدا دەبێت پێش جێبەجێبوونی ئەو دێڕەی بانگی دەکات ناسێنرابێت — سەرەتا بیناسێنە، پاشان بانگی بکە.)
Your first methodیەکەم میتۆدی خۆت
Call it again and againدووپاتە و دووپاتە بانگی بکە
Once a method exists, you can call it as often as you like. Banner prints the same line three times with three short calls instead of three copies of the line:
کاتێک هەبوو، دەتوانیت هەر چەند جار بتەوێت بانگی بکەیت. Banner هەمان دێڕ سێ جار چاپ دەکات، بە سێ بانگکردنی کورت لە جیاتی سێ کۆپیی دێڕەکە:
public class Banner {
public static void main(String[] args) {
printLine();
System.out.println(" Hawler Book Fair");
printLine();
System.out.println(" Open 9:00 to 21:00");
printLine();
}
static void printLine() {
System.out.println("======================");
}
}$ java Banner ====================== Hawler Book Fair ====================== Open 9:00 to 21:00 ======================
A method can also call another method. Here printHeader calls printLine twice, and main calls both. When a method ends, the program returns to the method that called it, its :
دەتوانێت بانگی تریش بکات. لێرەدا printHeader دوو جار بانگی printLine دەکات و main بانگی هەردووکیان دەکات. کاتێک تەواو دەبێت، دەگەڕێتەوە بۆ ئەو بانگی کردووە، واتە :
public class Header {
public static void main(String[] args) {
printHeader();
System.out.println(" Today: Java methods");
printLine();
}
static void printHeader() {
printLine();
System.out.println(" CeIT Java course");
printLine();
}
static void printLine() {
System.out.println("----------------------");
}
}$ java Header ---------------------- CeIT Java course ---------------------- Today: Java methods ----------------------
Parameters and argumentsپارامیتەرەکان و ئارگیومێنتەکان
Most jobs need some information: whom to greet, which number to square. A method receives it through : variables in the brackets of its header, each with a type. The values you write in the brackets of a call are the . At the call, each parameter gets its argument's value:
زۆربەی کارەکان پێویستیان بە زانیارییە: سڵاو لە کێ بکرێت، دووجای کام ژمارە بدۆزرێتەوە. ئەم زانیارییە لە ڕێگەی وەردەگرێت: ئەو لە کەوانەی سەردێڕەکەیدا نووسراون، هەریەکەیان بە جۆرێکەوە. ئەو لە کەوانەی بانگکردنێکدا دەینووسیت . کاتێک بانگکردنەکە جێبەجێ دەبێت، هەر وەردەگرێت:
public class Greet {
public static void main(String[] args) {
greet("Aram");
greet("Shilan");
String friend = "Karwan";
greet(friend);
greet("Rebin and " + friend);
}
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}$ java Greet Hello, Aram! Hello, Shilan! Hello, Karwan! Hello, Rebin and Karwan!
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3-7
Four calls, four arguments: two literals, a variable and an expression. Java works out the value first and passes the value.
چوار بانگکردن، چوار : دوو ، و . Java سەرەتا دەدۆزێتەوە و پاشان دەنێرێت.
- Lineدێڕی 10
String nameis the parameter: inside the method it is an ordinary local variable.String name: لە ناو ئاساییە.
An everyday picture: at the bakery the baker's order form has an empty slot "how many loaves: ___". The slot is the parameter; the 5 you say is the argument. The method gets a copy of the value, so changing the parameter never changes the caller's variable (Java passes a copy of the value). For an array the copy points to the same array (Arrays and methods).
وێنەیەکی ڕۆژانە: لە نانەواخانەدا فۆڕمی داواکاریی نانەواکە شوێنێکی چۆڵی هەیە: «چەند نان: ___». ئەو شوێنە چۆڵە ؛ ئەو 5ـەی دەیڵێیت . کۆپییەکی وەردەگرێت، بۆیە گۆڕینی هەرگیز ناگۆڕێت (Java کۆپییەکی نرخەکە دەنێرێت). بۆ کۆپییەکە بۆ هەمان (ڕیزەکەکان و میتۆدەکان).
Parameters and argumentsپارامیتەرەکان و ئارگیومێنتەکان
Several parameters: order mattersچەند پارامیتەرێک: ڕیزبەندی گرنگە
Separate several parameters with commas, each with its own type. A call must give the same number of arguments, of fitting types, in the same order: the first argument goes to the first parameter, the second to the second. The names do not matter at all.
چەند بە کۆما لێک جیا بکەرەوە، هەریەکەیان بە جۆری خۆی. بانگکردنێک دەبێت هەمان ژمارە بدات، بە جۆری گونجاو و بە هەمان ڕیزبەندی: یەکەم دەچێتە یەکەم و دووەم بۆ دووەم. ناوەکان هیچ گرنگ نین.
public class MarkReport {
public static void main(String[] args) {
printMark("Aram", 85);
printMark("Shilan", 92);
}
static void printMark(String name, int mark) {
System.out.println(name + " got " + mark + " out of 100");
}
}$ java MarkReport Aram got 85 out of 100 Shilan got 92 out of 100
When two parameters have the same type, swapped arguments still compile, but the answer is wrong. javac cannot know that you meant 2 to the power 10:
کاتێک دوو هەمان جۆریان هەبێت، ئەگەر ئاڵوگۆڕ بکرێن هەر کۆمپایل دەبێت، بەڵام وەڵامەکە هەڵەیە. javac ناتوانێت بزانێت مەبەستت 2 بە 10 بووە:
public class PowerOrder {
public static void main(String[] args) {
printPower(2, 10);
printPower(10, 2);
}
static void printPower(int base, int exponent) {
long result = 1;
for (int i = 1; i <= exponent; i++) {
result = result * base;
}
System.out.println(base + " to the power " + exponent + " = " + result);
}
}$ java PowerOrder 2 to the power 10 = 1024 10 to the power 2 = 100
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 9-11
A
forloop multipliesresultbybase,exponenttimes (The for loop).resultلەbaseدەدات، بە ژمارەیexponentجار (خولی for).
Parameters and argumentsپارامیتەرەکان و ئارگیومێنتەکان
When the arguments do not fitکاتێک ئارگیومێنتەکان ناگونجێن
javac checks every call against the method's parameter list. Arguments in the wrong order give a short message; with -Xdiags:verbose it shows the whole check, required against found:
javac هەموو بانگکردنێک بەراورد دەکات لەگەڵ لیستی . بە ڕیزبەندیی هەڵە پەیامێکی کورت دەدەن؛ بە -Xdiags:verbose هەموو پشکنینەکە پیشان دەدات، required بەرامبەر found:
public class MarkOrder {
public static void main(String[] args) {
printMark(85, "Aram");
}
static void printMark(String name, int mark) {
System.out.println(name + " got " + mark + " out of 100");
}
}$ javac MarkOrder.java
MarkOrder.java:3: error: incompatible types: int cannot be converted to String
printMark(85, "Aram");
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorjavac -Xdiags:verbose MarkOrder.java$ javac -Xdiags:verbose MarkOrder.java
MarkOrder.java:3: error: method printMark in class MarkOrder cannot be applied to given types;
printMark(85, "Aram");
^
required: String,int
found: int,String
reason: argument mismatch; int cannot be converted to String
1 errorToo few (or too many) arguments: the method cannot be applied to given types, because the two lists differ in length:
کەمتر (یان زیاتر): cannot be applied to given types، چونکە درێژیی دوو لیستەکە جیاوازە:
public class MarkCount {
public static void main(String[] args) {
printMark("Aram");
}
static void printMark(String name, int mark) {
System.out.println(name + " got " + mark + " out of 100");
}
}$ javac MarkCount.java
MarkCount.java:3: error: method printMark in class MarkCount cannot be applied to given types;
printMark("Aram");
^
required: String,int
found: String
reason: actual and formal argument lists differ in length
1 errorAnd in the header, every parameter needs its own type: (int width, height) stops at height with <identifier> expected. Write (int width, int height).
لە سەردێڕیشدا هەموو پێویستی بە جۆری خۆی هەیە: (int width, height) لە heightـدا دەوەستێت و <identifier> expected دەدات. بنووسە (int width, int height).
public class ParamType {
public static void main(String[] args) {
printRect(4, 3);
}
static void printRect(int width, height) {
System.out.println(width + " x " + height);
}
}$ javac ParamType.java
ParamType.java:6: error: <identifier> expected
static void printRect(int width, height) {
^
1 errorParameters and argumentsپارامیتەرەکان و ئارگیومێنتەکان
A method with if … elseمیتۆدێک بە if … else
A method body can hold any statements: decisions, loops, calls. checkMark decides with if … else (Two ways: if … else); in the second program the argument comes from the keyboard (Two lines get a Scanner ready):
دەتوانێت هەر لە خۆ بگرێت: بڕیار، ، بانگکردن. checkMark بە if … else بڕیار دەدات (دوو ڕێگا: if … else)؛ لە دووەمدا لە دێت (دوو دێڕ Scanner ئامادە دەکەن):
public class CheckMark {
public static void main(String[] args) {
checkMark(72);
checkMark(45);
checkMark(50);
}
static void checkMark(int mark) {
if (mark >= 50) {
System.out.println(mark + ": pass");
} else {
System.out.println(mark + ": fail, try again");
}
}
}$ java CheckMark 72: pass 45: fail, try again 50: pass
import java.util.Scanner;
public class CheckMarkInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Your mark: ");
int mark = input.nextInt();
checkMark(mark);
}
static void checkMark(int mark) {
if (mark >= 50) {
System.out.println(mark + ": pass");
} else {
System.out.println(mark + ": fail, try again");
}
}
}$ java CheckMarkInput Your mark: 64 64: pass $ java CheckMarkInput Your mark: 38 38: fail, try again
Returning a valueگەڕاندنەوەی نرخێک
Some methods do not print anything; they work out a value and hand it back to the code that called them. Two changes do this: write the instead of void (here int), and finish with return and the value. The call then has that value, the , and can stand wherever a value of that type may stand:
هەندێک هیچ چاپ ناکەن؛ دەدۆزنەوە و دەیدەنەوە بەو کۆدەی بانگی کردوون. دوو گۆڕانکاری ئەمە دەکەن: لە جیاتی void بنووسە (لێرەدا int) و بە return و کۆتایی پێ بهێنە. ئیتر بانگکردنەکە ئەو هەیە () و دەتوانێت لە هەر شوێنێک بێت کە ئەو جۆرە دەتوانێت لێی بێت:
public class SquareDemo {
public static void main(String[] args) {
int result = square(7);
System.out.println("square(7) = " + result);
System.out.println("square(3) + square(4) = " + (square(3) + square(4)));
System.out.println("square(square(2)) = " + square(square(2)));
}
static int square(int n) {
return n * n;
}
}$ java SquareDemo square(7) = 49 square(3) + square(4) = 25 square(square(2)) = 16
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
The call
square(7)becomes 49, which is stored inresult.بانگکردنی
square(7)دەبێتە 49 و لەresultـدا هەڵدەگیرێت.- Lineدێڕی 10-12
intbefore the name is the return type;return n * n;hands the value back.intـی پێش ناوەکە ؛return n * n;دەداتەوە.


Returning a valueگەڕاندنەوەی نرخێک
The parts of a methodبەشەکانی میتۆدێک
Every method you write in this course has the same five parts:
هەموو ئەو لەم کۆرسەدا دەینووسیت هەمان پێنج بەشیان هەیە:
static، ، ناو، و CêITstatic(a modifier): the method belongs to the class.mainalso haspublic; the other modifiers come with classes (Constructors, modifiers and encapsulation).- The :
void, or the type of the value that comes back (int,double,boolean,String…). - The name, then the parameter list in brackets (empty brackets when there are none). Together they are the first line, the .
- The body in braces
{ }: the statements that run at every call.
static: سەر بە .mainpublicـیشی هەیە؛ وشەکانی تری لەم جۆرە لەگەڵ دێن (دروستکەرەکان و کەپسوولکردن).- :
void، یان جۆری ئەو دەگەڕێتەوە (int،double،boolean،String…). - ناو، پاشان لیستی لە ناو کەوانەدا (کەوانەی بەتاڵ کاتێک هیچ نییە). پێکەوە یەکەم دێڕن، واتە .
- لە ناو
{ }ـدا: ناوی لە هەر بانگکردنێکدا جێبەجێ دەبن.
The name with the parameter types, square(int), is the method's . It matters when several methods share one name (The signature).
ناوەکە لەگەڵ جۆری ، square(int)، . ئەمە گرنگ دەبێت کاتێک چەند یەک ناویان هەیە (واژووی کردار).
Returning a valueگەڕاندنەوەی نرخێک
Using the returned valueبەکارهێنانی نرخی گەڕاوە
A returned value can be stored in a variable, tested in an if, printed, or passed straight to another method. Storing it first, as in double avg = average(85, 92);, usually makes code easier to read:
دەتوانرێت لە هەڵبگیرێت، لە ifـێکدا تاقی بکرێتەوە، چاپ بکرێت، یان ڕاستەوخۆ بنێردرێت بۆ تر. هەڵگرتنی لە سەرەتادا، وەک double avg = average(85, 92);، زۆرجار خوێندنەوەی کۆدەکە ئاسانتر دەکات:
public class Average {
public static void main(String[] args) {
double avg = average(85, 92);
System.out.println("Average: " + avg);
if (average(48, 56) >= 50) {
System.out.println("48 and 56: passed on average");
}
System.out.println(Math.max(average(70, 80), average(90, 61)));
}
static double average(int a, int b) {
return (a + b) / 2.0;
}
}$ java Average Average: 88.5 48 and 56: passed on average 75.5
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 11
Dividing by
2.0, not2, keeps the half: 177 / 2.0 = 88.5.دابەشکردن بەسەر
2.0، نەک2، نیوەکە دەهێڵێتەوە: 177 / 2.0 = 88.5.
A returned value can also be ignored: square(5); alone compiles and runs, but the 25 is lost and nothing is printed. If you want the value, use it.
دەتوانرێت پشتگوێ بخرێت: square(5); بە تەنیا کۆمپایل و جێبەجێ دەبێت، بەڵام 25ـەکە ون دەبێت و هیچ چاپ ناکرێت. ئەگەر دەوێت، بەکاری بهێنە.
public class Ignored {
public static void main(String[] args) {
square(5);
System.out.println("Nothing was printed for square(5).");
}
static int square(int n) {
return n * n;
}
}$ java Ignored Nothing was printed for square(5).
Returning a valueگەڕاندنەوەی نرخێک
Two kinds of methodsدوو جۆری میتۆد
A does a job, such as printing, and gives nothing back: you call it as a statement on its own. A works out a value and hands it back: you use the call as a value. Printing a result is not returning it (the same difference as in Python — print or return).
کارێک دەکات (وەک چاپکردن) و هیچ ناگەڕێنێتەوە: وەک سەربەخۆ بانگی دەکەیت. دەدۆزێتەوە و دەیداتەوە: بانگکردنەکەی وەک بەکار دەهێنیت. چاپکردنی ئەنجامێک گەڕاندنەوەی نییە (هەمان جیاوازیی Python — print یان return).
A void method has no value to use, and a void method may not return one. javac stops both mistakes:
هیچ نییە بۆ بەکارهێنان و ناشتوانێت بگەڕێنێتەوە. javac ڕێگری لە هەردوو هەڵەکە دەکات:
public class VoidResult {
public static void main(String[] args) {
int x = printLine();
System.out.println(printLine());
}
static void printLine() {
System.out.println("----------");
}
}$ javac VoidResult.java
VoidResult.java:3: error: incompatible types: void cannot be converted to int
int x = printLine();
^
VoidResult.java:4: error: 'void' type not allowed here
System.out.println(printLine());
^
2 errorspublic class VoidReturn {
public static void main(String[] args) {
printLine();
}
static void printLine() {
System.out.println("----------");
return 5;
}
}$ javac VoidReturn.java
VoidReturn.java:8: error: incompatible types: unexpected return value
return 5;
^
1 errorReturning a valueگەڕاندنەوەی نرخێک
return ends the method at oncereturn یەکسەر میتۆدەکە کۆتایی پێ دەهێنێت
return does two things: it hands back the value and leaves the method immediately. So a method may have several return statements, one on each path, and a void method may use a plain return; to stop early:
return دوو کار دەکات: دەداتەوە و یەکسەر لە دەردەچێت. بۆیە دەتوانێت چەند returnـێکی هەبێت، یەکێک لە هەر ڕێگایەک و دەتوانێت return;ـی ڕووت بەکار بهێنێت بۆ ئەوەی زوو بوەستێت:
public class MaxDemo {
public static void main(String[] args) {
System.out.println(max(8, 3));
System.out.println(max(-2, 5));
printRatio(7, 2);
printRatio(7, 0);
}
static int max(int a, int b) {
if (a > b) {
return a;
}
return b;
}
static void printRatio(int a, int b) {
if (b == 0) {
System.out.println("Cannot divide " + a + " by zero");
return;
}
System.out.println(a + " / " + b + " = " + (double) a / b);
}
}$ java MaxDemo 8 5 7 / 2 = 3.5 Cannot divide 7 by zero
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 10-13
If
a > b, the method ends atreturn a;and line 13 never runs for that call.ئەگەر
a > bبێت، لەreturn a;ـدا کۆتایی دێت و دێڕی 13 بۆ ئەو بانگکردنە هەرگیز جێبەجێ نابێت.- Lineدێڕی 17-20
return;without a value leaves the void method before the division.return;بەبێ پێش دابەشکردنەکە لە دەردەچێت.
A statement straight after a return in the same block could never run, so javac refuses it:
ڕاستەوخۆ دوای return لە هەمان هەرگیز جێبەجێ نابێت، بۆیە javac ڕەتی دەکاتەوە:
public class Unreachable {
public static void main(String[] args) {
System.out.println(square(4));
}
static int square(int n) {
return n * n;
System.out.println("square done");
}
}$ javac Unreachable.java
Unreachable.java:8: error: unreachable statement
System.out.println("square done");
^
1 errorReturning a valueگەڕاندنەوەی نرخێک
Every path must return a valueهەموو ڕێگایەک دەبێت نرخێک بگەڕێنێتەوە
A method with a return type must not reach its closing brace without a return. The compiler follows every path through the body; if one can fall off the end, it stops with missing return statement (Java Language Specification §8.4.7):
کە هەیە نابێت بەبێ return بگاتە کەوانەی داخستنی. بەدوای هەموو ڕێگایەکی ناو دەچێت؛ ئەگەر یەکێکیان بتوانێت بەبێ return بگاتە کۆتایی، بە missing return statement دەوەستێت (Java Language Specification §8.4.7):
public class MissingReturn {
public static void main(String[] args) {
System.out.println(result(72));
}
static String result(int mark) {
if (mark >= 50) {
return "pass";
}
}
}$ javac MissingReturn.java
MissingReturn.java:10: error: missing return statement
}
^
1 errorSurprisingly, adding else if (mark < 50) is still not enough. You can see that the two conditions cover every mark, but javac does not work out conditions; it only sees an if that may be false at the end:
سەیرە، زیادکردنی else if (mark < 50) هێشتا بەس نییە. تۆ دەبینیت کە دوو هەموو نمرەیەک دەگرنەوە، بەڵام javac لێک نادات؛ تەنیا ifـێک دەبینێت کە لە کۆتاییدا دەشێت هەڵە بێت:
public class MissingReturn2 {
public static void main(String[] args) {
System.out.println(result(72));
}
static String result(int mark) {
if (mark >= 50) {
return "pass";
} else if (mark < 50) {
return "fail";
}
}
}$ javac MissingReturn2.java
MissingReturn2.java:12: error: missing return statement
}
^
1 errorpublic class ResultFixed {
public static void main(String[] args) {
System.out.println(result(72));
System.out.println(result(45));
}
static String result(int mark) {
if (mark >= 50) {
return "pass";
} else {
return "fail";
}
}
}$ java ResultFixed pass fail
Methods that answer yes or noئەو میتۆدانەی وەڵامی بەڵێ یان نەخێر دەدەنەوە
A method can return a boolean. Such methods usually start with is or has and read like a question in an if: if (isEven(n)). The body can simply return the comparison, which is already true or false (true or false: boolean expressions):
دەتوانێت booleanـێک بگەڕێنێتەوە. ئەم جۆرە زۆرجار بە is یان has دەست پێ دەکەن و لە ناو ifـدا وەک پرسیارێک دەخوێنرێنەوە: if (isEven(n)). دەتوانێت ڕاستەوخۆ بەراوردەکە بگەڕێنێتەوە، کە خۆی true یان falseـە (true یان false: دەربڕینی بوولیان):
public class EvenTest {
public static void main(String[] args) {
for (int n = 1; n <= 5; n++) {
if (isEven(n)) {
System.out.println(n + " is even");
} else {
System.out.println(n + " is odd");
}
}
System.out.println("isEven(10) = " + isEven(10));
System.out.println("isEven(-4) = " + isEven(-4));
}
static boolean isEven(int n) {
return n % 2 == 0;
}
}$ java EvenTest 1 is odd 2 is even 3 is odd 4 is even 5 is odd isEven(10) = true isEven(-4) = true
A longer if (n % 2 == 0) { return true; } else { return false; } gives the same answers (real run: true true, false false), but return n % 2 == 0; says it in one line.
if (n % 2 == 0) { return true; } else { return false; }ـی درێژتر هەمان وەڵام دەدات (جێبەجێکردنی ڕاستەقینە: true true، false false)، بەڵام return n % 2 == 0; بە یەک دێڕ دەیڵێت.
Tracing a call by handبەدواداچوونی بانگکردنێک بە دەست
To trace a call, follow four steps: (1) Java works out the arguments; (2) it creates the method's parameters and copies the values into them; (3) the body runs with its own local variables; (4) return hands the value back, the method's variables disappear, and the caller goes on. Here is a small tea-house bill:
بۆ بەدواداچوونی بانگکردنێک چوار هەنگاو بگرە: (1) Java دەدۆزێتەوە؛ (2) دروست دەکات و کۆپی دەکاتە ناویان؛ (3) بە خۆی جێبەجێ دەبێت؛ (4) return دەداتەوە، نامێنن و بەردەوام دەبێت. ئەمە پسوولەیەکی بچووکی چایخانەیە:
public class TeaBill {
public static void main(String[] args) {
int teas = 3;
int bill = price(teas, 500);
System.out.println("Bill: " + bill + " dinars");
}
static int price(int count, int each) {
int total = count * each;
return total;
}
}$ java TeaBill Bill: 1500 dinars
| Lineدێڕ | What happensچی ڕوو دەدات | mainmain | priceprice |
|---|---|---|---|
| 3 | teas is createdteas دروست دەکرێت | teas = 3 | |
| 4 | the call price(teas, 500) startsبانگکردنی price(teas, 500) دەست پێ دەکات | teas = 3 | count = 3, each = 500 |
| 9 | the body multiplies لێکدان دەکات | teas = 3 | count = 3, each = 500, total = 1500 |
| 10 | return total; hands back 1500return total; 1500 دەداتەوە | teas = 3 | goneنەماوە |
| 4 | bill gets 1500bill دەبێتە 1500 | teas = 3, bill = 1500 | |
| 5 | prints the billپسوولەکە چاپ دەکات | teas = 3, bill = 1500 |
Behind the scenes Java keeps one frame per running call on the ; you will meet it with recursion (The call stack). For practice with loops, try the trace lab and Checking with a trace table.
لە پشتەوە Java بۆ هەر بانگکردنێکی کارا چوارچێوەیەک لەسەر هەڵدەگرێت؛ لەگەڵ دەیبینیت (ستاکی بانگکردن). بۆ ڕاهێنان لەسەر ، تاقیگەی بەدواداچوون و پشکنین بە خشتەی بەدواداچوون تاقی بکەرەوە.
main is a method toomainـیش میتۆدێکە
public static void main(String[] args) is a method like the others: void because it returns nothing, static because the JVM calls it without an object, and String[] args is its parameter (The main method). The JVM calls it; main calls your methods.
public static void main(String[] args) وەک ئەوانی تر: voidـە چونکە هیچ ناگەڕێنێتەوە، staticـە چونکە JVM بەبێ بانگی دەکات و String[] args (کرداری main). JVM بانگی دەکات؛ main بانگی تۆ دەکات.
Two rules follow. A method is never written inside another method, and never outside the class. Each mistake gives a confusing message, because javac no longer understands the structure:
دوو یاسا لێرەوە دێن. هەرگیز لە ناو تردا نانووسرێت و هەرگیز لە دەرەوەی . هەر هەڵەیەک پەیامێکی تێکەڵ دەدات، چونکە javac ئیتر پێکهاتەکە تێناگات:
public class Nested {
public static void main(String[] args) {
static void printLine() {
System.out.println("----------");
}
printLine();
}
}$ javac Nested.java
Nested.java:3: error: illegal start of expression
static void printLine() {
^
Nested.java:6: error: invalid method declaration; return type required
printLine();
^
Nested.java:8: error: class, interface, enum, or record expected
}
^
3 errorspublic class Outside {
public static void main(String[] args) {
printLine();
}
}
static void printLine() {
System.out.println("----------");
}$ javac Outside.java
Outside.java:7: error: class, interface, enum, or record expected
static void printLine() {
^
Outside.java:9: error: class, interface, enum, or record expected
}
^
2 errorsmain is a method toomainـیش میتۆدێکە
The methods main calls are staticئەو میتۆدانەی main بانگیان دەکات staticـن
Keep static on the methods that main calls. Without it the method belongs to an object, and a static main has no object to call it on — objects and instance methods come later (A static method has no object):
static لەسەر ئەو بهێڵەوە کە main بانگیان دەکات. بەبێ ئەو سەر بە دەبێت و mainـی static هیچ نییە تا لەسەری بانگی بکات — و دواتر دێن (میتۆدێکی static هیچ ئۆبجێکتێکی نییە):
public class NonStatic {
public static void main(String[] args) {
printLine();
}
void printLine() {
System.out.println("----------");
}
}$ javac NonStatic.java
NonStatic.java:3: error: non-static method printLine() cannot be referenced from a static context
printLine();
^
1 errorCommon mistakesهەڵە باوەکان
| You wroteنووسیت | What happensچی ڕوو دەدات | Fixچارەسەر |
|---|---|---|
no return on one pathreturn لە یەک ڕێگادا نییە | missing return statement | Return on every path; end with else or a last return.لە هەموو ڕێگایەکدا بگەڕێنەوە؛ بە else یان دوا returnـێک کۆتایی پێ بهێنە. |
int x = printLine(); | void cannot be converted to int | A void method has no value; call it on its own. نییە؛ بە تەنیا بانگی بکە. |
return n / 2.0; | in an int method: possible lossy conversion from double to intلە intـدا: possible lossy conversion from double to int | Make the return type double, or return an int. بکە بە double، یان intـێک بگەڕێنەوە. |
square("7") | String cannot be converted to int | Pass a value of the parameter's type. بە جۆری بنێرە. |
printMark("Aram") | cannot be applied to given types | Give every parameter an argument, in order.بە ڕیزبەندی بۆ هەموو بدە. |
static void box(int w, h) | <identifier> expected | Write a type for each parameter.بۆ هەر جۆرێک بنووسە. |
static void printLine(); { | missing method body, or declare abstract | No semicolon after the header.هیچ لە دوای سەردێڕەکە نەبێت. |
no static on a method main callsبێ static لەسەر کە main بانگی دەکات | non-static method … cannot be referenced from a static context | Add static.static زیاد بکە. |
a statement after return لە دوای return | unreachable statement | Delete it or move it before the return.بیسڕەوە یان بیبە پێش return. |
return (a + b) / 2; | 88.0 instead of 88.588.0 لە جیاتی 88.5 | Divide by 2.0.بەسەر 2.0ـدا دابەش بکە. |
The real messages of rows 3, 7 and one var mistake (var works for local variables only — Let the compiler find the type: var — never for parameters):
پەیامە ڕاستەقینەکانی ڕیزەکانی 3 و 7 و هەڵەیەکی var (var تەنیا بۆ کار دەکات — با کۆمپایلەرەکە جۆرەکە بدۆزێتەوە: var — هەرگیز بۆ نا):
$ javac WrongReturn.java
WrongReturn.java:8: error: incompatible types: possible lossy conversion from double to int
return n / 2.0;
^
WrongReturn.java:12: error: incompatible types: String cannot be converted to int
return "Aram";
^
2 errors
$ javac HeaderSemicolon.java
HeaderSemicolon.java:6: error: missing method body, or declare abstract
static void printLine(); {
^
1 error
$ javac VarParam.java
VarParam.java:6: error: 'var' is not allowed here
static int twice(var n) {
^
1 errorPracticeڕاهێنان
Write static void printStars(int n) that prints n stars on one line. Call it in a loop to print a triangle of 1 to 4 stars.
static void printStars(int n) بنووسە کە n ئەستێرە لە یەک دێڕدا چاپ بکات. لە بانگی بکە بۆ چاپکردنی سێگۆشەیەک لە 1 تا 4 ئەستێرە.
Hintئاماژە
Use print inside the loop and println() at the end.
لە ناو print و لە کۆتاییدا println() بەکار بهێنە.
Show answerوەڵامەکە پیشان بدە
public class Stars {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
printStars(row);
}
}
static void printStars(int n) {
for (int i = 1; i <= n; i++) {
System.out.print("*");
}
System.out.println();
}
}$ java Stars * ** *** ****
Write static double toFahrenheit(double celsius) using . Test 0, 37, 100 and -40.
static double toFahrenheit(double celsius) بنووسە بە . 0، 37، 100 و -40 تاقی بکەرەوە.
Show answerوەڵامەکە پیشان بدە
public class Fahrenheit {
public static void main(String[] args) {
System.out.println(toFahrenheit(0));
System.out.println(toFahrenheit(37));
System.out.println(toFahrenheit(100));
System.out.println(toFahrenheit(-40));
}
static double toFahrenheit(double celsius) {
return celsius * 9 / 5 + 32;
}
}$ java Fahrenheit 32.0 98.6 212.0 -40.0
-40 is the one temperature that is the same on both scales.
-40 تاکە پلەیە کە لە هەردوو پێوەرەکەدا وەک یەکە.
Write max3(int a, int b, int c) that uses a two-number max method twice.
max3(int a, int b, int c) بنووسە کە دوو جار maxـی دوو ژمارە بەکار بهێنێت.
Show answerوەڵامەکە پیشان بدە
public class MaxOfThree {
public static void main(String[] args) {
System.out.println(max3(4, 9, 7));
System.out.println(max3(-1, -8, -3));
System.out.println(max3(5, 5, 2));
}
static int max3(int a, int b, int c) {
return max(max(a, b), c);
}
static int max(int a, int b) {
if (a > b) {
return a;
}
return b;
}
}$ java MaxOfThree 9 -1 5
Write static boolean isLeapYear(int year): a year is a leap year if it can be divided by 4 but not by 100, or if it can be divided by 400. Test 2024, 2026, 1900 and 2000.
static boolean isLeapYear(int year) بنووسە: ساڵێک کەبیسەیە ئەگەر بەسەر 4ـدا دابەش بێت بەڵام بەسەر 100ـدا نا، یان ئەگەر بەسەر 400ـدا دابەش بێت. 2024، 2026، 1900 و 2000 تاقی بکەرەوە.
Show answerوەڵامەکە پیشان بدە
public class LeapYear {
public static void main(String[] args) {
System.out.println("2024: " + isLeapYear(2024));
System.out.println("2026: " + isLeapYear(2026));
System.out.println("1900: " + isLeapYear(1900));
System.out.println("2000: " + isLeapYear(2000));
}
static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
}$ java LeapYear 2024: true 2026: false 1900: false 2000: true
Write static char grade(int mark): A from 90, B from 80, C from 70, D from 50, otherwise F.
static char grade(int mark) بنووسە: A لە 90ـەوە، B لە 80ـەوە، C لە 70ـەوە، D لە 50ـەوە، ئەگینا F.
Show answerوەڵامەکە پیشان بدە
public class LetterGrade {
public static void main(String[] args) {
System.out.println("95 -> " + grade(95));
System.out.println("83 -> " + grade(83));
System.out.println("71 -> " + grade(71));
System.out.println("50 -> " + grade(50));
System.out.println("49 -> " + grade(49));
}
static char grade(int mark) {
if (mark >= 90) {
return 'A';
} else if (mark >= 80) {
return 'B';
} else if (mark >= 70) {
return 'C';
} else if (mark >= 50) {
return 'D';
} else {
return 'F';
}
}
}$ java LetterGrade 95 -> A 83 -> B 71 -> C 50 -> D 49 -> F
This program has two mistakes. Find both before you compile it.
ئەم دوو هەڵەی تێدایە. پێش کۆمپایلکردن هەردووکیان بدۆزەرەوە.
public class Bugs {
public static void main(String[] args) {
int total = add(3, "4");
System.out.println(total);
}
static int add(int a, int b) {
int sum = a + b;
}
}$ javac Bugs.java
Bugs.java:3: error: incompatible types: String cannot be converted to int
int total = add(3, "4");
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorShow answerوەڵامەکە پیشان بدە
javac shows only the first one, the wrong argument type. The missing return appears after you fix it, because javac checks the paths only once the types are right (Fix the first error first):
javac تەنیا یەکەمیان پیشان دەدات، جۆری هەڵەی . returnـە ونبووەکە دوای چاککردنی ئەو دەردەکەوێت، چونکە javac تەنیا کاتێک ڕێگاکان دەپشکنێت کە جۆرەکان دروست بن (سەرەتا یەکەم هەڵە چاک بکە):
public class Bugs2 {
public static void main(String[] args) {
int total = add(3, 4);
System.out.println(total);
}
static int add(int a, int b) {
int sum = a + b;
}
}$ javac Bugs2.java
Bugs2.java:9: error: missing return statement
}
^
1 errorpublic class BugsFixed {
public static void main(String[] args) {
int total = add(3, 4);
System.out.println(total);
}
static int add(int a, int b) {
int sum = a + b;
return sum;
}
}$ java BugsFixed 7
Write static int countDigits(int n) for with a while loop inside: 2026 has 4 digits, 7 and 0 have one.
static int countDigits(int n) بنووسە بۆ بە لە ناویدا: 2026 چوار هەیە، 7 و 0 یەکێک.
Hintئاماژە
Divide by 10 while n is 10 or more (The while loop).
تا n دە یان زیاتر بێت بەسەر 10ـدا دابەشی بکە (خولی while).
Show answerوەڵامەکە پیشان بدە
public class CountDigits {
public static void main(String[] args) {
System.out.println("2026 has " + countDigits(2026) + " digits");
System.out.println("7 has " + countDigits(7) + " digit");
System.out.println("0 has " + countDigits(0) + " digit");
}
static int countDigits(int n) {
int count = 1;
while (n >= 10) {
n = n / 10;
count++;
}
return count;
}
}$ java CountDigits 2026 has 4 digits 7 has 1 digit 0 has 1 digit
Summaryکورتە
- A method is a named block of code that runs when it is called. Write it once, call it often;
mainstays short. - Header: modifier (
static), return type, name, parameter list; then the body in{ }. Methods sit side by side inside the class, in any order. - Parameters are the variables in the header; arguments are the values in the call. They are matched by position, and the method gets copies.
voidmethods act; methods with a return type answer withreturn, which also ends the method. Every path must return a value.- A call to a value-returning method is replaced by its value: store it, test it, print it or pass it on.
- Boolean methods (
isEven) return a comparison directly and read like questions.
- کە ناوی هەیە و کاتی بانگکردن جێبەجێ دەبێت. جارێک بینووسە و زۆر جار بانگی بکە؛
mainکورت دەمێنێتەوە. - سەردێڕ:
static، ، ناو، لیستی ؛ پاشان لە ناو{ }ـدا. لە ناو لە تەنیشت یەکەوەن، بە هەر ڕیزبەندییەک. - ئەو لە سەردێڕدان؛ ئەو لە بانگکردنەکەدان. بەپێی شوێن یەک دەگرنەوە و کۆپییەکان وەردەگرێت.
-
voidکار دەکەن؛ ئەوانەی هەیە بەreturnوەڵام دەدەنەوە، کە کۆتایی پێ دەهێنێت. هەموو ڕێگایەک دەبێت بگەڕێنێتەوە. - بانگکردنی دەبێتە : هەڵیبگرە، تاقی بکەرەوە، چاپی بکە یان بینێرە.
- (
isEven) ڕاستەوخۆ بەراوردێک دەگەڕێننەوە و وەک پرسیار دەخوێنرێنەوە.
What is the difference between a parameter and an argument?جیاوازیی نێوان پارامیتەر و ئارگیومێنت چییە؟
The parameter is the variable in the method's header (int n); the argument is the value given in a call (7 in square(7)).
ناو سەردێڕی (int n)؛ ئەو لە بانگکردنێکدا دەدرێت (7 لە square(7)ـدا).
Why does if (m >= 50) return "pass"; else if (m < 50) return "fail"; not compile?بۆچی if (m >= 50) return "pass"; else if (m < 50) return "fail"; کۆمپایل نابێت؟
javac checks paths, not conditions: after the else if a path can still reach the end without a return.
javac ڕێگاکان دەپشکنێت، نەک : دوای else if ڕێگایەک هێشتا دەتوانێت بەبێ return بگاتە کۆتایی.
Can a method be written inside main?دەتوانرێت میتۆدێک لە ناو mainـدا بنووسرێت؟
No. Methods are written inside the class, next to main; javac reports illegal start of expression.
نەخێر. لە ناو ، لە تەنیشت main دەنووسرێن؛ javac illegal start of expression ڕاپۆرت دەکات.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Method Overloading and Scopeفرەپێناسەکردنی میتۆد و مەودا
Related lecturesوانە پەیوەندیدارەکان
- Method Overloading and Scopeفرەپێناسەکردنی میتۆد و مەودا
- Recursionخۆبانگکردنەوە
- Packages, import and the Java APIپاکێجەکان، import و APIـی Java
- Defining and Calling Functionsناساندن و بانگکردنی کردارەکان
- Return Values and Noneنرخە گەڕاوەکان و None
- Python Next to JavaPython لە تەنیشت Javaـەوە
- Function Files and Anonymous Functionsفایلەکانی کردار و کردارە بێناوەکان
- Algorithms, Pseudocode and Flowchartsئەلگۆریزمەکان، نیمچەکۆد و هێڵکارییەکانی ڕەوت
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java Methods
- W3Schools: Java Method Parameters
- W3Schools: Java Return Values
- The Java Tutorials: Defining Methods
- The Java Tutorials: Passing Information to a Method or a Constructor
- The Java Tutorials: Returning a Value from a Method
- Java Language Specification (Java SE 17), §8.4 Method Declarations (§8.4.7 Method Body)
- Java Language Specification (Java SE 17), §14.17 The return Statement
- Sedgewick and Wayne, Introduction to Programming in Java, 2.1 Static Methods
- JEP 512: Compact Source Files and Instance Main Methods
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.