★ India’s Student Guidance Platform

User-Defined Methods in Java — ICSE Class 10 Computer Applications

User-Defined Methods in Java — ICSE Class 10 Computer Applications

Ab tak aapne poora program ek hi jagah likha hai — sab kuch main() ke andar. Ek chhote program mein yeh chalta hai. Lekin jaise hi program bada hota hai, main() ek lambi, uljhi hui list ban jaati hai jise padhna bhi mushkil aur theek karna bhi. Yahin par methods aate hain. A method is a named block of code that does one job. You write it once, give it a name, and then call that name whenever the job needs doing. This chapter covers Unit 3, User-defined Methods, of the ICSE Class 10 Computer Applications syllabus (subject code 86) — and it is one of the highest-scoring units in the paper, because almost every programming question you write will be built out of methods.

Why Methods? One Job, One Name

Soch kar dekhiye: aapko ek program mein teen alag jagah rectangle ka area nikalna hai. Bina method ke aap wahi do lines teen baar likhenge. Agar formula mein galti ho gayi, toh teenon jagah theek karni padegi. With a method you write the formula once, in one place, and call it three times. Fix it once and every caller is fixed.

Methods give you four concrete gains, and the Council expects you to be able to name them:

  • Reusability — ek baar likho, baar-baar use karo.
  • Modularity — a big problem is broken into small, named sub-problems. This is what the syllabus calls modular programming.
  • Readabilityobj.rectangleArea(12, 5) tells the reader what is happening; two lines of arithmetic do not.
  • Easy debugging — galti ek hi jagah dhoondhni padti hai.
Key Rule

A method should do one job and its name should say what that job is. If you cannot name a method in two or three words, it is probably doing too much and should be split.

Anatomy of a Method Header

Har method ke do hisse hote hain — header (pehli line) aur body (curly braces ke andar ka kaam). Poora scoring header ka hai, kyunki ICSE mein header ke har part par sawaal ban sakta hai.

access_specifier  return_type  method_name ( parameter_list )
{
    // body — the statements that do the job
}
Part What it means Example
Access specifier Who is allowed to call it — public, private, protected. If you write nothing, it is default access — kai purani textbooks ise friendly bhi likhti hain, matlab dono ka ek hi hai. public
Return type The data type of the value sent back. void means nothing is sent back. int
Method name An identifier. House style: start with a lowercase verb. rectangleArea
Parameter list Type + name for each value the method needs. Empty brackets mean it needs nothing. (int length, int breadth)
Exam Tip

Two terms get confused every year. The method prototype (also called the signature) is the method name plus the number, order and types of its parameters — for example rectangleArea(int, int). The return type is not part of the signature. Remember that line; it explains everything in the overloading section below.

Defining and Calling a Method

Defining a method sirf batata hai ki kaam kaise hoga. Kaam tab hota hai jab aap use call karte hain. A non-static method belongs to an object, so first you create an object with new, then call the method through it using the dot operator.

Worked Example 1 — A method with no parameters and no return value

class Ex1
{
    void greet()
    {
        System.out.println("Welcome to Class 10 Computer Applications");
    }

    public static void main(String args[])
    {
        Ex1 obj = new Ex1();
        obj.greet();
        obj.greet();
    }
}

Output

Welcome to Class 10 Computer Applications
Welcome to Class 10 Computer Applications

Notice the order of execution. Control starts in main(), jumps into greet(), finishes the body, and returns to the line after the call. Then it jumps in a second time. Method ek baar likha, do baar chala.

Return Type and the return Statement

Ek method sirf print karke chup ho sakta hai, ya woh apne caller ko ek value laut sakta hai. Return type header mein likha jaata hai, aur body mein return statement se value bheji jaati hai.

  • void return type → koi value nahi lautegi. return; likh sakte hain (sirf bahar nikalne ke liye), lekin return value; nahi.
  • Koi bhi doosra return type (int, double, char, boolean, String…) → method ko zaroor us type ki value lautani hogi.
  • return chalte hi method wahin khatam — uske baad ki lines kabhi nahi chalti.
Worked Example 2 — Returning a value and using it two ways

class Ex2
{
    int rectangleArea(int length, int breadth)
    {
        int area = length * breadth;
        return area;
    }

    public static void main(String args[])
    {
        Ex2 obj = new Ex2();
        int a = obj.rectangleArea(12, 5);
        System.out.println("Area of rectangle = " + a);
        System.out.println("Area of square    = " + obj.rectangleArea(7, 7));
    }
}

Output

Area of rectangle = 60
Area of square    = 49

Do baaton par dhyaan dijiye. Pehli call ka result ek variable a mein rakha gaya. Doosri call ka result seedhe println ke andar use ho gaya — kyunki ek value-returning method ka call apne aap mein ek value hai, bilkul 60 ki tarah. Aur ek hi method ne rectangle aur square dono ka kaam kar diya, kyunki square ek rectangle hi hai jiski dono bhujaayein barabar hain.

Common Mistake

Ek non-void method ko call karke uska result phenk dena. obj.rectangleArea(12, 5); apne aap mein kuch print nahi karega — value aayi aur gayab ho gayi. Ya toh use kisi variable mein rakhiye, ya println ke andar likhiye.

Actual vs Formal Parameters

Yeh do shabd har saal poochhe jaate hain aur inka jawaab ek line ka hai.

  • Formal parameters — method ke header mein likhe hue variables. In Example 2 these are int length and int breadth. Ye method ke andar hi zinda rehte hain.
  • Actual parameters (arguments) — call ke waqt bheji gayi asli values, jaise 12 aur 5.
Key Rule

Actual and formal parameters must match in number, order and type. rectangleArea(12) ya rectangleArea("12", 5) compile hi nahi hoga. Order matter karta hai — (12, 5) aur (5, 12) alag calls hain, chahe area same aaye.

Static vs Non-Static Methods

Ek method ya toh class ka hota hai ya object ka. Yehi static keyword ka poora matlab hai.

Static method Non-static (instance) method
Declared with the static keyword. No static keyword.
Belongs to the class. Called as ClassName.method(), or just method() from another static method of the same class. Belongs to an object. You must create an object first: obj.method().
Can use only static variables and other static methods directly. Can use both instance variables and static variables.
One copy shared by every object. Works on that particular object’s own data.

main() khud static hota hai — isiliye program shuru hone ke liye kisi object ki zaroorat nahi padti. Aur isi wajah se aap main() ke andar se ek non-static method ko seedhe nahi bula sakte; pehle object banana padta hai. Aap library methods mein bhi yeh dono roop dekh chuke hain. Math.sqrt(25) static hai — ise seedhe Math class ke naam se bulaya jaata hai, koi object banane ki zaroorat nahi. Lekin agar aapke paas ek String hai, jaise String s = "Hello";, toh s.length() non-static hai — woh usi String object par kaam karta hai jise s pakde hue hai.

Common Mistake

Non-static method ko main() se bina object ke bulana. Compiler kehta hai “non-static method cannot be referenced from a static context”. Ilaaj do hi hain — ya method ko static bana dijiye, ya object bana kar obj.method() likhiye. ICSE answers mein doosra tareeka hi standard hai.

Pure and Impure Methods

Yeh distinction syllabus mein naam se likha hua hai, aur one-mark definition questions mein aata hai.

  • A pure method (also called an accessor method) apne arguments par kaam karke ek value lauta deta hai, aur object ki state badalta nahi.
  • An impure method (mutator method) object ke data members ki value badal deta hai.
Worked Example 3 — The same job done purely and impurely

class Ex4
{
    int marks = 40;

    int bonusPure(int m)
    {
        return m + 10;
    }

    int bonusImpure()
    {
        marks = marks + 10;
        return marks;
    }

    public static void main(String args[])
    {
        Ex4 obj = new Ex4();
        System.out.println("Original marks   : " + obj.marks);
        System.out.println("Pure returns     : " + obj.bonusPure(obj.marks));
        System.out.println("marks after pure : " + obj.marks);
        System.out.println("Impure returns   : " + obj.bonusImpure());
        System.out.println("marks after impure: " + obj.marks);
    }
}

Output

Original marks   : 40
Pure returns     : 50
marks after pure : 40
Impure returns   : 50
marks after impure: 50

Dono methods ne 50 hi lautaya — lekin fark uske baad dikhta hai. Pure method ke baad marks abhi bhi 40 hai. Impure method ke baad marks khud 50 ho gaya. Pure method ne object ko chhua tak nahi; impure ne uski state badal di.

Method Overloading (Polymorphism)

Ek hi class mein do ya do se zyada methods ka naam ek ho sakta hai, bas unki parameter list alag honi chahiye. Ise method overloading kehte hain, aur yeh polymorphism ka sabse simple roop hai jo ICSE Class 10 mein aata hai.

Parameter list alag kaise hoti hai? Teen mein se kisi ek tareeke se:

  • Number of parameters alag ho — area(int) vs area(int, int)
  • Type of parameters alag ho — area(int) vs area(double)
  • Order of parameter types alag ho — show(int, char) vs show(char, int)
Worked Example 4 — Three methods, one name

class Ex3
{
    void area(int side)
    {
        System.out.println("Area of square = " + (side * side));
    }

    void area(int length, int breadth)
    {
        System.out.println("Area of rectangle = " + (length * breadth));
    }

    void area(double radius)
    {
        System.out.println("Area of circle = " + (3.14 * radius * radius));
    }

    public static void main(String args[])
    {
        Ex3 obj = new Ex3();
        obj.area(6);
        obj.area(8, 3);
        obj.area(5.0);
    }
}

Output

Area of square = 36
Area of rectangle = 24
Area of circle = 78.5

Compiler har call par argument list dekh kar decide karta hai ki kaunsa version chalega. area(6) → ek int → square wala. area(8, 3) → do int → rectangle wala. area(5.0) → ek double → circle wala. Yeh faisla compile time par hota hai, isiliye ise compile-time polymorphism bhi kehte hain.

Common Mistake

Sirf return type badal kar overloading karne ki koshish. int show(int a) aur void show(int a) ek saath nahi reh sakte — compiler error. Yaad rakhiye, return type signature ka hissa hi nahi hai, isliye compiler ke liye ye dono bilkul ek jaise dikhte hain. Parameter list badalna zaroori hai.
Exam Tip

Parameter ke naam badalne se overloading nahi hoti. void area(int side) aur void area(int length) dono area(int) hi hain. Compiler naam nahi, sirf types dekhta hai.

Pass by Value vs Pass by Reference

Jab aap ek method ko argument bhejte hain, toh andar kya jaata hai — asli variable, ya uski copy? Iska jawaab is baat par nirbhar karta hai ki aap kya bhej rahe hain.

  • Pass by value — primitive types (int, double, char, boolean…) ki ek copy bheji jaati hai. Method ke andar badlaav karne se caller ka original variable nahi badalta.
  • Pass by reference — object bhejne par uske address ki copy jaati hai, isliye method aur caller dono ek hi object ko dekh rahe hote hain. Method ke andar object ka data badla, toh caller ko bhi badla hua dikhega.
Worked Example 5 — Dono ka fark ek hi program mein

class Ex5
{
    void changePrimitive(int n)
    {
        n = n * 2;
        System.out.println("Inside method, n = " + n);
    }

    void changeArray(int a[])
    {
        a[0] = a[0] * 2;
        System.out.println("Inside method, a[0] = " + a[0]);
    }

    public static void main(String args[])
    {
        Ex5 obj = new Ex5();
        int num = 25;
        obj.changePrimitive(num);
        System.out.println("Back in main, num = " + num);

        int arr[] = {25, 50};
        obj.changeArray(arr);
        System.out.println("Back in main, arr[0] = " + arr[0]);
    }
}

Output

Inside method, n = 50
Back in main, num = 25
Inside method, a[0] = 50
Back in main, arr[0] = 50

Yehi poora fark hai. num ek primitive tha — method ke andar 50 hua, lekin main() mein wapas 25 hi mila, kyunki andar sirf ek copy gayi thi. arr ek object hai — method ne usi array ko badla jise main() pakde hue hai, isliye badlaav bahar bhi dikha. (Arrays ka poora chapter aage aata hai; yahan woh sirf reference ka example hai. Syllabus is topic par sirf definition-with-an-example maangta hai, poore programs nahi.)

Exam Tip

Agar aap internet par padhenge toh kahin-kahin likha milega ki “Java always passes by value”. Technically woh sahi hai — object bhejte waqt bhi Java uske address ki copy hi bhejta hai. Lekin ICSE syllabus is behaviour ko pass by reference hi kehta hai. Board ke paper mein syllabus wali terminology hi likhiye; confusion ka koi faayda nahi.

Dry-Run Bank — Output Questions

Section A mein “give the output” wale sawaal sabse zyada number khaate hain, kyunki students code padh kar seedhe andaaza laga lete hain. Har question ko pehle kaagaz par trace kijiye, phir answer kholiye.

Dry Run 1 — a static variable that survives between calls

class D1
{
    static int count = 0;

    static void ticket()
    {
        count = count + 1;
        System.out.println("Ticket number " + count);
    }

    public static void main(String args[])
    {
        ticket();
        ticket();
        ticket();
        System.out.println("Total issued = " + count);
    }
}
Show Answer
Ticket number 1
Ticket number 2
Ticket number 3
Total issued = 3

count static hai, isliye woh class ka hai — har call ke baad apni value yaad rakhta hai. Agar yeh ticket() ke andar ek local variable hota, toh har baar 1 hi chhapta.

Dry Run 2 — overloading with int and String

class D2
{
    int twice(int n)
    {
        return n + n;
    }
    String twice(String s)
    {
        return s + s;
    }
    public static void main(String args[])
    {
        D2 ob = new D2();
        System.out.println(ob.twice(9));
        System.out.println(ob.twice("9"));
        System.out.println(ob.twice(9) + ob.twice("9"));
    }
}
Show Answer
18
99
1899

twice(9) ne addition kiya → 18. twice("9") ne concatenation kiya → 99. Teesri line mein 18 aur "99" ko + ne joda — ek taraf String hone se yeh concatenation ban gaya → 1899. Yahi trap har saal lagta hai.

Dry Run 3 — a method calling another method

class D3
{
    boolean isEven(int n)
    {
        return n % 2 == 0;
    }
    void report(int n)
    {
        if (isEven(n))
            System.out.println(n + " is even");
        else
            System.out.println(n + " is odd");
    }
    public static void main(String args[])
    {
        D3 ob = new D3();
        ob.report(14);
        ob.report(-7);
        ob.report(0);
    }
}
Show Answer
14 is even
-7 is odd
0 is even

report() ke andar se isEven() bina object ke bulaya gaya — yeh chalta hai kyunki dono non-static hain aur usi object par kaam kar rahe hain. Aur dhyaan dijiye: Java mein -7 % 2 ka jawaab -1 hai, 1 nahi — isliye condition == 0 likhna hi safe hai.

How This Chapter Is Examined

Ek baar paper ka dhaancha samajh lijiye, taiyari apne aap sadhi ho jaayegi. CISCE ke Class X syllabus ke anusaar Computer Applications (86) mein ek written paper, do ghante, 100 marks hota hai, aur uske saath Internal Assessment bhi 100 marks ka. Internal Assessment poori tarah practical hai — saal bhar mein kam se kam 20 lab assignments karne hote hain, jinka record teacher-in-charge rakhta hai. CISCE ke question paper mein yeh 100 marks do hisson mein bante hain: Section A — 40 marks, jismein saare sawaal karne hote hain (MCQs aur chhote answer, jahan output aur definition wale sawaal aate hain), aur Section B — 60 marks, jismein chhe sawaalon mein se koi chaar karne hote hain (yehi poore programs likhne wale sawaal hain). Section A khud do sawaalon ka banta hai: Question 1 20 marks ke MCQs, aur Question 2 20 marks ke chhote sawaal — das hisse, har ek 2 marks ka.

Methods se sawaal do roop mein aate hain. Chhote sawaalon mein definitions aur difference poochhe jaate hain — pure aur impure method mein antar, actual aur formal parameter mein antar, method prototype kya hota hai, overloading kis aadhaar par hoti hai. Bade programming sawaalon mein aapko class likhni hoti hai jismein ek ya do methods ho, aur unhein main() se object bana kar bulaya gaya ho. Dono jagah marks poore tab milte hain jab header bilkul sahi ho.

Exam Tip

Jab sawaal mein method ka header diya gaya ho — jaise “void display(int n)” — toh use hoo-ba-hoo waisa hi likhiye. Return type ya parameter type badalne par examiner marks kaat sakta hai, chahe aapka logic bilkul sahi ho.

Practice Worksheet (10 Questions)

Pehle khud kijiye, phir answer kholiye. Jo galat ho use dobara kaagaz par likhiye — padh lene se yaad nahi hota, likhne se hota hai.

Q1. Define a method prototype. State whether the return type forms part of it, and give one reason for your answer.

Show Answer

A method prototype (signature) is the method name together with the number, order and types of its parameters — for example rectangleArea(int, int). The return type is not part of it. Reason: the compiler picks a method from the call itself, and a call such as obj.rectangleArea(12, 5) carries no information about what type will come back, so the return type could never help it choose.

Q2. Distinguish between a pure method and an impure method. Give one example of each in words (no code).

Show Answer

A pure method works only on the values passed to it and returns a result without changing the object’s data members — for example a method that receives two numbers and returns their average. An impure method changes the state of the object — for example a method that adds a bonus to the object’s own marks variable. Pure method object ko chhoota nahi; impure use badal deta hai.

Q3. Give the output.

class W2
{
    int check(int x)
    {
        x = x + 5;
        return x;
    }
    public static void main(String args[])
    {
        W2 ob = new W2();
        int p = 10;
        int q = ob.check(p);
        System.out.println(p + " " + q);
        System.out.println(ob.check(p) + p);
    }
}
Show Answer
10 15
25

p primitive hai, isliye check() ke andar sirf copy badli — p abhi bhi 10. Doosri line mein check(10) ne 15 lautaya, phir 15 + 10 — dono int hain, isliye yeh addition hai, concatenation nahi → 25.

Q4. Give the output.

class W3
{
    void show(int a)
    {
        System.out.println("int version : " + a);
    }
    void show(double a)
    {
        System.out.println("double version : " + a);
    }
    void show(char a)
    {
        System.out.println("char version : " + a);
    }
    public static void main(String args[])
    {
        W3 ob = new W3();
        ob.show(7);
        ob.show(7.0);
        ob.show('7');
    }
}
Show Answer
int version : 7
double version : 7.0
char version : 7

Teenon calls ke arguments ke type alag hain, isliye teen alag versions chale. Dhyaan dijiye ki 7.0 waisa hi chhapa — double hai — aur '7' ek character hai, number nahi.

Q5. Give the output.

class Q4
{
    static int seed = 5;

    static int grow(int n)
    {
        seed = seed + n;
        return seed;
    }

    public static void main(String args[])
    {
        System.out.println(grow(3));
        System.out.println(grow(3));
        System.out.println(seed + grow(0));
    }
}
Show Answer
8
11
22

Pehli call: seed 5 se 8. Doosri: 8 se 11. Teesri line asli trap hai. Java + ke dono taraf ko baayen se daayen evaluate karta hai — pehle seed padha jaata hai (us waqt 11), uske baad grow(0) chalta hai jo 11 hi lautata hai → 11 + 11 = 22. Agar wahi line grow(1) + seed hoti, toh grow(1) pehle chalta aur seed ko 12 kar deta, phir daayen wala seed 12 padha jaata → 12 + 12 = 24. Yaani impure method ka side effect is baat par nirbhar karta hai ki woh expression mein kahan khada hai.

Q6. Why can a non-static method not be called directly from main()? State the two ways of fixing it.

Show Answer

main() is a static method, so it runs without any object existing. A non-static method belongs to an object, so there is no object for it to work on — the compiler reports that a non-static method cannot be referenced from a static context. Fix 1: create an object inside main() and call the method through it, as in Demo ob = new Demo(); ob.method();. Fix 2: declare the method itself as static. In ICSE answers the first fix is the expected one.

Q7. Write a class Interest with a method double simpleInterest(double p, double r, double t) that returns the simple interest, and call it from main() for a principal of 12000, rate 7.5% and time 3 years.

Show Answer
class Q1
{
    double simpleInterest(double p, double r, double t)
    {
        return (p * r * t) / 100;
    }
    public static void main(String args[])
    {
        Q1 ob = new Q1();
        System.out.println("SI = " + ob.simpleInterest(12000, 7.5, 3));
    }
}

Output:
SI = 2700.0

Return type double hai, isliye output 2700.0 aata hai, 2700 nahi. Yeh chhota sa fark output questions mein marks le doobta hai.

Q8. Write a class with two overloaded methods named larger — one that returns the larger of two integers, and one that returns the largest of three. Show both being called.

Show Answer
class Q2
{
    int larger(int a, int b)
    {
        if (a > b)
            return a;
        return b;
    }
    int larger(int a, int b, int c)
    {
        return larger(larger(a, b), c);
    }
    public static void main(String args[])
    {
        Q2 ob = new Q2();
        System.out.println(ob.larger(18, 25));
        System.out.println(ob.larger(18, 25, 21));
    }
}

Output:
25
25

Teen-parameter wala version do-parameter wale ko do baar bula leta hai — yeh modular programming ka asli faayda hai. Logic ek hi jagah likha, dobara nahi.

Q9. Give the output, then state which method is pure and which is impure.

class Q3
{
    int store = 100;

    int addPure(int a, int b)
    {
        return a + b;
    }

    void addImpure(int a)
    {
        store = store + a;
    }

    public static void main(String args[])
    {
        Q3 ob = new Q3();
        System.out.println(ob.addPure(20, 30));
        System.out.println("store = " + ob.store);
        ob.addImpure(25);
        System.out.println("store = " + ob.store);
    }
}
Show Answer
50
store = 100
store = 125

addPure() pure hai — ise accessor method bhi kehte hain. Usne sirf parameters par kaam kiya aur value lautayi; store waisa ka waisa raha. addImpure() impure hai — yani mutator method. Usne data member store badal diya, isliye teesri line 125 dikhati hai. Paper mein examiner pure/accessor aur impure/mutator ko ek doosre ki jagah use kar leta hai, toh dono jodiyon ko synonym maan kar chaliye.

Q10. Write a class Q5 with two overloaded display methods: display(int n) prints the value once, and display(int n, int times) prints it the given number of times with a serial number. Show the output for display(8) and display(8, 3).

Show Answer
class Q5
{
    void display(int n)
    {
        System.out.println("Value : " + n);
    }
    void display(int n, int times)
    {
        for (int i = 1; i <= times; i++)
            System.out.println(i + ". Value : " + n);
    }
    public static void main(String args[])
    {
        Q5 ob = new Q5();
        ob.display(8);
        ob.display(8, 3);
    }
}

Output:
Value : 8
1. Value : 8
2. Value : 8
3. Value : 8

Yahan overloading aur loop dono ek saath aaye — exactly jaise paper mein aate hain. Parameter count alag hai, isliye dono methods ek hi naam se reh sakte hain.

↑ Back to top

Aage kya? Ab tak aapne dekha ki ek method object ka kaam kaise karta hai. Agla sawaal yeh hai ki object banta kaise hai aur uske data members ko pehli value kaun deta hai — woh kaam constructors ka hai. Peeche jaana ho toh Iterative Constructs (Loops) aur Conditional Constructs dobara padh lijiye, kyunki methods ke andar ka logic wahi se banta hai.

Kaizen: Aaj se roz apne purane programs mein se ek uthaiye aur uska ek hissa — sirf ek — ek method mein nikal dijiye. Us method ko naam dijiye, header likhiye, aur main() se bulaiye. Ek hafte mein aapko lambe programs chhote-chhote naam wale tukdon mein dikhne lagenge. Yehi soch exam mein programming question ko aasan banati hai.

Written & reviewed by Team Principal Saab — Meet the team →