Java Function

Function in Java

In Java, a function is also known as a method. A method is a block of code that performs a specific task or action. Methods in Java help organize code into reusable modules, reducing redundancy and improving code maintainability.
A method in Java typically has a return type and a name and may accept input parameters.

Basic Syntax:

<access modifier> <return type> <method name>(<parameters>)
{
    // Method body
}

  • Access Modifiers: Methods in Java can have access modifiers like public, private, protected, etc., which control the accessibility of the method from other parts of the program.
  • Return Type: Methods may return a value of a specified data type using the return If a method doesn’t return anything, its return type is specified as void.
  • Parameters: Parameters are used to pass data to the method for processing. Methods can accept zero or more input parameters.
Basic Method

Scenario: Create a program that:
1. Defines a custom method named message() that prints “Hello World!” to the console.
2. Calls this custom method in the main method.

Scenario 1: Custom method with the static keyword—allowing direct method calls without creating an instance of the class.

Scenario 2: Custom method without the static keyword—requiring an instance of the class to access the method.

class Program {

    public static void message() {

        System.out.println(“Hello World!”);

    }

 

    public static void main(String[] args) {

        message();

    }

}

 

 

class Program {

    public void message() {

        System.out.println(“Hello World!”);

    }

 

    public static void main(String[] args) {

        Program program = new Program();

        program.message();

    }

}

 

Output: Hello World!

Output: Hello World!

 

Explanation of Scenario 1: In this example, the message() method is declared as static, so it can be called directly from the main method without needing to create an instance of the Program class.

Explanation of Scenario 2: Here, the message() method is not declared as static, so you need to create an instance of the Program class (Program program = new Program();) to call the message() method.

In the below image as you can see we have to create an instance of the class like  (Program call = new Program(); )   and call that function like ( call.Message(); )so the function will be called and output will be  Hello, World! In console.

Method with Parameters & Return Type
Scenario: Create a custom method with parameters and a return type. The method should:
    ● Take two integers as input, add them, subtract the sum from 20, and return the result.
    ● The method will be called in the main method.

Scenario 1: Custom method with parameters and a void return type.

Scenario 2: Custom method with parameters and an int return type.

class Program {

    public static void operation(int num1, int num2) {

        int add = num1 + num2;

        int subtract = 20 – add;

        System.out.println(subtract);

    }

 

    public static void main(String[] args) {

        operation(4, 5);

    }

}

 

class Program {

    public static int addition(int num1, int num2) {

        int add = num1 + num2;

        return add;

    }

 

    public static void main(String[] args) {

        int sum = addition(4, 5);

        int subtraction = 20 – sum;

        System.out.println(subtraction);

    }

}

 

 

Output: 11

Output: 11

Scenerio1 Explanation:

class Program {

Defines a new class called Program. In Java, all code must be inside a class.

public static void operation(int num1, int num2) {

Declares a method named operation that:
              ■ Is public (can be accessed from outside the class).
              ■ Is static (belongs to the class and can be called without creating an instance of Program).
              ■ Has a void return type (does not return a value).
              ■ Accepts two integer parameters: num1 and num2.

int add = num1 + num2;

Adds num1 and num2 and assigns the result to the variable add.
For the input values 4 and 5, add will be 9.

int subtract = 20 – add;

Subtracts the value of add from 20 and stores the result in the variable subtract.
With add as 9, subtract will be 20 – 9 = 11.

System.out.println(subtract);

Prints the value of subtract to the console.
This will output 11.

public static void main(String[] args) {

Declares the main method, which serves as the program’s entry point. Java runs this method first.

operation(4, 5);

Calls the operation method and passes 4 and 5 as arguments for num1 and num2.
This executes the code inside the operation method, ultimately printing 11.
Output: 11

Scenerio2 Explanation:

class Program {

Declares a new class named Program, which contains the methods for this program.

public static int addition(int num1, int num2) {

      ○ Declares a method named addition that:
                ■ Is public (accessible outside the class).
                ■ Is static (belongs to the class and can be called without an instance).
                ■ Has an int return type (returns an integer).
                ■ Accepts two integer parameters: num1 and num2.

int add = num1 + num2;

      ○ Adds num1 and num2 and assigns the result to the variable add.
      ○ For inputs 4 and 5, add will be 9.

return add;

Returns the value of add (which is 9) to the method that called addition.

public static void main(String[] args) {

Declares the main method, which is the starting point for the program.

int sum = addition(4, 5);

      ○ Calls the addition method with 4 and 5 as arguments, which returns 9.
      ○ Stores the returned value (9) in the variable sum.

int subtraction = 20 – sum;

      ○ Subtracts sum from 20 and stores the result in the variable subtraction.
      ○ With sum as 9, subtraction becomes 20 – 9 = 11.

System.out.println(subtraction);

      ○ Prints the value of subtraction to the console.
      ○ This outputs 11.
Output: 11

Tasks:
1. Calculate Factorial: Create a method calculateFactorial that takes an integer and returns its factorial. Use a for loop inside the method. Use an if-else statement to handle negative inputs by returning -1.
2. Check Prime: Create a method isPrime that takes an integer and returns true if it’s a prime number and false otherwise. Use a for loop and an if statement to check for primality.
3. Sum of Even Numbers: Create a method sumOfEvenNumbers that takes two integers as the range and returns the sum of all even numbers in that range. Use a for loop and an if statement inside the method. Use a continue statement to skip odd numbers.
4. Guessing Game: Create a method playGuessingGame that generates a random number and prompts the user to guess it. Use a do-while loop, if-else statements, and a break statement to handle the guessing logic.
5. Temperature Conversion: Create a method convertCelsiusToFahrenheit that takes a double representing Celsius and returns the equivalent Fahrenheit. Create another method printTemperatureCategory that takes a temperature in Fahrenheit and uses a switch statement to print “Cold”, “Warm”, or “Hot”.
6. Menu Display: Create a method displayMenu that prints a menu and returns the user’s choice. Use a while loop to keep displaying the menu until the user chooses to exit. Use a switch statement to handle menu options.
7. Fibonacci Sequence: Create a method printFibonacciSequence that takes an integer n and prints the first n numbers of the Fibonacci sequence. Use a for loop and an if statement to handle the sequence generation. Use a break statement if the sequence exceeds a certain number.

Course Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

In Java, a method is a block of code that performs a specific task and is associated with a class or object. Methods define the behavior of objects and can be called to execute the defined functionality.

The training covers defining methods, calling methods, method overloading, and accessing methods from other classes.

It is designed for beginners who want to understand Java methods step-by-step.

Yes, the tutorial is available for free on the Iqra Technology Academy website.

Yes, the tutorial is beginner-friendly and does not require prior programming knowledge.

Yes, the training is fully accessible online and can be completed at your own pace.

Defining methods, passing parameters, using return types, and overloading methods.

Yes, examples include creating and calling methods with and without parameters.