Java Variable and Data Type




Variable

Variables are names used to refer some location in memory – a location that holds a value with which we are working. 

Before a program utilizes memory to store a variable it must claim memory needed to store the values for a variable.  This is done by declaring variable. Declaring variable is way in which program shows number of variables needed, what they are going to be named, and how much memory they will need.

Declaring, Initializing and Assigning variables

 

Declare variable


While declaring variable we need to specify 2 things:

  • Data type : We must specify type of data variable is going to store. There are specific keywords to do this. We’ll look at them in data type section.

  • Name: A variable must have some name, this can be used in further code to access memory location pointed by it.

Syntax for declaring variable is:

                Datatype variableName;

Eg. int num;

Here variable of type int has been declared whose name is num.
We can declare multiple variables of same type in single statement:
                int num1, num2, num3;

Initialize variable


When variable is declared it doesn’t have any value stored. We need to initialize variable with some value as:

                int num = 10;

Assign variable

 

You can assign value of one variable to another.

                int another_num = num;

So, value of another_num is 10.

Types of variables

 

There are 3 types of variables in Java.
  • Local variable
  • Instance variable / non-static variable
  • Static variable

Local Variable

 

Variable declared inside method is called as local variable.

It is only accessible inside method in which it is declared.

public void sum(){
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
} 

Inside method sum() variables declared num1, num2 and sum are local variables. If you try to access these variables inside other method, you will get compile time error.

Instance/ Non-static Variable

 

Variable which is declared inside a class but outside the method is called as instance variable. Before understanding instance variable in detail lets discuss 2 Object Oriented programming concepts: class and object.

Java is OOP language. While coding we take reference of real world entities. For example, if I have to write code for Dog, I will take reference of real world entity named “Dog”. Dog has some properties like name, color etc and behavior like bark, run. This entity is called as object in programming.

In industry, if I have to create similar objects then we create a mould for it. We can also say it as blueprint of object. In OOP, similar concept of mould is used to create multiple objects of same type, which is known as class. Currently, I have to write code for my dog “puppy” but in future I may wish to write code for more dogs. So what I am going to do is create a class named Dog. Using class I will create “puppy”. Code looks like this.


class Dog{
    String name;
    String color;
   
    void bark(){
         //some code
    }
    void run(){
         //some code
    }

    public static void main(String args[]){
         //code for creating puppy
        Dog puppy = new Dog();
         puppy.name = “puppy”;
         puppy.color = “white”;
         puppy.bark();

         //code for creating doggy.
         Dog doggy = new Dog();
         doggy.name = “doggy”;
         doggy.color = “gray”;
         doggy.run();
    }
}

When object puppy is created from class Dog, it gets separate existence into memory. Separate variables (name and color) are created for it. Both objects are isolated in memory.

So you got what is class and object. Let’s come to original topic.

As mentioned, variable which is declared inside a class but outside the method is called as instance variable. Here variables name and color are instance variables. By default, each object when created it gets separate copy of these variables and methods as well. So I can say, puppy.name belongs to puppy object. They are not shared with doggy object. doggy has its own name and color. Thus these variables are called as non-static variables.

Static variable

 

Suppose I have to add one more property to all dogs named category with value as animal. As studied earlier, I can add an instance variable in class Dog and after creating object I can assign value to category as object.category = “animal”. 

When object is created each time all data members will get separate memory allocated. Each dog will have distinct name ,color and category. Name and color as instance variable are good. Category refers to common property of all objects. If I create a shared variable named category for all objects then it will get memory only once. This shared variable is called as static variable.
 



Do you know
·         As static variable is shared among all objects, it has class level scope. It cannot be a local variable.
·        Object level variable is accessed as object.variable_name. Class level variable is accessed as Class_Name.variable_name.
·         Static variables are created and initialized when class is first loaded. That happens when static member of class is referred somewhere or instance (object) of class is created, whichever comes first.

Example,

class Dog{
    String name;
    String color;
    static String category = “animal”;
   
    void display(){
         System.out.println(name+”  “+color+” “+category);
    }
   
    public static void main(String args[]){
         //code for creating puppy
         Dog puppy = new Dog();
         puppy.name = “puppy”;
         puppy.color = “white”;
         puppy.display (); //puppy white animal

         //code for creating doggy.
         Dog doggy = new Dog();
         doggy.name = “doggy”;
         doggy.color = “gray”;
         doggy.display (); //doggy gray animal
        
    }
}

Output:

puppy white animal
doggy gray animal

We are going to discuss about static variable in more detail in upcoming tutorial.



Datatype


Variables are used to store data in memory. To declare variable data type is required. Based on data type operating system allocates memory and decides what can be stored in reserved memory.

Data types are mainly divided into 2 parts:

  • Primitive data types
  • Non-primitive data types
 




Primitive data type

 

Primitive data types are predefined by language and named by a keyword. There are 8 primitive data types supported by Java.



Type
Description
Default
Size
Range
Example
byte
Signed two’s complement integer
0
8 bit
(1 byte)
-128 to 127
100,-50
short
Signed two’s complement integer
0
16 bit
(2 bytes)
-32768 to 32767
1000,-20000
int
Signed two’s complement integer
0
32 bit
(4 bytes)
- 2,147,483,648 to 2,147,483,647
7000,-9000
long
Signed two’s complement integer
0L
64bit
(8 bytes)
-263 to (263 -1) 
10000L
float
IEEE 754 floating point
single-precision
0.0f
32 bit
(4 bytes)
±1.4E-45 to
±3.40282347E+38F
100.20f
double
IEEE 754 floating point
double-precision
0.0d
Or
0.0
64bit
(8 bytes)
±439E-324 to
±1.7976931348623157E+308
50.70d,
500.6
char
Unicode character
unsigned
\u0000
16 bit
(2 bytes)
0 to 65,535 or
\u0000 to \uFFFF
'A'
boolean
True or false
false
1 bit
True or false
True, false
 




Non-primitive data type

 

Non-primitive data types are not defined by programming language, but are instead created by programmer. They are also called as reference variables or object references, since they reference memory location, which stores data.

String , class objects and array variables come under non-primitive data types.

Default value of any non-primitive data type is NULL.
 

Do you know : Why data types are classified as primitive and non-primitive
Primitive data types have just one value to store. For instance, int i=1; The required space allocated variable is stored in memory as it is.

In case of non-primitive data types, for instance an object, must be stored differently because they are more complex. Generally object has multiple values. All these values need to be stored in memory and association between each value and object must be maintained throughout object’s life.

To serve purpose, there are 2 kinds of memory used in Java, named stack memory and heap memory.

Stack memory
Stack memory stores primitive data types and memory location of heap where object is stored.

Heap memory
Object values are stored in heap memory. Variable in stack labeled with object’s name stored address of object stored in heap memory.

Stack memory is program’s memory and heap memory resides outside of program.

 

In diagram, there is a code where ‘a’ is a variable with primitve data type and ‘test’ is a variable with non-primitive data type. In stack memory, a is stored as it is with value 1. In heap memory, test object value is stored and pointer to object is stored in stack.



 



No comments:

Post a Comment

Operators in Java

Operator is a symbol which is used to perform operation on data. Eg. +,-,/,* etc. Do you know : Operator and operan...

Popular