Definition : In Java, all variable must be declared before they can be used. The variables are container that hold the address of data stored in your temporary memory or RAM for using in your further programming and developing some projects needs.
So just think as Variables as Container that contain your data that you feed to a random address and labelled it in your desired or required unique name and you can access it any time by calling and do any type operation like arithmetic or pass to any methods.
The basic form of a variable declaration is shown here :
dataType identifierName = value ; Example - byte myByte = 125; short myShort = 1245; int myInt = 25 ; float myFloat = 25.48f;
There are three kinds of variables in Java
- Class/static variables
- Local variables
- Instance variables
- Local variables are declared in methods, constructors, or blocks.
- Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
- Access modifiers cannot be used for local variables.
- Local variables are visible only within the declared method, constructor or block.
- Instance variables are declared in a class, but outside a method, constructor or any block.
- When a space is allocated for an object in the heap a slot for each instance variable value is created
- Instance variables are created when an object is created with the use of the key word ‘new’ and destroyed when the object is destroyed.
- Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an objects state that must be present throughout the class. Instance variables can be declared in class level before or after use.
- Access modifiers can be given for instance variables.
- Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
- There would only be one copy of each class variable per class, regardless of how many objects are created from it.
- Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants
- Static variables are created when the program starts and destroyed when the program stops.
- Static variables can be accessed by calling with the class name. ClassName. VariableName.