Table of contents
1.
Introduction
2.
Variables in Java
2.1.
Declaration
2.2.
Initialisation
3.
Types of variables in Java
3.1.
Local variables
3.2.
Static variables
3.3.
Instance Variables
4.
Frequently Asked Questions:
5.
Key Takeaways
Last Updated: Mar 27, 2024

Introduction to Variables

Author Yashesvinee V
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Programs are used to perform specific tasks, which may include storing, manipulating or printing data. The involvement of data in a program introduces the need for variables. A variable is a container that temporarily saves a data value during the execution of a program. They label and store data in the memory for easy access. The amount of space allocated to a variable in the memory depends on the type of value it holds.

Recommended Topic-  Iteration Statements in Java, Duck Number in Java

Variables in Java

Variables are also called identifiers in Java. Every programming language has its set of rules and conventions for naming a variable, and Java is no different. The conventions for naming Java variables are as follows:

  • A variable name can contain alphanumeric characters, the underscore and dollar characters. 
     
  • A variable name must always start with a letter as ‘_’ and ‘$’ are not conventionally used.
     
  • Whitespaces are not permitted.
     
  • Keywords can not be used as variable names.
     
  • Variable names are case-sensitive.

Declaration

Declaration of a variable is the process of creating and introducing the variable into your program. It lets the compiler know about the identifier’s name and the type of data it will hold. Once declared, a variable can not change its type throughout the program.

Syntax:

data_type variable_name;

 

Built_in data types like int, float, char, double, String, etc., can be used to declare a variable.

Initialisation

The initialisation of a variable involves assigning a value to the variable. A variable can be assigned different values throughout the program, but the type of value is restricted to the declared data type. Initialisation can be done separately or along with a variable’s declaration.

Syntax:

data_type variable_name = value;

 

The following example shows the initialisation and declaration of variables in Java.

int a;
a = 10;
int b = 1;
b = 30;

 

Must Read Static Blocks In Java and Hashcode Method in Java.

Types of variables in Java

There are three types of variables that can be used in Java. Let us go through each of them in detail.

Local variables

The variables declared in methods or constructors used only inside that code block are known as local variables. These variables can not be accessed outside their declared method or block. A block refers to a set of code that is enclosed within curly brackets { }. Local variables are used only when the program is running and discarded after exiting its block. Here is an example to show the scope of local variables in a program.

class A
{
   public static void main(String[] args)
   {
      int a = 10;
      if (a > 5)
      {
         int b = 10;
         a = a + b;
      }
      System.out.println(a,b);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

error: cannot find symbol
      System.out.println(a,b);
                           ^
  symbol:   variable b
  location: class A

 

The variable ‘a’ is local to the main method, and variable b is local to the if block.  We get an error since the print statement attempts to access the value to b from outside the if block.

Static variables

Static, a non-access modifier in Java, is attached as a prefix to variables or methods to indicate that it belongs to the entire class and not just an object. In other words, static members of a program can be accessed without creating an object. All objects of a class share a single copy of the static variable. Hence, they are also known to be global variables. However, their scope is limited to the declared class and not outside. Static members are allocated their memory only once when the entire class is loaded for execution.

public class Main
{
   static int a = 10;
   public static void main(String[] args)
   {
      int b = 10;
      System.out.prinln(a)
      sum(b);
   }
   public static void sum(int num)
   {
     System.out.println(a+num);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

10
20

 

Variable ‘a’ is a static variable and can be accessed in the main and sum methods. Since ‘b’ is a local variable, it is passed to the sum function as a parameter.

Instance Variables

Classes and methods are essential parts of a Java program. Instance variables are declared in a class outside any method, constructor, or block. Unlike local variables, instance variables directly form a part of the class and have default values. Access modifiers are used to declare instance variables. Instance variables can form a part of several subroutines, i.e. even if the value of an instance variable is situated in one subroutine, it can be used while executing another subroutine. However, they can be accessed only using objects.

In the given example, â€˜a’ is an instance variable visible to any child class. It is accessed using the ‘obj’ object.

public class A
{
   public int a;
   public A (int b)
   {
      a = b;
   }
   public void display() 
   {
      System.out.println(a);
   }
   public static void main(String args[]) 
   {
      A obj = new A(10);
      obj.display();
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

10

 

Must Read Conditional Statements in Java and Swap Function in Java

Frequently Asked Questions:

Q: What are the differences between static and instance variables?

  • All objects of a class have a single copy of static variables but a different copy of instance variables.
  • Changes made to a static variable is reflected in all objects, whereas the changes made to an instance variable in an object has no effect on the other objects.
  • Static variables can be accessed using the class name, and instance variables can be accessed through object references.
     

Q: What are access modifiers in Java?
Access modifiers are used to set the accessibility and scope of classes, interfaces, variables, methods, constructors and data members in a Java program. There are four types of access modifiers in Java - Public, Private, Protected and Default.

Key Takeaways

Variables carry the most important part of any program: the data. Without variables, it is impossible to perform even basic arithmetic operations. This blog covers the basics of variables in Java and how to use them in a program. It also explains the different kinds of variables in Java examples to help understand them better.

Related Links:

Addition of two numbers in java

Static and Instance Methods in Java

What is static in Java?

Classes and Objects in Java

Check out the official Coding Ninjas Blog site and visit our Library for more.

Live masterclass