What
is a Variable?
A
variable can be thought of as a container which holds value for you during the
life of your program. Every variable is assigned a data type which
designates the type and quantity of a value it can hold.
Syntax:
Variable_name =
value;
Rules to declare a Variable
Ø Every variable name should start with either alphabets or
underscore ( _ ) or dollar ( $ ) symbol.
Ø No space are allowed in the variable declarations.
Ø Except underscore ( _ ) no special symbol are allowed in
the middle of variable declaration
Ø Variable name always should exist in the left hand side
of assignment operators.
Ø Maximum length of variable is 64 characters.
Ø No keywords should access variable name.
Variable declarations
In which sufficient
memory will be allocated and holds default values.
Syntax
Datatype variable_name;
byte b1;
Variable initialization
It is the process of storing user defined values at the time of
allocation of memory space.
Variable assignment
Value is assigned
to a variable if that is already declared or initialized.
Syntax
Variable_Name = value
int a = 100;
Types of Variable
Ø There
are three types of variables in java:
Ø local
variable
Ø instance
variable
Ø static
variable
Ø Instance variables
Instance
variables are variables that are declare inside a class but outside any
method,constructor or block. Instance variable are also variable of object
commonly known as field or property.
class Student
{ String name;
int age;
}
Here name and age are instance variable of Student
class.
Ø Static
variables
Static are class variables declared with static keyword. Static
variables are initialized only once. Static variables are also used in
declaring constant along with final keyword.
class Student
{
String name;
int age;
static int instituteCode=1101;
}
Here instituteCode is a static variable. Each object of
Student class will share instituteCode property.
Ø Local
variables
Local variables are declared in method constructor or blocks.
Local variables are initialized when method or constructor block start and will
be destroyed once its end. Local variable reside in stack. Access modifiers are
not used for local variable.
float getDiscount(int
price)
{
float discount;
discount=price*(20/100);
return discount;
}
Here discount is a local variable.
Comments
Post a Comment