A variable provides a named storage location that programs can manipulate. Each Java variable has a specific declaration type, determining the size and memory layout, the range of values that can be stored in that memory, and the operators to manipulate the variables.
All variables must be declared before they are used. Below is the basic structure of how to declare variables in Java:
Declare three integers, namely a, b, and c, using the syntax int a, b, c;
Illustration of initialization: int a = 10, b = 10;
Initialize a byte type variable B with the value 22: byte B = 22;
Declare and assign the value of PI to a double variable: double pi = 3.14159;
Explore the realms of variables: Local Variables, Class/Static Variables, and Instance Variables.
Local Variables
- Local variables are declared within methods, constructors, or blocks.
- Example:
In this example, age serves as a local variable. It is defined within the pupAge() method and is confined solely to this method:
The output of the above example is:
Puppy age is: 7
Example
In the following example, the variable age is used without initialization, leading to a compilation error:
The above example results in a compilation error, as shown below:
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error
Instance Variables
- Instance variables are declared within a class, outside of any method, constructor, or block.
Example
Here is an example illustrating how to declare instance variables in Java:
The above example will yield the following output:
name : Ransika
salary : 1000.0
Class / Static Variables
- Class variables, also known as static variables, are declared with the static keyword within a class, outside of any method, constructor, or block.
- Example:
Here is an example showcasing class variables:
The above example will yield the following output:
Development average salary:1000
Note:
When accessed from outside the class, constants are accessed as: Employee.DEPARTMENT.
Above are the insights into Java - the way of declaring variables in Java that Mytour presents to you. To delve deeper into this language, explore further through the tutorial on Java basics and stay tuned for more related articles from Mytour. Wishing you all success!
