What is a variable?
A variable is a piece of memory which stores a data value. Thus, a variable has a data type. Primarily there are eight primitive data types in java. We will learn about these in a later post.
Variables are typically used to store information which our Java program needs to do its job. This can be any kind of information ranging from texts, codes (e.g. country codes, currency codes etc.) to numbers, temporary results of multi-step calculations etc.
You can declare a variable as below -
Types of variables
There are three types of variables in Java. We will discuss them one by one.
1. Local variables -
- They can be declared in a method, constructor, or block.
- When a method is entered, an area is pushed onto the call stack which contains slots for each local variable and parameter.
- When the method is called, the parameter slots are initialized to the parameter values.
- When the method exits, this area is popped off the stack and the memory becomes available for the next called method.
- Parameters are essentially local variables which are initialized from the actual parameters.
- Local variables are not visible outside the method.
For example, see below code snippet.
2. Instance variables -
- These are declared in a class, but outside a method.
- When an object is allocated in the heap, there is a slot in it for each instance variable value.
- Therefore an instance variable is created when an object is created and destroyed when the object is destroyed.
- Visible in all methods and constructors of the defining class should generally be declared private but may be given greater visibility (public/protected/default).
For example, see below code snippet.
3. Static/Class variables
- These are declared with the static keyword in a class, but outside a method.
- There is only one copy per class, regardless of how many objects are created from it.
- They are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.
For example, see below code snippet.
Here, id is a static or class variable which can be accessed using the class name.
A sample Java program
Below is a sample java code that illustrates the usage of all three variable types
Conclusion
In this post, we have gone through the different types of variables in Java. You can find the code of these examples on my GitHub repository. Feel free to fork or open issues, if any.
Happy Coding 😊.
This is what commonly happens to the newbies in the business industry who do not know how to effectively market their product or service or service.Best Sites like FMovies
ReplyDeletebut you can still afford some pretty good cleaning coverage with a service that provides you a housekeeper on a scheduled plan.Fraud Triangle
ReplyDelete