This article covers the basics of Java variables, including variable declaration, scope, naming conventions and types of variable. It explains the types of variable in Java with the help of examples.
What is a variable?
In Java, a variable is a name of the memory location that holds a value of a particular data type. It is a fundamental concept in java programming that allows you to store and manipulate data during the execution of a program.
Variables in Java can hold various types of data, including integers, floating-point numbers, characters, and booleans. You can also use variables to hold more complex data types, such as arrays, objects, and strings.
A variable is a name which is associated with a value that can be changed. For example when I write int i=10;
here variable name is i which has the value 10, int is a data type that represents that this variable can hold integer values. We have covered the data types in this tutorial. In this tutorial, we will discuss about variables.
Java Variable Declaration: Syntax and Best Practices
In Java, you can declare a variable using the following syntax:
data_type variable_name = value;
Here value is optional because in java, you can declare the variable first and then later assign the value to it.
Here, data_type
represents the type of data that the variable will hold, such as int
, double
, String
, boolean
, etc. variable_name
is the name you want to give to the variable.
For example: In the following code, the num is a variable and int is a data type. You can read data types here but I would recommend you to finish reading this guide before proceeding to the next one.
int num;
Similarly we can assign the values to the variables while declaring them, like this:
char ch = 'A'; int number = 100;
or we can do it like this:
char ch; int number; ... ch = 'A'; number = 100;
Note:
By default, the value of the variable will be set to 0 for numeric types, false
for booleans, and null
for objects.
It is a good practice to initialize variables at the time of declaration to avoid unexpected behaviour or errors in the code.
In the following section, I am sharing the syntax of different types of variables. Although I have discussed the types of variables later in this same article, I thought it is a good idea to discuss the syntax of these variables here –
Syntax of local variables declaration:
Variables declared inside a method or block. For example:
int myAge; double mySalary; String myName;
Syntax of instance variables declaration:
These variables are declared inside the class but outside a method or a block. Examples are:
public int myAge; private double mySalary; String myName;
Syntax of class variables declaration:
These are also known as static variables. These variables are declared in the class but outside any method or block. Read more about static variables here.
public static int counter; private static double rateOfInterest;
Java Variable Naming Convention: Best Practices for Readable and Maintainable Code
- Variables naming cannot contain white spaces, for example:
int num ber = 100
; is invalid because the variable name has space in it. - Variables should not start with a digit or contain special characters like
@
,#
,$
,%
,^
,&
,*
,(
,)
,-
,+
,/
,,
|
,?
,:
or;
. - As per the java coding standards the variable name should begin with a lower case letter, for example
int number;
For lengthy variables names that has more than one words do it like this: int smallNumber; int bigNumber; (start the second word with capital letter). - Constants (variables whose values do not change during runtime) should be written in all capital letters with underscores separating words. For example:
MAX_VALUE
,PI
. - Variable names are case sensitive in Java. For example, the variables
myNum
andmynum
are two different variables. - Variables should not use reserved keywords or class names as their name. For example, you should not name a variable “int” or “String”.
Default Values for Java Variables
In Java, variables are automatically assigned default values if they are not explicitly initialized. The default value depends on the data type of the variable, as shown in the following table:
Data Type | Default Value |
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | ‘u0000’ |
boolean | false |
object | null |
For example, if you declare an integer variable without initializing it, it will be assigned a default value of 0:
int num; System.out.println(num); // prints 0
Similarly, if you declare a boolean variable without initializing it, it will be assigned a default value of false
:
boolean bool; System.out.println(bool); // prints false
Note that for object types, the default value is null
, which means that the variable does not reference any object. If you try to access an uninitialized object variable, you will get a NullPointerException
at runtime:
String str; System.out.println(str); // throws NullPointerException
It’s always a good practice to initialize your variables at the time of declaration to avoid unexpected behaviour or errors in the code.
Types of Variables in Java
There are three types of variables in Java.
- Static (or class) variable
- Global variable (Instance variable)
- Local variable
1. Static (or class) Variable
Static variables are also known as class variable because they are associated with the class and common for all the instances of class. To declare a static variable in Java, you use the static
keyword before the variable’s data type in the class definition, like this:
public class MyClass { static int myStaticVariable = 100; }
Static variables can be accessed using the class name, rather than the instance name, like this:
int num = MyClass.myStaticVariable;
For example, If I create three objects of a class and access this static variable, it would be same for all, the changes made to the variable using one of the object would reflect when you access it through other objects.
Example of static variable
public class StaticVarExample { public static String myClassVar="class or static variable"; public static void main(String args[]){ StaticVarExample obj = new StaticVarExample(); StaticVarExample obj2 = new StaticVarExample(); StaticVarExample obj3 = new StaticVarExample(); //All three will display "class or static variable" System.out.println(obj.myClassVar); System.out.println(obj2.myClassVar); System.out.println(obj3.myClassVar); //changing the value of static variable using obj2 obj2.myClassVar = "Changed Text"; //All three will display "Changed Text" System.out.println(obj.myClassVar); System.out.println(obj2.myClassVar); System.out.println(obj3.myClassVar); } }
Output:
class or static variable class or static variable class or static variable Changed Text Changed Text Changed Text
As you can see all three statements displayed the same output irrespective of the instance through which it is being accessed. That’s is why we can access the static variables without using the objects like this:
System.out.println(myClassVar);
Do note that only static variables can be accessed like this (without using object). This doesn’t apply for instance and local variables.
2. Global variable or Instance variable
A global variable is also known as instance variable. It is declared at the class level and is accessible to all methods and constructors within the class.
Each instance(objects) of class has its own copy of instance variable. Unlike static variable, instance variables have their own separate copy of instance variable.
In the following example, we have changed the instance variable myInstanceVar
value of the object obj2 and when we displayed the variable using all three objects, only the obj2 value got changed, others remain unchanged. This shows that they have their own copy of instance variable.
Example of Instance variable
public class InstanceVarExample { String myInstanceVar="instance variable"; public static void main(String args[]){ InstanceVarExample obj = new InstanceVarExample(); InstanceVarExample obj2 = new InstanceVarExample(); InstanceVarExample obj3 = new InstanceVarExample(); System.out.println(obj.myInstanceVar); System.out.println(obj2.myInstanceVar); System.out.println(obj3.myInstanceVar); obj2.myInstanceVar = "Changed Text"; System.out.println(obj.myInstanceVar); System.out.println(obj2.myInstanceVar); System.out.println(obj3.myInstanceVar); } }
Output:
instance variable instance variable instance variable instance variable Changed Text instance variable
3. Local Variable
In Java, a local variable is a variable that is declared inside a method, constructor, or block of code, and is only accessible within that block. Their scope is limited to the method which means that You can’t change their values and access them outside of the method.
Local variables are used to store temporary values that are needed to perform a specific task within a method or block. They have a limited scope and lifetime, and are destroyed once the method or block finishes executing.
Here’s an example of a local variable declared in a method:
public void myMethod() { int num = 100; System.out.println(num); }
In this above example, the variable num
is a local variable that is declared inside the myMethod()
method. It is assigned the value of 100 which gets printed to the console using println() method. Once the method finishes executing, the variable is destroyed and its value is no longer accessible.
Example of Local variable
public class VariableExample { // instance variable public String myVar="instance variable"; public void myMethod(){ // local variable String myVar = "Inside Method"; System.out.println(myVar); } public static void main(String args[]){ // Creating object VariableExample obj = new VariableExample(); /* We are calling the method, that changes the * value of myVar. We are displaying myVar again after * the method call, to demonstrate that the local * variable scope is limited to the method itself. */ System.out.println("Calling Method"); obj.myMethod(); System.out.println(obj.myVar); } }
Output:
Calling Method Inside Method instance variable
If I hadn’t declared the instance variable and only declared the local variable inside method then the statement System.out.println(obj.myVar); would have thrown compilation error. As you cannot change and access local variables outside the method.
Difference between Global variable and local variable in Java
In Java, a global variable is a variable that is declared at the class level and is accessible to all methods and constructors within the class. On the other hand, a local variable is a variable that is declared within a method or block and is only accessible within that method or block.
Here are some key differences between global and local variables:
- Scope: Global variables have a wider scope as they are accessible throughout the class. Local variables, on the other hand, have a narrower scope as they are only accessible within the method or block in which they are declared.
- Lifetime: Global variables have a longer lifetime as they are created when the object is instantiated and are destroyed when the object is destroyed. Local variables have a shorter lifetime as they are created when the method or block is executed and are destroyed when the method or block exits.
- Access: Global variables can be accessed from any method or constructor within the class, which means they can be modified by any method or constructor that has access to them. Local variables can only be accessed within the method or block in which they are declared.
- Initialization: Global variables are initialized to default values (e.g., 0 for numeric types, false for boolean, and null for objects) if no explicit initialization is provided. Local variables must be initialized explicitly before they can be used.
Let’s take an example to understand the differences:
public class JavaExample { private int myGlobalVariable = 100; //a method public void myMethod() { int myLocalVariable = 100; myGlobalVariable++; //global variable increment myLocalVariable++; //local variable increment System.out.print("Global variable: " + myGlobalVariable); System.out.println(" Local variable: " + myLocalVariable); } public static void main(String args[]){ JavaExample obj = new JavaExample(); obj.myMethod(); // Output: Global variable: 101 Local variable: 101 obj.myMethod(); // Output: Global variable: 102 Local variable: 101 obj.myMethod(); // Output: Global variable: 103 Local variable: 101 } }
In general, it is recommended to use local variables whenever possible, as they promote good coding practices and reduces the risk of errors caused by unintended modifications to global variables. Global variables should be used sparingly and only when they are truly necessary.
Check out these related java examples before proceeding to the next topic:
Leave a Reply