Variables and Types of Variables in Java

Introduction

The most basic implementation of any program is storing and manipulating data. Java supports different types of data, such as numbers, symbols, boolean, etc.

To store these types of values Java uses a variable, which is a name assigned to the memory location where the data will be stored. A variable can have different data types depending on the type of data it stores.

Java is strongly typed, so the type that is stored in each variable is checked at compile time. If a type mismatch is detected, a compilation error occurs.

Syntax:

datatype variableName; 

  • datatype: Any type supported by Java. 
  • variableName: A valid variable name.

Examples:

int studentId;

String studentName;

Here, two variables have been declared namely, studentId and studentName. The studentId is of type integer and studentName is of type String. Based on the datatype, memory is allocated to the variables. It is compulsory to declare a variable before using it in code.

Variable names must conform to some naming conventions, which are as follows,

  • The variable name cannot be a Java keyword, such as static, empty, public, int, etc.
  • Variable name can have letters and numbers in unicode, an underscore (_), and dollar sign ($).
  • A variable name must begin with a letter, dollar sign ($) or underscore (_).
  • Variable name is case-sensitive, so the number is not the same as the Number.
  • A single-word variable name must start in lower case, such as a student.
  • A variable name with multiple words must begin with the capital letter of each subsequent word, e.g., firstName.

The following table lists some acceptable and unacceptable variable names according to Java naming conventions,

ValidInvalid
studentNamestudent#name
_passwordInteger
$amount4thousand

Variables can be assigned values during declaration or after declaration as follows,

/ Declaring two variables of Integer type 
int a,b; 
// Initializing variables, a and b 
a=20; 
b=10; 
// Declaring one variable and initializing two variables in // the same statement 
int x = 4, y, z = 10; 
// Declaring and initializing a variable 
byte age = 20; 
// Declaring and initializing multiple variables 
// with the same value
int val1 = val2 = 10;

Types of variables

Java supports instances, static and local variables. Each variable is briefly explained as follows,

  • Instance variables can be accessed by using an instance of a class. There is a separate copy of the instance variable for each instance.
  • Static variables do not require an instance to access them because they are class-level variables. The static keyword is used to declare a static variable, and a shared copy of the variable is shared by all instances.
  • Local variables are declared inside blocks or methods and cannot be accessed outside of them.
  • A block begins with ‘{‘ and ends with ‘}’ curly braces symbol.

The following figure shows the use of instance and static variables,

Instance and Static Variables
Instance and Static Variables

Here the variable num is an instance variable and the counter is a static variable. The objects object1 and object2 have their own copies of the values for the variable num. But the variable count value is the same for both objects, because it is a static variable. Therefore, the objects have the same copy of the variable count.

In addition to variable types, Java also defines a scope for each variable. The scope is determined by where the variables are declared and when they are accessed. Broadly speaking, the scope of variables can be at the class level or at the method (local) level.

Class scope includes instance and static variables, while local variables are declared within a method or block. The lifetime of an instance variable is until the object exists, while a static variable is until the class exists.

The lifetime of method-level variables depends on the execution of methods. These variables are allocated to memory during method execution and are destroyed when the method is complete. Another set of variables are parameters passed to methods, which hold values passed to methods at runtime.

The following example shows the different uses of variables in a Java program,

public class Calculate {
  // variables with the class level scope 
  int a,
  b;
  static int count;
  public static void main(String args[]) {
    int x; // variable with method level scope 
    {
      int y = 10; // variable with block level scope 
    }
    //Below statement gives error 
    // as y is not accessible here 
    System.out.println("Value of y is " + y);
  }
}

In the println() method, the statement Value of y is is concatenated with the actual variable y by using the concatenation operator (+). If the value of y would be accessible, the output would be “Value of y is 10”.

Leave a Comment