Java Variable Types and Rules for Declaring Variables

Variable is nothing it is just the name of memory location.
While declaring variables we must follow rules given below.
Java Variable Types and Rules for Declaring Variables

Rules for Declaring Variables in Java

1. Variable name must bound with data type. It means while
declaring a variable we must specify its data type.
Ex: int x=10;
2. Reserve word or keywords cannot be taken as a variable
name.
3. C
supports 32 character long variable names while in Java the length of variable
name can be infinite.
4. Nothing except 0-9, A-Z, a-z, _, $ can be used in variable
name.
5. Variable name must not start with numeric and special
characters are also not allowed.
Example:
intabc=7; (valid)
int _abc=8; (valid)
int abc8=9; (valid)
int 8abc=10 (invalid)
int $_abc=12; (valid)
int $_abc*=15; (invalid)
6. Variable name should be meaningful.
Example:
string i=”Raj”; 
//valid but not meaningful
string name=”Raj”; //valid and meaningful
Note: Local variables must be initialized before first use.
class demo
{
                public
static void main(String…s)
                {
                                int
x;      //must be initialized
                                System.out.println(x);
                }
}

Java Variable Types

There are three types of variables in Java that are
instance, local and static.

1. Instance Variables

Instance variables are declared in a class, but outside any
method, constructor or block.

2. Local Variables

Local variables are declared in methods, constructors or
blocks. It must be initialized before first use.

3. Static Variables

Static variables are declared with the static keyword in a class, but outside any method, constructor or block.
class A
{
                int
x=12;               //instance variable
                staticint
y=13;    //static variable
               
                public
static void main(String…s)
                {
                                int
z=30;               //local variable
                                System.out.println(x);
                                System.out.println(y);
                                System.out.println(z);
                }

}

Leave a Comment

Your email address will not be published. Required fields are marked *