This tutorial covers another fundamental concept of Java, i.e., variables. It will help you learn how to define and use variables in Java programs.
The variables are the basic building blocks of every programming language. They are essential to implement business logic in the code.
Learn to Use Variables in Java
The tutorial has the following sections to help you learn quickly.
What does a variable mean?
Variables, as the name suggests, can hold a particular value and can also accept modifications time in time out.
In terms of a programming language, a variable is a name pointing to a memory location.
In Java, one should define all the variables before using them.
Why should you use variables in Java?
Consider a scenario where you wish to do arithmetic calculations using a Java program. Assume, you did some initial calculations and came up with a numerical value.
You feed the value (say 1) into your Java program and use that value at about 100 lines in your code.
Now, you decide to re-check your calculations and realize that a blunder occurred at some point as the actual value was 0.5, not 1.
In this case, you can either go on changing the value at all 100 places from 1 to 0.5 or use a variable instead.
How to declare variables in Java?
To use a variable, you need to declare it first. And it is also quite straightforward:
int myVar;
There are a few thumb rules to note while you create a variable in Java.
- First, never start a variable name with “_” or “$” symbols.
- Ensure that the variable name makes sense in the context of the value you are storing in it.
- Also, having multiple variables with the same name doesn’t work if they are in the same scope.
For declaring a variable, first, specify the keyword, i.e., the data type, and then type its name.
For example –
int value; // value is name of the variable and int is the keyword
The above is an un-initialized variable. You can also give a default value. See below.
int value = 0; // variable initialized with zero boolean isOdd = true; // boolean variable set to true whereas its default value is false char letter = 'J'; // variable to store characters
Until this point in time, three variables “value,” “isOdd,” and “letter” have entered in program’s memory.
The variable “value” points to a memory location which the user can change to assign any value. Similarly, other variables also have memory allocated and can store specific values.
Must Read – Data types in Java
Types of variables
There are three major types of variables in Java:
Local variable
Any variable that appears inside a constructor, a method, or a block is a local one.
These types of variables incarnate whenever a constructor or a method or a block gets invoked and destroyed subsequently upon losing their scope.
The extent of these variables exists just inside the block in which they get used.
Below is a demo program using the local variables.
public class MyProgram { public static void main(String[] args) { String myMessage; // local variable, has scope in the main function only. myMessage = "I'm learning Java."; System.out.println(myMessage); } }
Executing the above code gives the following result:
I'm learning Java.
Instance variable
An instance variable is one that has its definition inside the class but outside any of its function, constructor, or block.
Please note that it is non-static and each object of the class will have its respective copy of the instance variable.
An instance variable gets allocated along with the class object and remains until the object persists.
In contrast to the local ones, you may apply appropriate access specifiers for these variables. If you don’t indicate any, then the default specifier will be used.
Below is a demo program using the instance variable.
public class Book { public String name; // instance variable accessible to any child class. private String author; // instance variable accessible only in Book class. // Constructor method public Book(String value) { name = value; } // Class method to set the private instance variable public void setAuthor(String value) { author = value; } // Class method to get the private instance variable public void getAuthor() { System.out.println("Written by: " + author); } public static void main(String[] args) { Book first = new Book("Java"); first.setAuthor("James Gosling"); Book second = new Book("Python"); second.setAuthor("Guido van Rossum"); System.out.println("Book name: " + first.name); first.getAuthor(); System.out.println("\n"); System.out.println("Book name: " + second.name); second.getAuthor(); } }
Executing the above code gives the following result:
Book name: Java Written by: James Gosling Book name: Python Written by: Guido van Rossum
Static variable
Static variables are otherwise called Class variables.
Similar to instance variables, they also have a definition at the class level. But they do differ in a way as we need to prefix the “Static” keyword to declare them. And each class object shares a single copy of them.
The static variables go live at the beginning of program execution and terminate when the application ends. To get to static variables, we don’t need to make any object of that class.
Check out the below program to get more clarity on the functionality of static variables.
// Java program to demonstrate the // use of a static variable public class StaticDemo { static int counter = 0; // Constructor method incrementing the counter // for every new object getting created public StaticDemo() { counter++; } public static void main(String[] args) { StaticDemo static1 = new StaticDemo(); StaticDemo static2 = new StaticDemo(); StaticDemo static3 = new StaticDemo(); System.out.println("Total objects created: " + counter); } }
Executing the above code gives the following result:
Total objects created: 3