Computer Science, asked by Prasanma, 1 year ago

difference between local variable and instance variable

Answers

Answered by Rajdeep11111
7
HELLO FRIEND!!

What is the difference between a local variable and an instance variable?

Here's your answer:

A local variable is the variable that is declared or defined within a particular method, and the scope of which is limited only to the method. The variable is not global to the class.

Consider the following program snippet:
class Sample
{
public static void main (String args[])
{
Sample obj = new Sample();
int a = 5, b = 10;
int x = obj.Add(a, b);
System.out.println("The sum is: " + x);
}

public int Add(int n1, n2)
{
int sum;
sum = n1+n2;
return (sum);
}
}

In the above program code, consider that the variable sum is a local variable because it is declared within the method 'Add' and cannot be used in the main method or in any other methods.





An instance variable is a non-static variable which is global to the class, and multiple copies of it are available for all objects of the class (since it is n on-static). An instance variable can be changed into a static variable by using the keyword 'static' with it.

Consider the following program snippet:

class Sample2
{
int a = 2, b = 3;
void Add()
{
int sum = a + b;
System.out.println("Sum is" + sum);
}
void Diff()
{
int x = a - b;
System.out.println("Difference is: " + x);
}
}

In the above program, variables a and b are instance (global) variables because they can be accessed by both the methods, Add and Diff.



THANKS.
Hope my answer is satisfactory.
Best of luck for your exam tomorrow!

Prasanma: thx
ayushi114: thanks
Rajdeep11111: You are most welcome.
Answered by chaitanyakrishn1
7
Local variables

They are accesible only within the method in which they are declared.
Their life span is within its method.
They belong to individual instances of class.
Any change in local variables affects only that particular object.
THIS keyword can be used with it.

Class variable

They are accesible throughout the class.
Their life span is within the class.
They belong to the class jtself.
Any change in affects all instances (objects).
THIS keyword cannot be used with it.

hope it helps

Thank u ★ ★ ★
#ckc

Prasanma: welcome
chaitanyakrishn1: Plz mark brainliest I have given so many points of difference
Similar questions