Java Variables | infoStud blogs

A variable is a name given to a memory location that holds the value while the Java program is executed. A variable is appointed with a data type. 

Variable is the name of the memory area or location. There are three kinds or types of variables in java: local, instance, and static.

There are two kinds of data types in Java: 

  • Primitive
  • Non Primitive

Variable 

A variable is a name given to a memory location that holds the value while the Java program is executed. It is a blend of "vary + able" that implies its value can be changed.

Java Variables

Types of Variables

There are three types of variables in Java:

  • local variable
  • instance variable
  • static variable
Types of Variables


1) Local Variable 

A variable announced inside the body of the method is called a local variable. You can utilize this variable just inside that method and other methods in the class aren't even mindful that the variable exists. 

A local variable can't be characterized with a "static" keyword. 

2) Instance Variable 

A variable announced inside the class however outside the body of the method is called an instance variable. It isn't declared as static. 

It is called an instance variable since its value is instance explicit and isn't divided between instances. 

3) Static variable 

A variable that is declared as static is called a static variable. It can't be a local variable. You can make a single duplicate of static variables and divide between every one of the instances of the class. Memory allocation for static variables happens just once when the class is stacked or loaded in the memory.

Example to understand the types of variables in java


    class ABC{  
        int data=40;//instance variable  
        static int m=10;//static variable  
        void method(){  
        int n=80;//local variable  
        }  
        }//end of class  

Java Variable Example: Add Two Numbers

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

Output

25

Java Variable Example: Widening

        class Simple{  
            public static void main(String[] args){  
            int a=18;  
            float f=a;  
            System.out.println(a);  
            System.out.println(f);  
            }
        }  

Output

18

18.0

Java Variable Example: Narrowing (Typecasting)

        class A{  
            public static void main(String[] args){  
            float f=16.5f;  
            //int a=f;//Compile time error  
            int a=(int)f;  
            System.out.println(f);  
            System.out.println(a);  
            }
        }  

Output

16.5

16



Post a Comment

0 Comments