Wednesday, January 13, 2021

Variables in Java

Variables in Java

A variable is a name given to a memory location. It is the unit of storage in the program. The value stored in a variable can be changed during program execution.
For example- int a;   // where int is data type and a is variable

Java variables type:

Local variable
Instance variable
Static variable

Local variable:

A local variable is declared inside the body of the method is called the local variable. A Local variable cannot be defined with a static keyword. No object requires to access the Local variable. The scope of these variables exists only within the method in which variable the variable is declared.

Instance variable:

An instance variable is declared inside the class but outside the body of the method is called the Instance variable. It is not declared with the static keyword. These variables are accessed through the object of the class. 

Static variable:

A static variable is declared inside the class but outside the body of the method with the static keyword is called Static variable. It is similar to the instance variable but the difference is the static variable declared with the static keyword while the instance variable declared without the static keyword.

Sample program:

public class Variables{
static int a=10; // static variable
int b=20;  // Instance variable
public static void main(String args[]){
int c=30;  //Local variable
System.out.println("static variable is:"+a);
System.out.println("local variable is:"+c);
Variables obj=new Variables(); //object created for instance variable
System.out.println("instance variable is:"+obj.b);
}
}

For instance, variable if we do not create an object it gives an error. Let's see
public class Variables{
static int a=10;
int b=20; // In this program no object create for instance variable
public static void main(String args[]){
int c=30;
System.out.println("static variable is:"+a);
System.out.println("local variable is:"+c);
System.out.println("instance variable is:"+b);
}
}
Arrow mark show error when no object create for instance variables





No comments:

Post a Comment

Data Types in Java

 Data Types in Java Data Type in Java is defined as that specifies the size of memory allocated for a specific variable and which type of va...