Java variables are containers that contain different values. A variable has three basic attributes by which it is recognized. A variable has a name, data type and a memory location. Variables are used to store memory locations with a name. The initial value of a variable can change while the execution of program.
Create a Java Variable
There are two steps of creating a variable
- Variable declaration
- Variable initialization
Variable declaration
In java variable declaration, we create a variable by defining its type and its name. A variable must be declared before it is used in the program. The syntax for declaring a variable is:
Here data_type is the data type selected for the variable and var_name is the name of the variable. The variable data type can be any of the following data types:
- String: String variables store text for example, “Hello World”. These are written in double quotes.
- int: int variables store numbers without decimal for example, whole numbers like 3, -4, etc.
- float: float variables store decimal values and floating point numbers like 3.6, -3.5 etc.
- char: char variables store single characters ‘a’, ‘2’, etc. These are written in single quotes.
- boolean: boolean variables store either true or false values.
Variable Initialization
In java variable initialization, we assign a value to the variable using the assignment operator (=). The syntax for initializing a variable is:
Programmer can also declare a variable first and assign value to it later as shown below:
Here, var_val is the value assigned to the variable. For example, the below code creates (declares and initializes) an int type variable:
int var = 9;
Where int is the data type of variable var having value 9. Similarly, a string variable will be created in the following way:
string var = "Hello World!";
Here, string is the data type of java variable having value “Hello World!”. The best practice to declare a variable is by keeping first letter of the variable name in lower case. If the variable name consists of more than one words then use camel case. For example, “num” for one word variable name and “myNum” for two words variable name is the correct syntax.
Display a Java Variable
After creating a java variable, user can use it for further manipulations or display it. The method println() is used to print a variable.
Example 1
For example, the code below creates a string type variable named var and prints that variable.
public class MyProgram { public static void main(String[] args) { String var = "Hello World!"; System.out.println(var); } }
The output of the above code after compilation on console is:
Example 2
Here is another example in which the code assigns a new value to the int type variable var.
public class MyProgram { public static void main(String[] args) { int var = 20; var = 40; // variable var now contains value 40. System.out.println(var); } }
The output of the above code after compilation on console is:
Final Variable
If as a programmer, you do not want to change the value of your java variable, you can create a final variable use final keyword. Its value once assigned cannot be changed or altered later in the program.
Example 3
For example, The below code will give an error on the console:
public class MyProgram { public static void main(String[] args) { final int var = 20; var = 40; // will raise an error on console System.out.println(var); } }
The error displayed on console will be something like this:
Types of Java Variables
In Java, there are three types of Java variables as shown below:
- Local variables
- Instance variables
- Class/Static variables
Local Variables
A local variable is a variable that is declared inside a method or a block or a constructor and the rest of the code has no access to it. This variable can only be called inside the method, constructor or block, it is declared in. The outside code does not use it.
Local variable is called when its method or constructor is called and it is destroyed after the compiler exits the block of code. As its name suggests its existence is only within its block. So, there is no need to assign access specifiers for local variables.
It is compulsory to initialize a local variable. These variables are stored in the stack. It cannot be defined with static keyword.
Example 4
For example, in the below code, there is a local variable. the scope of this variable is only within the method.
public class MyProgram { public void calTax() { int tax = 0; tax = tax + 7; System.out.println("The tax is : " + tax + "%"); } public static void main(String args[]) { MyProgram prog = new MyProgram(); prog.calTax(); } }
The output of the above code after compilation on the console is:
In this case if the user does not initialize the tax variable, compiler will generate an error.
Instance Variables
Instance variables are the variables that are declared outside a method or a constructor but inside the class. When the object of that is created, compiler stores an instance variable for each object in the heap. The keyword new is used to create an instance variable.
Instance variable is created when a class’s object is created and it is destroyed when the object is destroyed. As its name suggests, instance variable is instance specific. Each instance can have its own instance variable.
Instance variable cannot be defined with static keyword as it is non static. They can have access specifiers. If no access specifier is defined for instance variable then it will the default access specifier.
Unlike local variables, it is not mandatory to initialize instance variables. By default these variables will have 0 value. If the variable type is Boolean then its default value will be false. Programmer can assign values to instance variables later.
Programmer can access the instance variable inside the class by calling its name. However outside the class, dot operator (.) is used to access instance variable of specific object. For example, object.instanceVariable.
Example 5
For example, the code below demonstrates the concept of instance java variables.
import java.io.*; public class Product { // Public Instance variable declaration public String name; // Private Instance variable declaration private double price; public Product (String itemName) { name = itemName; } public void setPrice(double itemPrice) { price = itemPrice; } // This method prints the details of the product. public void printProd() { System.out.println("Item name : " + name ); System.out.println("Price :" + price + "$"); } public static void main(String args[]) { Product prodOne = new Product("Soap"); prodOne.setPrice(100.0); prodOne.printProd(); } }
The output of above code on the console after compilation is:
Class/Static Variables
Static variable is the java variable that is defined with static keyword. These are declared outside a method or constructor but inside the class. It cannot be a local variable. It is shared among all instances of class. As its name suggests, class/static variables are class specific.
Class variables are created with the execution of the program and are destroyed when the program ends. These variables are stored in the static memory.
It is not necessary to initialize static variables. By default, their value is set to 0. If static variable is of Boolean type then its default value is false.
Programmer can access static/class variable by using dot operator (.) with class name and variable name. For example, ClassName.variableName.
Example 6
For example, the code below demonstrates the concept of static variables.
import java.io.*; public class Product { // price variable is a private static variable private static double price; // item is a constant public static final String Item = "Soap"; public static void main(String args[]) { price = 100.0; System.out.println(Item + " average price:" + price + "$"); } }
The output of above code on the console after compilation is:
Comments are closed.