About us

Join us FREE!

Java Variables

Tutorial by Er Satya connectclue-author-image

All > Tech Blogger | Java | Spring Boot | HTML | CSS | MySQL > Java | Spring Boot

1 like

Please login to like this article.

connectclue-linkedin-share

Java Variables - A variable is a container that holds the value while the Java program is executed. A variable is assigned with a data type. The variable is the name of a memory location. 

A variable is the name of a reserved area allocated in memory. In other words, it is the name of the memory location. It is a combination of "vary + able" which means 
its value can be changed.


Types of Variables

There are three types of variables in Java:

local variable
instance variable
static variable


1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class 
aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.


2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.


3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all 
the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.


Example 

public class A  
{  
    static int x=10;    //static variable  
    void method()  
    {    
        int y=20;        //local variable    
    }  
    public static void main(String args[])  
    {  
        int data=100;//instance variable    
    }  



Java Variable Example: Add Two Numbers

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




connectclue-linkedin-share

More articles:


Recent lost & found:


Login for enhanced experience

connectclue-tick Create and manage your profile

connectclue-tick Refer an author and get bonus Learn more

connectclue-tick Publish any lost and found belongings

connectclue-tick Connect with the authors & add your review comments

connectclue-tick Join us for Free to advertise for your business or Contact-us for more details

connectclue-tick Join us for Free to publish your own blogs, articles or tutorials and get your Benefits

connectclue-login

Back to top