12 Java Fundamentals | Methods in Java | By Dummy for Dummies

 


INTRODUCTION

What if I tell you, you can have an assistant in your program that will do a specific task assigned to it everytime you ask. Everytime you call the assistant, give it the data, it will do the assigned task. All you have to do is just code it for once, and then call it unlimited times to do your tasks.


METHODS 

In Java, a method is a block of code enclosed in curly brackets. There is a main method always, and you can create multiple other methods if you want. Think of these like you have one boss method and many assistants.

Boss Method → Always execute, code execution starts from here.

Assistant Methods → You can chose to execute them multiple times, or not even once depends on you, executes when you call them.


Let's simulate a situation where boss monkey will ask to see 2 bananas plus 3 bananas how much total bananas? To make assistant do the calculations we need to send it the data. In programming that data we send are called Arguments. As we know that we store data in variables, so when the assistant recieve that data/arguments it need to store it in some variables right? In programming that variable which receive and store arguments are called Parameter. So we have:

Arguments → The data Boss monkeys sends (2 bananas and 3 bananas)

Parameters → The Variable that stores Arguments 

When we need the assistant, we will call it, tell it the data through the call, it will receive the data. What will the assistant do with data? we will code it to add two numbers. 

Boss Method = Orange

Assistant Method = Yellow

public class Main {


    // Boss method - program starts here

    public static void main(String[] args) {

        System.out.println("Boss Monkey: Send data to assistant!");


        // Boss calls the assistant to calculate bananas

        assistant(2, 3);


    }


    // Assistant method → Adds two numbers (bananas)

    public static void assistant(int a, int b) {

        int total = a + b;

        System.out.println("Total Bananas: "+total);

    }

}



OUTPUT:

Boss Monkey: Send data to assistant! Total Bananas: 5 

While creating assistant method you see there are few words that need explanation. This the is the assistant method:
  public static void assistant(int a, int b){ }  

Let's break it down word by word:

 public   It decides who can access this assistant method. Right now we created one file of code i.e. Main.java, when you reach OOP and start making bigger projects you will create a lot of java files. There if you write "public" in start of such method then from any file you can access it, if you write "private" then only from that file you can access where it belongs. As it decides who can access this method, therefore it is called Access Modifier 

 static   This concept is a bit more complex, so we will learn it through analogies. Imagine you have a blueprint for a car, and you use that to create many actual cars (real objects). Each car will have their own meter to check how many kilometers it traveled. Imagine you added a meter that does not calculate distance traveled for a single car, instead it keeps track of the total distance traveled by all cars of the company combined. So even if your car never traveled not even for a meter, it will show how much all cars of the company traveled. All car will share same meter.
Static is somehow like that, writing static means this part of code does not belong to each object you create from this, but rather all objects created from it will share this

 void   It tells the method to do not return anything back. You can decide anything for it to return. Like when added the two numbers we printed it there, if we wanted we could have returned the total value, for that we needed to write int instead of void
So void means empty, do not return anything

 assistant(int a, int b)  This is the method name, since you can create multiple methods therefore each needs a name to see which are we calling. After the name we put brackets and inside it are parameters to receive the arguments in their respective variables. Parameters should be in same order in which we sent the arguments.
⦿ If we sent arguments as : int, String, char, char, char, String
⦿ Parameters should be: int a, String b, char c, char d, String e

These a b c d e are just names, you can write anything there. 

 { }  → This is where we will write all that code which belongs to that specific method.



POINTS TO REMEMBER

⦿ While calling a method write it's name and arguments inside it. You do not need to write datatype of argument when calling from main method, i.e. just  assistant(3, 2)  

⦿ When creating a specific method, for now just write public static, and decide the return type that suits you (will explain other return type as follow)

⦿ Order of arguments sent, and parameters must match

⦿ Method name should be in lower case alphabets (convention)

⦿ Number of arguments sent and received in parameters MUST be same.

⦿ Methods DOES NOT send/recieve variables, they just send/ receive the data inside variables



METHODS WITH SPECIFIC RETURN TYPE

Let's write a code which asks user for value, send it as arguments, then the method returns another value, and we will print that value. 
To return a value just write return in the end of assistant method and the value you want to return in front of it.
It will return that value to exact that place in main method from where you called the assistant method. Here again you need a variable to store it. So in that case we first create a variable, write "=", and then call the method. Therefore the returned value is directly assigned to the variable.

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);


        // Asking user for a number

        System.out.print("Enter a number: ");

        int number = input.nextInt();


        // Sending the number as an argument to the assistant method and when the method return value we will store it in 'result'

        int result = squareNumber(number);


        // Printing the returned value

        System.out.println("Square of " + number + " is: " + result);


        input.close(); //closes the scanner we created

    }


    // Assistant method: takes a number as parameter and returns its square

    public static int squareNumber(int n) {

        int a = n * n;

        return a;

    }

}



OUTPUT:

Enter a number: 7 Square of 7 is: 49 
  

EXERCISE

Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.


import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);


        // Asking the user for two numbers

        System.out.print("Enter first number: ");

        int num1 = sc.nextInt();


        System.out.print("Enter second number: ");

        int num2 = sc.nextInt();


        // Calling assistant methods

        int sum = addNumbers(num1, num2);   // returns a value

        int product = multiplyNumbers(num1, num2); // returns a value


        // Calling a void method (just prints)

        printResults(num1, num2, sum, product);


        sc.close(); //closes the scanner we created

    }


    // Assistant 1: adds two numbers and returns result

    public static int addNumbers(int a, int b) {

        return a + b;

    }


    // Assistant 2: multiplies two numbers and returns result

    public static int multiplyNumbers(int a, int b) {

        return a * b;

    }


    // Assistant 3: void → prints results, does not return anything

    public static void printResults(int x, int y, int sum, int product) {

        System.out.println("You entered: " + x + " and " + y);

        System.out.println("Their sum is: " + sum);

        System.out.println("Their product is: " + product);

    }

}



OUTPUT:

Enter first number: 4 Enter second number: 6 You entered: 4 and 6 Their sum is: 10 Their product is: 24 
  

MINI PROJECT: (Calculator with Methods)

Your project is to create a simple Java calculator using methods. The program should ask the user to enter two numbers. Show a menu of operations:

⦿ 1 → Addition
⦿ 2 → Subtraction
⦿ 3 → Multiplication
⦿ 4 → Division

The user chooses one operation. The program should call the correct assistant method to perform that operation. Print the result in a neat format using printf.

Example: addNumbers(int a, int b) returns the sum.

Example: printResult(int result) just prints (void).

Rules:

Use Scanner for input.

Create at least 4 separate methods:

One for addition, one for subtraction, one for multiplication, one for division.

Use arguments, parameters, return values, and void methods.

Handle division carefully (if the second number is 0, print “Invalid: Division by Zero”).

Bonus (Optional):

After showing the result, ask the user if they want to perform another calculation. If yes, repeat the process.



EXAMPLE OUTPUT:


Enter first number: 12 Enter second number: 4 Choose operation: 1 → Addition 2 → Subtraction 3 → Multiplication 4 → Division Your choice: 3 Result: 12 * 4 = 48 Do you want to perform another calculation? (yes/no): no Goodbye!   
  



CLOSING

That’s it for methods in Java! Methods are like your program’s assistants, they let you organize code into reusable, focused tasks. Once you understand how to pass data (arguments), receive it (parameters), and sometimes return results, your programs become cleaner, more powerful, and much easier to manage. 

You can re-use any method as much as you like. Code them once and use them multiple times