A variable is a container it holds the value. The variable must assign with data types. Depends on it holds the memory and value.
Variable declaration and initialization:
Data type variable = value , variable1 = value…
Example:
int x, y; // Declares two ints, x, y.
int x = 100, b = 20; // Example of initialization
float A = 12; // initializes a float type variable A.
char b = 'b'; // the char variable b is initialized with value 'b'
There are three categories of variables available in java.
1. Local variables
2. Instance variables
3. Static variables
Local variables:
It is declared inside method of the class. We cannot access it outside from the class. For the local variable we have to assign the value there is no default value.
Example:
public class sample { public void agecalc() { int x = 0; x = x + 5; system.out.print(" age of person is : " + x); } public static void main(String args[]) { sample obj1 = new sample(); obj1.agecalc(); } }
Output:
age of person is : 5
Instance variable:
It is defined without keyword STATIC keyword. It is defined outside method declaration. These variables are created when object created and destroyed when object is destroyed.
Example:
public class student { public String name; private float mark; public student (String sname) { name = sname; } // The mark value is assigned. public void getmark(float smark) { mark = smark; } public void printstu() { System.out.println("name : " + name ); System.out.println("mark :" + mark); } public static void main(String args[]) { student s1 = new student("mani"); s1.getmark(100); s1.printstu(); } }
Output:
name : mani
mark : 100.0
Static Variables:
It is declared with keyword STATIC. It is access by class name. It is initialized first only once. It is also known as class variable.
Example:
public class student { // mark variable is private and static private static float mark; // subject is a constant public static final String SUBJECT = "Tamil"; public static void main(String args[]) { mark = 75; System.out.println(SUBJECT + "average Mark:" + mark); } }
Output:
Tamil average mark: 75
Follow Us