Open In App

Local Variables in Java

Last Updated : 03 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The variables declared inside the body of the method are termed local variables. A function is a collection of statements that are designed to perform a specific task. Functions take certain input(s) and its parameter and give output or return value. A function is created that one can not have to write the same code, again and again, we call to use it as many times just by calling the function name.

public static return_type function_name(parameter 1, parameter 2, .....)
{
    // Body of function
    // or set of statements    
}

Illustration: Adding two numbers

Java




// Java Program to Illustrate A Method
// Which Adds Up Numbers
 
// Method
// Using two parameters of integer data type
// With integer return type
public static int add(int a, int b)
{
 
    // Creating a sum to add the numbers
    int sum = a + b;
 
    // Returning the sum of int data type
    return sum;
}


Here input to the functions are the numbers and their output is the sum

What is Return Type?  

A function may return a value. The return type of a function is the data type of the value of the function return. The return type of function can be on any data type but sometimes it is not required to return the function so use the void return type. In void return type function did not return any value. Now let’s get an example for a better understanding of it.

Example 1:

Java




// Java Program to Illustrate Return Type
// In a Method
 
// Class
public class GFG {
 
    // Method 1
    // To compute area of circle
    public static double Area(double radius)
    {
 
        // Computing area of circle
        double area = radius * radius * 3.14;
 
        // Returning computed area
        return area;
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input
        double radius = 4.4;
 
        // Calling method and storing result
        double answer = Area(radius);
 
        // Printing area of circle on console
        System.out.println(answer);
    }
}


Output

60.79040000000001

Example 2:

Java




// Java Program to Illustrate Return Type
// In a Method
 
// Class
class GFG {
 
    // method 1
    // We are using void return type
    public static void printAverage(int a, int b)
    {
        // Calculating average
        int avg = (a + b) / 2;
 
        // Printing the average of input numbers
        System.out.print(avg);
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Input numbers
        int a = 15;
        int b = 25;
 
        // Calling method 1 inside main() method
        printAverage(a, b);
    }
}


Output

20

Why Do We Need a Function?

  • Reusability: Once a function is created, it can be over and over again. you can call the function as many times as we need it, which saves work and time. now suppose you are required to find the area of a rectangle, now we have to option one we can apply a formula each time to get the area or we can just make a function for finding the area of the rectangle and call the function whenever we need it
  • Easy Debugging: It is easy to find the error and correct the code in a function as compared to raw code without a function where you must correct the error(if required) everywhere the specific task of the function is performed.
  • Neet code: A code created with a function is ready o read and dry run. You don’t need to type the same code, again and again, instead you can invoke the function it is needed.
  • Modularisation: Modularisation means to divide the code into small modules (part) each performing its specific task. Functions help in doing so as they are the same fragment of the program designed to perform the specific task.

How does function calling work?

The function begins called is called by the callee(name of the function) and the function which calls the callee is the caller. When a function is called, program control goes to the entry point of the function. Entrypoint is where the function is defined. So focus now to shift to the callee and the caller function and the caller function goes in paused state.

Java




// Java Program to Illustrate Working Of Function Calling
 
// Class
class GFG {
 
    // Method 1
    public static int findsum(int a, int b)
    {
        int sum = a + b;
        return sum;
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        int a = 10, b = 20;
        int c = findsum(a, b);
 
        System.out.print(c);
    }
}


Output

30

Here in the above example, the code entry point of the function findsum() is at line number 2. so when the function calls occur the control goes to findsum() (line 2), then after that the statement in the function findsum() is executed the programme control comes back at last.

Local Variable and Scopes 

A local variable is a variable that is given a local scope. Local variable belonging to a function or a block has their scope only within the function or block inside which it is declared. The scope of a variable is part of a program for which this variable is accessible.

The lifetime of a variable: The lifetime of a variable is the time period for which the declared variable has a valid memory. Scope and lifetime of a variable are two different concepts, the scope of a variable is part of a program for which this variable is accessible whereas lifetime is the duration for which this variable has a valid memory.

Pass by Value: When the parameters are passed to a function bypass by the value method, then the formal parameters are allocated to a new memory. These parameters have the same value as that of actual parameters. Since the formal parameters are allocated to new memory any changes in these parameters will not reflect the actual parameter.

Note: Java only supports pass by value because of object-oriented language because of which every time we need to create an object making a pass by references impractical and out of bound.

Example:

Java




// Java Program to Illustrate variable and Scopes
// Inside a Method
 
// Class
public class GFG {
 
    // Method 1
    public static void increase(int x, int y)
    {
        x++;
        y = y + 1;
 
        // Print statement
        System.out.println(x + " : " + y);
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        int a = 10;
        int b = 40;
 
        increase(a, b);
 
        System.out.println(a + " : " + b);
    }
}


Output

11 : 41
10 : 40

For the above code, changes in the values of x and y are not reflected a and b because x and y are formal parameters and are local to function increment so any changes in their values here won’t affect variables a and b inside the main.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads