Variables in java

 In java, a variable is a name which acts just like a container which stores the values in it. Variables are declared along with data types such as int, float, double, char ..etc which tells the size of the variable and we can perform several different operations by using variables in java.


java variables
Variables in java



A variable is basically a name given to a memory location where the different values are stored. Variable name specifies that its values can vary or change.

A Few Examples of variables in java are:-

int var = 20;
Here var is the name of the variable which contains the value 20 in it and the var variable is of integer type.

float a = 5.5f;
Here a is the variable of float data type which contains the value 5.5.

Types of variables in java:-

  • Local variable :- These are the type of variables which is local to the method in which it is created and the local variable is not valid outside of the method in which it is created.
  • Instance variable :- These are the type of variables which is declared outside the method which is valid both inside and outside of the method.
  • Static variable :- These are the variables which is common to class and it is declared as static by using "static" keyword.
Example :-

public class example {

    static int a = 10; // static variable

    public static void m() {
         int b = 20; // local variable
    }
 
    public static void main(String args[]) {
        int c = 30; // instance variable
    }

}


Some of the rules of naming a variable in java :-

  • Variables names should only contain only letters (Uppercase and Lowercase)and numbers, ($) currency character and a special character underscore(_).
  • The first letter of the variable name should start with a letter or an underscore (you cannot start with a number) or dollar sign.
  • variables cannot contain any special characters other then numbers, letters, currency character and underscore.
  • Variables in java programming iscase sensitive i.e Uppercase and lowercase characters are treated  differently.
  • Java keywords cannot be used as variable names.

Few Examples of valid variables:-

int  _var12;
char $character;
float n1_num;

variables in java
variables in java


Few Examples of invalid variables:-

int 1var1;
    -This is invalid because the first character here is a number.
char new;
    -This is invalid because new is the reserved keyword in java.
float _n1#
    -Again this would generate an error as we cannot use ampersand.

Assigning values to a variable :-

int number = 99;
In the above statement we are storing the value 99 in to the variable name number which is of integer type.

float num = 99.99f;
In the above statement we are storing the value 99.99 in to the variable name num which is of floating value type.

Comments

Popular posts from this blog

Data types in java | java tutorial for beginners

BASIC STRUCTURE OF A JAVA PROGRAM