Thursday, July 11, 2019

Variables And Datatype







Variable

Variable is name of reserved area allocated in memory. In other words , it name of memory location. It is a combination of "very+able" that means its value can be changed.
Example:
int data=10;
here data is variable.

There are three types of variables in java:
  • Local Variable
                   A variable which is declare inside the method is              called local variable.
  • Instance Variable
                   A variable which is declared inside the class but outside the method, is called instance variable. It is not declared as static.
  • Static Variable  
                  A Variable that is declared as static is called static variable. It cannot be local. 
Example for better understanding variables
Class A{
  int data=50;//instance variable
static int m=20;//static variable
void method(){
int n=90;//local variable
}
}//end of class

        Data Type in Java
Datatype represents the different values to be stored in the variable. In java, there are two types of datatypes:
  • Primitive data type 
  • Non-primitive data type  
 
Data type          Default Value           Default Size

Boolean                             false                                      1 bit
Char                                  '\u000'                                    2 byte
Byte                                   0                                            1 byte
Short                                  0                                            2 byte
Int                                      0                                            4 byte
Long                                  0L                                          8 byte
Float                                  0.0f                                        4 byte
Double                              0.0d                                        8 byte

Why char uses 2 byte in Java and what is \u0000? 
It is because java uses Unicode system than ASCII code system. The \u000 is the lowest range of Unicode system. 

Java variable example: Add Two Numbers

          class add {
          public static void main(String [] args){
          int a=10;
          int b=10;
          int c=a+b;
         System.out.println(c);
         } 
      }
Output: 20

Java variable example : Narrowing (Typecasting)
            class Type{
             public static void main(String [] args){
             float f=10.5f;
            //int a=f;//compile time error
            int a=(int)f;
            System.out.println(f);
            System.out.println(a);
             }
           }
Output:
10.5
10


No comments:

Post a Comment

                                    ARRAY IN JAVA Normally, array is a collection of similar type of elements that have contiguous memo...