Hello Readers !!!

What is variable ???

This is mostly asked questions when you enter in any Programming field (JAVA,PHP,Android,C++,C# etc.). And the definition is same for all programming languages. In simple words variables are container which are used to store some values. value should be anything.

for example

  int a = 10;

in given example a is a variable and we are storing 10 into variable a. and we make that variable as int becase 10 is of int type data. in int type data we can’t store a,b,c. To store a,b,c we need to change type of variable a to char or String. because a,b,c are alphabet. so we will store like this :

  char a = 'a';
  char demo = 'b';
  String test = "abc";

To store single character we use char and it should be written inside single quotes (‘’), and to store a word or sentence we need to use String as data type and it should be written inside double quotes (“”).

Type of variable depend on which type of data we are going to store in it.

Variables are of two types:

  1. Primitive Data type
  2. Complex objects

Primitive type :

Primitive objects are normal variables like int, char, float etc. We can arrange them in list like below

  • Single character (A,B,C,1)
  • Boolean (true/false)
  • Numerical values (float, int, double etc.)

Complex variables :

Complex variables are those variables which is made from Class. It should be built in class or custom class. If any variables are made from class is count under complex variables.

  • String
  • Date
  • Integer

These are variables of classes so its count under complex variables.

How to declare variables

Primitive variables are declared in 3 parts :

  • Data type of variable (*Required)
  • Name of variable (*Required)
  • Initial Value of variable (optional)

for example as shown in below image : variable

Complex variables are declared as below:

  • Complex variables are Instance of Class.
  • Complex variables use new keyword and Constructor of that class.
  • It contains value of class, because its Instance of that class.

for example :

MyClass test = new MyClass();

Declaration type of variables:

  1. Local Variables
  2. Global Variables (it’s also known as Instance variables)

Local Variable :

Local Variables are declared and initialize inside Method, and their scope is only inside that class.

For example

class First{
  public static void main(String[] args){
    int num = 10;

Global Variables:

Global Variables are declared outside the methods but inside class. It is also called as Instance variables. Global Variables are accessible from every methods and inner classes of that class. It is also available for derived class if Global Variables are declared as public.

for example

class First{
  int num = 10;
  public static void main(String[] args){