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ـی ونبوو.

21 min read19 خولەک خوێندنەوە · 21 stepsهەنگاو

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() ژمارەیەک دەخوێنێتەوە. لەم وانەیەدا خۆت دەنووسیت.

A method drawn as a machine. The call square(7) sends the value 7, labelled argument, into a machine headed static int square(int n). Inside, a box n holds 7 and the body says return n * n;. The value 49, labelled return value, comes out on the right. Below: int a = square(7); — a gets 49. Text: write the job once; call it by its name as often as you need.میتۆدێک وەک ئامێرێک کێشراوە. بانگکردنی square(7) نرخەکە 7، بە ناونیشانی ئارگیومێنت، دەنێرێتە ناو ئامێرێک کە سەردێڕەکەی static int square(int n)ـە. لە ناوەوە سندووقی n ژمارە 7 هەڵدەگرێت و جەستەی کردار دەڵێت return n * n;. نرخەکە 49، بە ناونیشانی نرخی گەڕاوە، لە لای ڕاستەوە دێتە دەرەوە. لە خوارەوە: int a = square(7); — a دەبێتە 49. نووسین: کارەکە جارێک بنووسە؛ هەر چەند جار پێویست بوو بە ناوەکەیەوە بانگی بکە.
A method takes values in, does one job and can hand a value back وەردەگرێت، یەک کار دەکات و دەتوانێت بگەڕێنێتەوەCêIT

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 تەنیا فەرمان دەدات؛ سێ کارەکە دەکەن:

A box labelled main holds three lines: printHeader(); double avg = average(85, 92); printResult("Aram", avg);. Arrows lead down to three method boxes: printHeader() prints the title, average(a, b) works out the mean, printResult(name, avg) prints pass or fail. Note: each method is short, has one job and can be tested on its own.سندووقێک بە ناوی main سێ دێڕی تێدایە: printHeader(); double avg = average(85, 92); printResult("Aram", avg);. تیرەکان دەچنە خوارەوە بۆ سێ سندووقی میتۆد: printHeader() ناونیشانەکە چاپ دەکات، average(a, b) ناوەند دەدۆزێتەوە، printResult(name, avg) دەرچوون یان کەوتن چاپ دەکات. تێبینی: هەر میتۆدێک کورتە، یەک کاری هەیە و دەتوانرێت بە تەنیا تاقی بکرێتەوە.
main reads like a list of jobs; the methods do themmain وەک لیستێکی کار دەخوێنرێتەوە؛ دەیانکەنCêIT

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یەکەم میتۆدی خۆت

Definitionپێناسە

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ـدا بانگی دەکات:

FirstMethod.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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.");
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

The call: the method's name, brackets and a semicolon.

بانگکردنەکە: ناوی ، کەوانە و .

Lineدێڕی 8

static: the method belongs to the class, so main can 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 FirstMethod program with numbered lines. Line 4, printWelcome();, is highlighted, and an arrow marked 1 jumps from it to line 8, static void printWelcome() {. A dashed arrow marked 2 goes from line 11, the end of the method, back to line 5. The terminal shows: Start of main, Welcome to Java methods!, A method is a named block of code., End of main; the two middle lines come from the method. Note: Java reads the whole class first, so main may stand before the method it calls.بەرنامەکە FirstMethod بە دێڕی ژمارەدار. دێڕی 4، printWelcome();، دیار کراوە و تیرێک بە ژمارە 1 لێیەوە باز دەدات بۆ دێڕی 8، static void printWelcome() {. تیرێکی پچڕپچڕ بە ژمارە 2 لە دێڕی 11ـەوە، کۆتایی میتۆدەکە، دەگەڕێتەوە بۆ دێڕی 5. تێرمیناڵەکە پیشان دەدات: Start of main، Welcome to Java methods!، A method is a named block of code. و End of main؛ دوو دێڕە ناوەڕاستەکە لە میتۆدەکەوە دێن. تێبینی: Java سەرەتا هەموو کلاسەکە دەخوێنێتەوە، بۆیە main دەتوانێت پێش ئەو میتۆدەی بانگی دەکات بێت.
A call jumps into the method; at its end the program comes back to the next lineبانگکردن باز دەدات بۆ ناو ؛ لە کۆتاییدا دەگەڕێتەوە بۆ دێڕی دواترCêIT

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 هەمان دێڕ سێ جار چاپ دەکات، بە سێ بانگکردنی کورت لە جیاتی سێ کۆپیی دێڕەکە:

Banner.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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("======================");
    }
}

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 بانگی هەردووکیان دەکات. کاتێک تەواو دەبێت، دەگەڕێتەوە بۆ ئەو بانگی کردووە، واتە :

Header.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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("----------------------");
    }
}
A call tree: main calls printHeader() and printLine(); printHeader() calls printLine() twice. Next to it, the terminal's five lines are tagged with the call that printed them: printLine(), printHeader(), printLine(), main, printLine(). Notes: each line comes from one call; when a method ends, its caller goes on.دارێکی بانگکردن: main بانگی printHeader() و printLine() دەکات؛ printHeader() دوو جار بانگی printLine() دەکات. لە تەنیشتیەوە، هەر یەک لە پێنج دێڕەکەی تێرمیناڵەکە بەو بانگکردنە نیشانە کراوە کە چاپی کردووە: printLine()، printHeader()، printLine()، main و printLine(). تێبینی: هەر دێڕێک لە یەک بانگکردنەوە دێت؛ کاتێک میتۆدێک تەواو دەبێت، بانگکەرەکەی بەردەوام دەبێت.
Who printed which lineکێ کام دێڕی چاپ کردCêIT

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:

زۆربەی کارەکان پێویستیان بە زانیارییە: سڵاو لە کێ بکرێت، دووجای کام ژمارە بدۆزرێتەوە. ئەم زانیارییە لە ڕێگەی وەردەگرێت: ئەو لە کەوانەی سەردێڕەکەیدا نووسراون، هەریەکەیان بە جۆرێکەوە. ئەو لە کەوانەی بانگکردنێکدا دەینووسیت . کاتێک بانگکردنەکە جێبەجێ دەبێت، هەر وەردەگرێت:

Greet.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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 + "!");
    }
}
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 name is the parameter: inside the method it is an ordinary local variable.

String name : لە ناو ئاساییە.

The header static void greet(String name) with String name highlighted and labelled parameter: a variable in the header. Below, two rows: greet("Aram"); sends "Aram" into a box name, which leads to Hello, Aram!; greet("Shilan"); sends "Shilan" into name, giving Hello, Shilan!. Label: argument: the value in the call. Note: each call puts a new value into the parameter.سەردێڕی static void greet(String name) کە String name تێیدا دیار کراوە و ناونیشانی پارامیتەر: گۆڕاوێک لە سەردێڕەکەدا. لە خوارەوە دوو ڕیز: greet("Aram"); "Aram" دەنێرێتە ناو سندووقی name و دەبێتە Hello, Aram!؛ greet("Shilan"); "Shilan" دەنێرێتە ناو name و Hello, Shilan! دەدات. ناونیشان: ئارگیومێنت: ئەو نرخەی لە بانگکردنەکەدایە. تێبینی: هەر بانگکردنێک نرخێکی نوێ دەخاتە ناو پارامیتەرەکە.
The argument is the value in the call; the parameter is the variable that receives it ئەو لە بانگکردنەکەدایە؛ ئەو کە وەریدەگرێتCêIT

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.

چەند بە کۆما لێک جیا بکەرەوە، هەریەکەیان بە جۆری خۆی. بانگکردنێک دەبێت هەمان ژمارە بدات، بە جۆری گونجاو و بە هەمان ڕیزبەندی: یەکەم دەچێتە یەکەم و دووەم بۆ دووەم. ناوەکان هیچ گرنگ نین.

MarkReport.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
    }
}

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⁩ بووە:

PowerOrder.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 9-11

A for loop multiplies result by base, exponent times (The for loop).

result لە base دەدات، بە ژمارەی exponent جار (خولی for).

The header static void printPower(int base, int exponent). Row 1: printPower(2, 10) fills base = 2 (blue) and exponent = 10 (purple) and gives 1024. Row 2: printPower(10, 2) fills base = 10 and exponent = 2 and gives 100: no error, but a different answer. Bottom: printMark(85, "Aram") against printMark(String name, int mark) is crossed out; javac: int cannot be converted to String.سەردێڕی static void printPower(int base, int exponent). ڕیزی 1: printPower(2, 10) دەبێتە base = 2 (شین) و exponent = 10 (مۆر) و 1024 دەدات. ڕیزی 2: printPower(10, 2) دەبێتە base = 10 و exponent = 2 و 100 دەدات: بێ هەڵە، بەڵام وەڵامێکی جیاواز. خوارەوە: printMark(85, "Aram") بەرامبەر printMark(String name, int mark) خەتی بەسەردا هاتووە؛ javac: int cannot be converted to String.
The first argument fills the first parameter, the second fills the secondیەکەم یەکەم پڕ دەکاتەوە، دووەم دووەم پڕ دەکاتەوەCêIT

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:

MarkOrder.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
    }
}
BASHType in a terminalلە تێرمیناڵدا بینووسە
javac -Xdiags:verbose MarkOrder.java

Too 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، چونکە درێژیی دوو لیستەکە جیاوازە:

MarkCount.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
    }
}

And 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).

ParamType.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ParamType {
    public static void main(String[] args) {
        printRect(4, 3);
    }

    static void printRect(int width, height) {
        System.out.println(width + " x " + height);
    }
}

Parameters 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 ئامادە دەکەن):

CheckMark.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
CheckMarkInput.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}

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 و کۆتایی پێ بهێنە. ئیتر بانگکردنەکە ئەو هەیە () و دەتوانێت لە هەر شوێنێک بێت کە ئەو جۆرە دەتوانێت لێی بێت:

SquareDemo.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

The call square(7) becomes 49, which is stored in result.

بانگکردنی square(7) دەبێتە ⁦49⁩ و لە resultـدا هەڵدەگیرێت.

Lineدێڕی 10-12

int before the name is the return type; return n * n; hands the value back.

intـی پێش ناوەکە ؛ return n * n; دەداتەوە.

An animation of CallSquare. Frame 1: main runs line 3, int a = square(7);, and a has no value yet. Frame 2: the call jumps to static int square(int n) and a new box for square appears with n = 7. Frame 3: the body works out n * n = 7 * 7 = 49. Frame 4: return 49 sends the value back to the call. Frame 5: a gets 49 and square's box is gone. Frame 6: main runs line 4 and the terminal shows 49.
An animation of CallSquare. Frame 1: main runs line 3, int a = square(7);, and a has no value yet. Frame 2: the call jumps to static int square(int n) and a new box for square appears with n = 7. Frame 3: the body works out n * n = 7 * 7 = 49. Frame 4: return 49 sends the value back to the call. Frame 5: a gets 49 and square's box is gone. Frame 6: main runs line 4 and the terminal shows 49.
square(7) step by step: the call, the copy into n, the work, the return⁦square(7)⁩ هەنگاو بە هەنگاو: بانگکردن، کۆپیکردن بۆ n، کارەکە، گەڕانەوەCêIT

Returning a valueگەڕاندنەوەی نرخێک

The parts of a methodبەشەکانی میتۆدێک

Every method you write in this course has the same five parts:

هەموو ئەو لەم کۆرسەدا دەینووسیت هەمان پێنج بەشیان هەیە:

The method static int square(int n) { return n * n; } in large code with coloured parts: static (purple) — belongs to the class; int (blue) — return type, what kind of value comes back; square (orange) — the name, in camelCase; (int n) (green) — parameters, a type and a name for each; the bracketed body — the statements that do the job. Boxes below: the first line is the method header; signature = name + parameter types: square(int).میتۆدەکە static int square(int n) { return n * n; } بە کۆدی گەورە و بەشی ڕەنگاوڕەنگ: static (مۆر) — سەر بە کلاسەکە؛ int (شین) — جۆری نرخی گەڕاوە، چ جۆرە نرخێک دەگەڕێتەوە؛ square (پرتەقاڵی) — ناو، بە camelCase؛ (int n) (سەوز) — پارامیتەرەکان، جۆر و ناوێک بۆ هەر یەکێک؛ بەشی ناو کەوانەکان — جەستەی کردار، کە ڕستەکانی کارەکەی تێدایە. سندووقەکانی خوارەوە: یەکەم دێڕ سەردێڕی کردارە؛ واژووی کردار: square(int).
Modifier, return type, name, parameters and bodystatic، ، ناو، و CêIT
  1. static (a modifier): the method belongs to the class. main also has public; the other modifiers come with classes (Constructors, modifiers and encapsulation).
  2. The : void, or the type of the value that comes back (int, double, boolean, String…).
  3. The name, then the parameter list in brackets (empty brackets when there are none). Together they are the first line, the .
  4. The body in braces { }: the statements that run at every call.
  1. static: سەر بە . main publicـیشی هەیە؛ وشەکانی تری لەم جۆرە لەگەڵ دێن (دروستکەرەکان و کەپسوولکردن).
  2. : void، یان جۆری ئەو دەگەڕێتەوە (int، double، boolean، String…).
  3. ناو، پاشان لیستی لە ناو کەوانەدا (کەوانەی بەتاڵ کاتێک هیچ نییە). پێکەوە یەکەم دێڕن، واتە .
  4. لە ناو { }ـدا: ناوی لە هەر بانگکردنێکدا جێبەجێ دەبن.

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);، زۆرجار خوێندنەوەی کۆدەکە ئاسانتر دەکات:

Average.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 11

Dividing by 2.0, not 2, keeps the half: 177 / 2.0 = 88.5.

دابەشکردن بەسەر 2.0، نەک 2، نیوەکە دەهێڵێتەوە: ⁦177 / 2.0 = 88.5⁩.

Two columns. Left: square(3) + square(4) becomes 9 + 16, which becomes 25: each call becomes its value. Right: square(square(2)) becomes square(4), which becomes 16: the inner call goes first.دوو ستوون. چەپ: square(3) + square(4) دەبێتە 9 + 16 و ئەویش دەبێتە 25: هەر بانگکردنێک دەبێتە نرخەکەی. ڕاست: square(square(2)) دەبێتە square(4) و ئەویش دەبێتە 16: سەرەتا بانگکردنە ناوەکییەکە.
Java replaces each call by the value it returnsJava هەر بانگکردنێک بەو دەگۆڕێت کە دەیگەڕێنێتەوەCêIT

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⁩ـەکە ون دەبێت و هیچ چاپ ناکرێت. ئەگەر دەوێت، بەکاری بهێنە.

Ignored.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}

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).

Two panels. Left, void method: printLine() prints a line of dashes in a terminal; it does a job and gives nothing back; you write printLine(); as a statement on its own; return type: void. Right, value-returning method: a vending machine marked square(7) drops a chip 49 into a variable box a; it works out a value and hands it back; int a = square(7); uses the call as a value; return type: int.دوو بەش. چەپ، کرداری نەگەڕێنەر: printLine() دێڕێکی هێڵ لە تێرمیناڵێکدا چاپ دەکات؛ کارێک دەکات و هیچ ناگەڕێنێتەوە؛ printLine(); وەک ڕستەیەکی سەربەخۆ دەنووسیت؛ جۆری نرخی گەڕاوە: void. ڕاست، کرداری نرخگەڕێنەر: ئامێرێکی فرۆشتن بە نیشانەی square(7) پارچەیەکی 49 دەخاتە ناو سندووقی گۆڕاوی a؛ نرخێک دەدۆزێتەوە و دەیداتەوە؛ int a = square(7); بانگکردنەکە وەک نرخێک بەکار دەهێنێت؛ جۆری نرخی گەڕاوە: int.
A void method acts; a value-returning method answers کار دەکات؛ وەڵام دەداتەوەCêIT

A void method has no value to use, and a void method may not return one. javac stops both mistakes:

هیچ نییە بۆ بەکارهێنان و ناشتوانێت بگەڕێنێتەوە. javac ڕێگری لە هەردوو هەڵەکە دەکات:

VoidResult.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class VoidResult {
    public static void main(String[] args) {
        int x = printLine();
        System.out.println(printLine());
    }

    static void printLine() {
        System.out.println("----------");
    }
}
VoidReturn.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class VoidReturn {
    public static void main(String[] args) {
        printLine();
    }

    static void printLine() {
        System.out.println("----------");
        return 5;
    }
}

Returning 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;ـی ڕووت بەکار بهێنێت بۆ ئەوەی زوو بوەستێت:

MaxDemo.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 10-13

If a > b, the method ends at return 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 ڕەتی دەکاتەوە:

Unreachable.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
    }
}

Returning 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⁩):

MissingReturn.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class MissingReturn {
    public static void main(String[] args) {
        System.out.println(result(72));
    }

    static String result(int mark) {
        if (mark >= 50) {
            return "pass";
        }
    }
}

Surprisingly, 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ـێک دەبینێت کە لە کۆتاییدا دەشێت هەڵە بێت:

MissingReturn2.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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";
        }
    }
}
Two flowcharts of result(mark) with the test mark >= 50. Left: true leads to return "pass"; (ticked), but false runs into the closing brace (crossed): false reaches the end without a return — missing return statement. Right: true leads to return "pass"; and false to return "fail";, both ticked: with else, both paths return a value. Note: javac checks the paths, not the numbers: else if (mark < 50) is still not enough.دوو هێڵکاریی ڕەوت بۆ result(mark) بە پشکنینی mark >= 50. چەپ: true دەچێت بۆ return "pass"; (✓)، بەڵام false دەگاتە کەوانەی داخستن (✗): false بێ return دەگاتە کۆتایی — missing return statement. ڕاست: true دەچێت بۆ return "pass"; و false بۆ return "fail";، هەردووکیان ✓: بە else هەردوو ڕێگاکە نرخێک دەگەڕێننەوە. تێبینی: javac ڕێگاکان دەپشکنێت، نەک ژمارەکان: else if (mark < 50) هێشتا بەس نییە.
With else, no path can fall off the endبە else هیچ ڕێگایەک بێ return ناگاتە کۆتاییCêIT
ResultFixed.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public 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";
        }
    }
}

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: دەربڕینی بوولیان):

EvenTest.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}
A machine static boolean isEven(int n) with the body return n % 2 == 0; and the label: true when the remainder is 0. The input 4 comes out as true, the input 7 as false. Below: if (isEven(n)) { ... } — it reads like a question: is n even?ئامێری static boolean isEven(int n) بە جەستەی کردار return n % 2 == 0; و ئەم نووسینە: true کاتێک پاشماوەکە 0 بێت. نێوخستەی 4 وەک true دێتە دەرەوە و 7 وەک false. لە خوارەوە: if (isEven(n)) { ... } — وەک پرسیارێک دەخوێنرێتەوە: ئایا n جووتە؟
isEven answers with true or falseisEven بە true یان false وەڵام دەداتەوەCêIT

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 دەداتەوە، نامێنن و بەردەوام دەبێت. ئەمە پسوولەیەکی بچووکی چایخانەیە:

TeaBill.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}
A trace table for TeaBill بۆ TeaBill
LineدێڕWhat happensچی ڕوو دەداتmainmainpriceprice
3teas is createdteas دروست دەکرێتteas = 3
4the call price(teas, 500) startsبانگکردنی price(teas, 500) دەست پێ دەکاتteas = 3count = 3, each = 500
9the body multiplies لێکدان دەکاتteas = 3count = 3, each = 500, total = 1500
10return total; hands back 1500return total; ⁦1500⁩ دەداتەوەteas = 3goneنەماوە
4bill gets 1500bill دەبێتە ⁦1500⁩teas = 3, bill = 1500
5prints the billپسوولەکە چاپ دەکاتteas = 3, bill = 1500
Two boxes. main holds teas = 3 and bill = 1500 and the line int bill = price(teas, 500);. price holds count = 3, each = 500 and total = 1500. An arrow carries a copy of 3 from teas to count, a dashed arrow carries the value 500 to each, and an arrow labelled return 1500 goes back to bill. Note: main waits while price runs; when price returns, count, each and total are gone; only bill keeps the answer.دوو سندووق. لە mainـدا teas = 3، bill = 1500 و دێڕی int bill = price(teas, 500); هەن. لە priceـدا count = 3، each = 500 و total = 1500 هەن. تیرێک کۆپییەکی 3 لە teas دەبات بۆ count، تیرێکی پچڕپچڕ نرخەکە 500 دەبات بۆ each و تیرێک بە ناوی return 1500 دەگەڕێتەوە بۆ bill. تێبینی: main چاوەڕێ دەکات تا price کار دەکات؛ کاتێک price دەگەڕێتەوە، count، each و total نامێنن؛ تەنیا bill وەڵامەکە دەهێڵێتەوە.
Each call has its own variables; only the returned value survivesهەر بانگکردنێک خۆی هەیە؛ تەنیا دەمێنێتەوەCêIT

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 بانگی تۆ دەکات.

A class box public class TeaBill { … } holds two method boxes side by side: public static void main(String[] args) { int bill = price(3, 500); … } and static int price(int count, int each) { return count * each; } — ticked. On the right, two crossed-out layouts: a method written inside main gives illegal start of expression; a method written outside the class gives class, interface, enum, or record expected.سندووقی کلاسی public class TeaBill { … } دوو سندووقی میتۆدی لە تەنیشت یەکەوە لە خۆ دەگرێت: public static void main(String[] args) { int bill = price(3, 500); … } و static int price(int count, int each) { return count * each; } — ✓. لە لای ڕاست، دوو شێوەی هەڵە: میتۆدێک لە ناو main نووسرابێت illegal start of expression دەدات؛ میتۆدێک لە دەرەوەی کلاسەکە نووسرابێت class, interface, enum, or record expected دەدات.
Methods sit next to each other inside the class لە ناو لە تەنیشت یەکەوە دادەنیشنCêIT

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 ئیتر پێکهاتەکە تێناگات:

Nested.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Nested {
    public static void main(String[] args) {
        static void printLine() {
            System.out.println("----------");
        }
        printLine();
    }
}
Outside.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Outside {
    public static void main(String[] args) {
        printLine();
    }
}

static void printLine() {
    System.out.println("----------");
}

main 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 هیچ ئۆبجێکتێکی نییە):

NonStatic.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class NonStatic {
    public static void main(String[] args) {
        printLine();
    }

    void printLine() {
        System.out.println("----------");
    }
}

Common mistakesهەڵە باوەکان

You wroteنووسیتWhat happensچی ڕوو دەداتFixچارەسەر
no return on one pathreturn لە یەک ڕێگادا نییەmissing return statementReturn on every path; end with else or a last return.لە هەموو ڕێگایەکدا بگەڕێنەوە؛ بە else یان دوا returnـێک کۆتایی پێ بهێنە.
int x = printLine();void cannot be converted to intA 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 intMake the return type double, or return an int. بکە بە double، یان intـێک بگەڕێنەوە.
square("7")String cannot be converted to intPass a value of the parameter's type. بە جۆری بنێرە.
printMark("Aram")cannot be applied to given typesGive every parameter an argument, in order.بە ڕیزبەندی بۆ هەموو بدە.
static void box(int w, h)<identifier> expectedWrite a type for each parameter.بۆ هەر جۆرێک بنووسە.
static void printLine(); {missing method body, or declare abstractNo semicolon after the header.هیچ لە دوای سەردێڕەکە نەبێت.
no static on a method main callsبێ static لەسەر کە main بانگی دەکاتnon-static method … cannot be referenced from a static contextAdd static.static زیاد بکە.
a statement after return لە دوای returnunreachable statementDelete it or move it before the return.بیسڕەوە یان بیبە پێش return.
return (a + b) / 2;88.0 instead of 88.588.0 لە جیاتی 88.5Divide 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 — هەرگیز بۆ نا):

Outputدەرئەنجام
$ 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 error

Practiceڕاهێنان

ExerciseڕاهێنانA row of starsڕیزێک ئەستێرە

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وەڵامەکە پیشان بدە
Stars.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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();
    }
}
ExerciseڕاهێنانCelsius to Fahrenheitسیلیزی بۆ فەهرەنهایت

Write static double toFahrenheit(double celsius) using F=C×95+32F = C \times \frac{9}{5} + 32. Test 0, 37, 100 and -40.

static double toFahrenheit(double celsius) بنووسە بە F=C×95+32F = C \times \frac{9}{5} + 32. 0، ⁦37⁩، ⁦100⁩ و ⁦-40⁩ تاقی بکەرەوە.

Show answerوەڵامەکە پیشان بدە
Fahrenheit.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}

-40 is the one temperature that is the same on both scales.

⁦-40⁩ تاکە پلەیە کە لە هەردوو پێوەرەکەدا وەک یەکە.

ExerciseڕاهێنانThe largest of threeگەورەترینی سێ ژمارە

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وەڵامەکە پیشان بدە
MaxOfThree.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}
ExerciseڕاهێنانLeap yearsساڵی کەبیسە

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وەڵامەکە پیشان بدە
LeapYear.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}
ExerciseڕاهێنانA letter gradeنمرەی پیتی

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وەڵامەکە پیشان بدە
LetterGrade.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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';
        }
    }
}
ExerciseڕاهێنانFind the two mistakesدوو هەڵەکە بدۆزەرەوە

This program has two mistakes. Find both before you compile it.

ئەم دوو هەڵەی تێدایە. پێش کۆمپایلکردن هەردووکیان بدۆزەرەوە.

Bugs.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}
Show 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 تەنیا کاتێک ڕێگاکان دەپشکنێت کە جۆرەکان دروست بن (سەرەتا یەکەم هەڵە چاک بکە):

Bugs2.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}
BugsFixed.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public 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;
    }
}
ExerciseڕاهێنانCount the digitsژمارەی تاکژمارەکان بژمێرە

Write static int countDigits(int n) for n≥0n \ge 0 with a while loop inside: 2026 has 4 digits, 7 and 0 have one.

static int countDigits(int n) بنووسە بۆ n≥0n \ge 0 بە لە ناویدا: ⁦2026⁩ چوار هەیە، 7 و 0 یەکێک.

Hintئاماژە

Divide by 10 while n is 10 or more (The while loop).

تا n دە یان زیاتر بێت بەسەر ⁦10⁩ـدا دابەشی بکە (خولی while).

Show answerوەڵامەکە پیشان بدە
CountDigits.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
    }
}

Summaryکورتە

  • A method is a named block of code that runs when it is called. Write it once, call it often; main stays 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.
  • void methods act; methods with a return type answer with return, 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) ڕاستەوخۆ بەراوردێک دەگەڕێننەوە و وەک پرسیار دەخوێنرێنەوە.
Review questionsپرسیارەکانی پێداچوونەوە
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زاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Method Overloading and Scopeفرەپێناسەکردنی میتۆد و مەودا

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.