Solution:
Before everything else, we need to know:
# A local variable is declared in methods, constructors, or blocks.
# A local variable is visible only within the declared method, constructor, or block.
# Access modifiers cannot be used for local variables
See the program below:
public class Gavin {
public void myAge() {
int age;
age = age + 5;
System.out.println("My age is : " + age);
}
public static void main(String args[]) {
Gavin gavin = new Gavin();
gavin.myAge();
}
}
The following program will produce an error because I didn’t initialize the local variable before I use it. So I need to write the program this way:
public class Gavin {
public void myAge() {
int age=20;
age = age + 5;
System.out.println("My age is : " + age);
}
public static void main(String args[]) {
Gavin gavin = new Gavin();
gavin.myAge();
}
}
Now the program looks perfect and produces the age 25 as an output. I hope things are clear to you now.
Thanks.