Saturday, July 11, 2020

Variables in JAVA, Variable declaration, Rules to declare Variable, Syntax

Variable :
A variable is a container which holds the value. Variable is nothing but name of memory location.

Declaration of Variables:

Syntax :

     1) single variable :
       type variable_name;

  2)Multiple variables:
     type variable_name, variable_name, variable_name;

Here, the meaning of type is data type. It specifies what type of data the variable will hold.

Example :
int var = 10;


here, varible is created with name var of int data type which hold value 10.

Rules to Declare variables:

1) Variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and two special
     characters such as underscore(_) and dollar Sign($).

2) The first character must be a letter.

3) Java Reserved keywords cannot be used as variable names.

4) Variable names are case-sensitive.

5) Variable name can’t start with digit.

6) Variable name can start with $ or _ .

Types of variables :

1) Local Variable:

Local variable is declared inside the body of the method I.You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. local variable cannot be defined with "static" keyword. Local variable must be initialized before use.

class Test{

void method(){

int number = 90; //local variable

}

System.out.println(n); //it will show an error

}

2) Instance Variable:

Instance variable declared inside the class but outside the body of the method .It is not declared as ststic. It is called instance variable because its value is instance specific and is not shared among instances. Each instance has its own unique instance variable value. Instance variables are initialized when class instance is created.
class A
{
int var1; //instance variable
}

3) Static variable

Staic variable is declared with static keyword. It cannot be local. single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.

static int m = 100;   //static variable


4) Final Variable :-

A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. data within the object can be changed. So, the state of the object can be changed but not the reference. final modifier often is used with static to make the constant a class variable.
public class Test {
final int value = 10;

public void changeValue() {

value = 12; // it will give an error

}

}








0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home