Java Variables

What is a Variable?, Explicit Declaration of Variable, Types of Variables in Java, Local; Variables. Instance Variables, and Static Variables.

Java Tutorial for Beginners

Java Variables

1. What is a Variable?

Variable is a named memory location to store the temporary data within a program.

We have variables in every computer programming language, the use of variables is the same for all programming languages but syntax varies from one language to another.

We have two types of memory in the Computer environment

a. Primary memory (RAM – Random-access memory)

b. Secondary memory (HDD, DVD, USB drive, etc…)

2. Declaration of Variables

Java supports Explicit declaration of Variables.

Syntax and Examples:

dataType variableName;

int a;
————-
dataType variablename=value;

int b=20;
—————
dataType variable1, Variable2, variable3;

int a, b, c;
—————–
dataType variable1=value; variable2=value; varible3=value;

int a=10; b=20; c=30;

3. Assign values to variables

a) Initialization

b) Reading

Ex:

int a=100; //Initialization

int a=10;
int b;
b=a; //Reading

4. Variable Naming Restrictions

a. Java variables are case sensitive.

b. Java variable name should start with a letter or $ or _

Example:

myvar(Correct)
MYVAR
$myvar
_myvar
myvar_1
————–
1myvar(Incorrect)
*myvar
—————-
c. Variable names should not match with Java keywords/Reserved words.

d. The variable must be unique in the scope of the declaration.

e. Variable names must not exceed 255 characters.

5. Types of Variables

There are three types of variables in Java

a. Local variable(Local variable is declared in methods or blocks.)

b. Instance variable(Instance variables are declared in a class but outside of a method or any block)

c. Class/Static variable – Variable that is declared as static, It cannot be local.

Java Program Example:

package abcdef;

public class VariablesExample {
static int a =100; //Static variable or Class variable
int b=200;//Instance variable or Non-static variable

public int salary(){
int mysalary =10000+2000+1500; //mysalary variable is a Local variable.
mysalary=mysalary + a;
return mysalary;
}

public static void main (String[]args){
int c =300;
System.out.println(a);//100
System.out.println(c); //300

VariablesExample obj= new VariablesExample();

System.out.println(obj.b); //200 (print Instance varaible)

System.out.println(obj.salary());

for (int i=1; i<=5; i++){ // i is a Local Variable
System.out.println(i);
System.out.println(a);
System.out.println(b);
}

}
}


Java Programming Language Syllabus

Java Step by Step Videos

Follow me on social media: