Search

Tuesday, March 30, 2021

Variable in Java

 



Variable in Java


In Java programming language variables are basically the containers that are used to hold some values when your program executed. To define a variable in Java language, we must first define the data type for the variable and that data type will show what type of value variable will hold in memory.


When you define a variable in Java a memory space is allocated and the value will be placed in that location and to access that location we must provide a valid name. That name is actually called an identifier in Java programming language. The value of the variable can change during program execution

 

How to declare Java Variable


Syntax

        Datatype varableName=someValue;


For Example

        int a = 100;

        System.out.println(a);

       

        Output = 100

 

Different types of variables in Java language

 

1.   Local variable

2.   Instance variable

3.   Static variable

 

 

 

1.Local Variable


when you define a variable in some method body, it is known as local variable and this variable can only be used inside the body of that method.

Outside method body, that variable will not be visible.


Example


class localvariableExample

{

Void methodName()

{

Int varName=100;

}

}

 

2. Static variables


Static variables are those variables that can be shared with different instances of classes.  Java language will allocate memory to the static variables only one time when your program is loaded.  we must write static keyword with static variable to actually make it as static variable


Example


class staticVariableExample

{

static int varName=10;

}

 

3.Instance Variable


When you define a variable in class and not in the method that variable is known as instance variable. It is also known as class level variable.


Example


class instanceVariableExample

{

int varName=10;

}


Video Lecture


No comments:

Post a Comment