Variable in java

A variable refers to the memory location that holds values like: numbers, texts etc. in the computer memory. A variable is a name of location where the data is stored when a program executes.

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:


Datatype variableName [ = value][, variableName [= value] ...] ;
The variable Name is also called identifier. You can declare more than one variable of the specified type; use a comma-separated list.
Naming variables
Rules that must be followed when naming variables or errors will be generated and your program will not work:

  • No spaces in variable names
  • A variable name must begin with a letter and must be a sequence of letters or digits.
  • A letter is defined as 'A'–'Z', 'a'–'z', '_', or any Unicode character that denotes a letter in a language.
  • No special symbols in variable names such as !@#%^&*
  • Variable names can only contain letters, numbers, and the underscore ( _ ) symbol
  • Variable names cannot start with numbers, only letters or the underscore ( _ ) symbol (but variable names can contain numbers)
How to Declare & Initialization a variable in Java
Here are examples of variable declarations and initialization of various types.
int a, b, c; // Declares int data type. int p, q=10, r = 15; // Declares three more ints, as well as initializing . byte x = 22; // Declares as well as initializes x. double price = 9.79; // Declares an approximation of price. char y = 'y'; // The char variable y has the value 'y'.
There are three kinds of variables available in Java Language:
  1. Local variables
  2. Instance Variables (Non-static fields)
  3. Class Variables (Static fields)
Local variables:
The variables defined in a method or block of code is called local variables. These variables can be accessed within a method or block of code only. These variables don't take default values if not initialized. These values are required to be initialized before using them.
  • These variables are declared in methods, constructors, or blocks.
  • These variables can be accessed within a method or block of code only.
  • These variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
  • These variables don't take default values if not initialized.
  • These values are required to be initialized before using them.
  • Access modifiers cannot be used for local variables.
  • Local variables are visible only within the declared method, constructor or block.
  • Local variables are implemented at stack level internally.
Example:
Here salary is a local variable. This is defined inside countSalary() method and its scope is limited to this method only.

public class VariableDemo{ public void countSalary(){ int salary =20000; salary = salary + 1500; System.out.println("Now salary is : " + age); } public static void main(String args[]){ VariableDemo ob = new VariableDemo (); ob. countSalary (); } }

Output:

   Now salary is: 21500   
Instance Variables (Non-static fields):
  • Instance variables are declared inside the class, but outside of any method, constructor or any block.
  • When a space is allocated for an object in the heap a slot for each instance variable value is created.
  • In object oriented programming, objects store their individual states in the "non-static fields" that is declared without the static keyword.
  • Instance variables are created when an object is created with the use of the key word 'new' and destroyed when the object is destroyed.
  • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object.
  • Instance variables can be declared in class level before or after use.
  • Access modifiers can be given for instance variables.
  • The instance variables are visible for all methods, constructors and block in the class.
  • Instance variables take default values if not initialized.  
  • Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
  • Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) the should be called using the fully qualified name . ObjectReference.VariableName.

Example:

import java.io.*; class Student{ // name instance variable accessed for any subclass. public String name; // enrolmentNo variable is accessed in Student class only. private int enrolmentNo; // The name variable is assigned in the parameterised constructor. public Student (String stuName){ name = stuName; } // The enrolmentNo variable is assigned a value. public void setEnrolmentNo(int stuEnrolmentNo){ enrolmentNo = stuEnrolmentNo; } // This method show the Student Records details. public void showRecord(){ System.out.println("Name : " + name ); System.out.println("EnrolmentNo :" + enrolmentNo); } public static void main(String args[]){ Student stu = new Student("Sunil Kumar Singh"); stu.setEnrolmentNo(436); stu.showRecord(); } }

Output :

   Name : Sunil Kumar Singh   
   EnrolmentNo: 436   
Class Variables (Static fields):
  • A class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many instances of the class exist.
  • In Java class variables are declared with the keyword static, and may therefore be referred to as static member variables.
  • Always the same set of values is shared among different objects of the same class.
  • So these variables are like global variables which are same for all objects of the class.
  • A class variable is not an instance variable. It is a special type of class attributes (or class property, field, or data member).
  • Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.
  • Static variables are created when the class is first loaded and destroyed when the program stops.
  • A class variable visibility is similar to instance variables. However, most static variables are declared public since they must be available for all users of the class.
  • Default values are same as instance variables. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor. Additionally values can be also assigned in special static initialization blocks.
  • Static variables can be called with the name of class name.(dot) variable name .

  • ClassName.VariableName.

Example:

import java.io.*; class StudentClassDemo{ // age variable is default static int variable static int age=21; // enrolmentNo variable is a private static int variable private static int enrolmentNo; // programme is a constant string varaible public static final String programme = "MCA"; // Static block initilized static { System.out.println("Static block initilized."); age=age+1; } public static void main(String args[]){ enrolmentNo = 436; System.out.println(" Programme :"+programme+" Enrolment Number :"+enrolmentNo); System.out.println("Age is :"+age); } }

Output :

   Static block initilized
   MCA Enrolment Number : Sunil Kumar Singh   
   Age is: 436   
 



 

Latest Tutorial


Most Visited Tutorial