A java variable is a reserved space of computer memory where a data value can be stored. You can assign a specific name to each of these memory locations however should follow the naming conventions.
Usually, a java program begins with the variable declaration since variables store the information that is required by your java program to perform its task. The information or data can be anything like simple texts or codes or numbers or even simple predefined calculations. Hence the variables that store data have specific data types which you will learn in detail in the next tutorial -Data types in Java.
public class Student {
public static void main(String[] args) {
String name;
int age;
}
}
In the above code, the name
is a variable of string data type and age
is another variable of integer data type.
Though 'Java' has provided the freedom of using variable names according to your wish and convenience, there are certain rules you must abide by.
Following the below table gives you the idea of valid and invalid variable names.
VALID VARIABLES NAMES | INVALID VARIABLES NAMES |
---|---|
age, _age, $age | 17age |
num, NUM | int, float, for, while |
stud1, stud_2 | Stud#, [email protected], Stud 1 |
Apart from these, Java has few naming conventions that are not necessary to follow but are practiced by many java developers to keep the proficiency of the java code. Following these conventions result in code readability. So the few naming conventions are listed below:
age
, name
, etc.studName
,studAge
,studFatherName
, etc.EXCHANGE_RATE
.Like in other programming languages, in java also all the variables which are going to be used in the program must be declared first. It is because of the two reasons
Variable declaration syntax involves two important parts as shown below, one is the data type and the other is the variable name. Variable declarations should always end with a semicolon unless the compiler will raise a termination error. Also, java provides the freedom to declare multiple variables in a single line if they possess the same datatype.
Syntax :
datatype variable_name;
For instance,
int num1;
int num 2;
float f1,f2;
Here, int
means the integer numbers, float
means a fractional number. int
and float
are data types and num1
, num2
, f1
, f2
are identifiers(variable names). A variable once declared with a specific data type will only take values of that particular data type. Here num
can take only integral values, if we try to store any other values like character to num then it will raise an error.
After the declaration is done, you are free to use the allocated space (i.e. variable) as per your requirement. This declared variable initially contains garbage values which are the undefined values. If you wish to assign some values initially you can do that with the help of the assignment operator ‘=
’. Variable initialization can be performed at the time of declaration itself or you can assign the value later.
Syntax:
datatype variable_name = value;
Some examples of variable initialization are illustrated below:
int num1 = 4;
float f1 ;
f1 = 2.5;
A variable always allocates the latest value in its space unless it is declared with the keyword final. See below example,
public class Student {
public static void main(String[] args) {
String name = "TOM";
int age = 17;
age = 20;
System.out.println("Name:" + name);
System.out.println("Age:" + age);
}
}
Output:
Name:TOM Age:20
In the above example, initially, the variable age
stores the value 17
but as it goes it encounters that the age
is assigned with a new value 20
. So the new value 20
overwrites the previous value 17
since the variable is not declared with the keyword final
. Hence it displayed age as 20
.
If you declare the variable as final
and attempt to assign it with another value, the result will be an error.
Now to display the variables in java we can use the println()
method. Let’s understand this with the help of an example:
public class Sum {
public static void main(String[] args) {
int num1 = 4;
int num2 = 5;
System.out.println("First number is : " + num1);
System.out.println("Second number is : " + num2);
int sum = num1 + num2;
System.out.println("Sum is " + sum);
}
}
Here variables num1
and num2
store the integer value 4 and 5 respectively. The variable sum
contains the added value of num1
and num2
. Using the println()
method, the values stored in the variables are displayed. To club the text with variables we can make use of the +
character.
Output:
First number is : 4 Second number is : 5 Sum is 9
Java describes 4 types of variables. They are listed below:
A local variable is a variable that is defined inside a method or constructor or a block of code. The scope of the variable is limited to that method or block of code. Hence we can say this type of variable has local scope only which means the variable is created upon entering the code block or being called by the method and destroyed when it exits that code block or returning the method.
void method()
{
int num = 5; // Local Variable
}
Here, variable num
is bound to the function method()
.
Instance variables are variables that are defined inside a class but outside a method or constructor or code block and are not being prefixed with the keyword static
. That means instance variables are non-static field variables.
An instance variable belongs to an object which in turn is an instance of a class thus we can say in other words that “An instance variable is an instance of the class”. An instance variable gets created whenever an object of a class is created with the use of keyword new
. That means instance variables are unique to their objects.
Class Employee{
String employee_Name;
int employee_Id;
In the above example, two instances (emp 1 and emp2) of class Employee got created.
A variable is said to be static if it is prefixed with the keyword static. Static variables in java are defined inside a class but outside a method or code block. Static variables are also called class variables as they belong to the class and not the objects(instance). Hence static variables are common to all instances of the class irrespective of the number of instantiations. In other words, the variables declared as static are shared among all the objects of the class. The below code snippet will illustrate the working of static variables.
Class Employee{
String employee_Name;
int employee_Id;
static String company_Name= “ABC”; //Static
Parameters are variables associated with methods. When a method is called, parameters are used to pass the information to the method. The scope of the parameter lies inside the method that declares the parameter.
public class ParamEx {
static void MethodDisp(String fname) {
System.out.println("Hai " + fname + " Welcome to LearneTutorials!!!");
}
public static void main(String[] args) {
MethodDisp("Tom");
MethodDisp("Jerry");
}
}
This example, ParamEx
is a class with a method named MethodDisp()
. The purpose of this method is to display the message “ Hai (name) Welcome to Learnetutorials!!!”. Here the name is passed as a string parameter fname
to the MethodDisp() on the method call.
Don’t bother yourself now about parameters. Definitely, you will learn in future tutorials. As of now just keep in mind variables can show up in the form of parameters also.