Java Variable

Hi! 👽

   In my childhood, I love to play marbles (kancha) and store them In a jar😄

java variable example

So same thing happens in java we have to play with value and store them in a jar 

Oh😅, sorry not jar we call it variable in java


variable:

we referred variable as a name of a memory location in our computers A variable is a container that holds the value while the Java program is executed. A variable is assigned with a data type

variable java

To indicate the storage area, each variable should be given a unique name (identifier). Learn more about Java identifiers.


How to declare variable:

how to declare variable

Here, codeelife is a variable of int data type and is assigned value 5.
Mean, codeelife variable can store integer values.

We can also declare a variable without assigning it

int codeelife;

The value of a variable can be changed in the program, hence the name ‘variable’. For example,

int codeelife = 5;
.. .. .. . .
codeelife = 6;

Note: variable must be declaring before it uses

  • Variables in Java are case-sensitive.
  • A variable’s name is a sequence of Unicode letters and digits. It can begin with a letter, $ or _.
  • variable names cannot use whitespace in Java.
Variable NameREMARK
_codeelifeValid but bad
$CodeelifeValid but bad
Codee lifeinvalid
Codee”lifeinvalid
Codeelife1valid
codeelifevalid
Example of add two-variable int type:
1.	class Simple{  
2.	public static void main(String[] args){  
3.	int a=10;  
4.	int b=10;  
5.	int c=a+b;  
6.	System.out.println(c);  
7.	}}  

Output:

20


Type of variable in java:

There are 4 type of variable in java

  • local variable
  • instance variable
  • static variable
types of variable

Local Variable: –

A variable declared inside the body of the method is called local variable.

We can only access local variable inside the method

We can’t access from outside of the method

Instance variable:

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance specific and is not shared among instances.

Static variable:

A variable that is declared as static is called a static variable. We can access the static variables from other classes in the same package.

Example of different type of variable:
1.	class A{  
2.	int data=50;//instance variable  
3.	static int m=100;//static variable  
4.	void method(){  
5.	int n=90;//local variable  
6.	}  
7.	}//end of class  



SHARE THIS PAGE





Important Link