Instance variable:
we can declare variable in the class level not in the method level.
inside the method we can initialize the value for that variable declared.
Example:
public class School {
// Instance(Object) variable
int std;
int age;
public static void main(String[] args) {
// Object or Instance
School akshaya = new School();
akshaya.std = 10;
akshaya.age = 15;
System.out.println(akshaya.std);
System.out.println(akshaya.age);
School kiruthika = new School();
kiruthika.std = 7;
kiruthika.age = 12;
System.out.println(kiruthika.std);
System.out.println(kiruthika.age);
School karthick = new School();
karthick.std = 12;
karthick.age = 17;
System.out.println(karthick.std);
System.out.println(karthick.age);
Local variable:
It is inside the class and also inside the method that is called a local variable.
we cannot able to access from the different method.
Static variable:
It is initialized in the class level not a method level.
It is common for all the objects. we can use that variable in all the object if needed.
example:
public class School {
// static variable
static String school_name = "abc hr sec school";
public static void main(String[] args) {
School akshaya = new School();
System.out.println(School.school_name);
}
}
Global variable:
We can access the variable in side the any methodor all method.
Example for all:
package moduleOne;
public class School {
// Instance(Object) variable
int std;
int age;
// static variable
static String school_name = "abc hr sec school";
// Global variable
String leave = "10th standard";
public static void main(String[] args) {
// Object or Instance
School akshaya = new School();
akshaya.std = 10;
akshaya.age = 15;
System.out.println(akshaya.std);
System.out.println(akshaya.age);
akshaya.calculate(60, 70, 50, 80, 95);
System.out.println(School.school_name);
School kiruthika = new School();
kiruthika.std = 7;
kiruthika.age = 12;
System.out.println(kiruthika.std);
System.out.println(kiruthika.age);
kiruthika.calculate(40, 75, 85, 50, 75);
School karthick = new School();
karthick.std = 12;
karthick.age = 17;
System.out.println(karthick.std);
System.out.println(karthick.age);
karthick.calculate(45, 56, 59, 40, 94);
}
public void calculate(int tamil, int english, int maths, int science, int social) {
// Local variable
int total = tamil + english + maths + science + social;
System.out.println(total);
}
}
Top comments (0)