What is Variable
Variable is a name of the memory address(part of the memory) and it is used to store data of various data types. Each Variable must have a unique name to identify the memory address.
Type of Java Variables
there are mainly four types of variables but here you will learn only three types:
- Instance
- Local
- Static(class Variable)
1. Instance Variable
A variable that is declared outside the method but inside the class is called instance variable.
2. Local Variable
A variable that is declared inside the method is called local variable.
3. Static Variable
A variable which is declared as static is called a static variable and it is also known as the class variable.
Declaration of Java Variables
Here you will learn how to declare java variables and assign the value. Syntax:
type variable_name=value;
java variables Example
Here we are taking two variables num
and number
where num
is int type and number
is float type. Example:
int num =5;
float number=10.0;
Let’s see this example where we are using all the java variables type to demonstrate how it works. Example:
class A{
int speed = 45; //instance variable
static int rollno = 888; //static variable
void test()
{
float time = 10.00; //local variable
}
}
Here, speed
is an instance variable of int type and it is containing value is 45 and Another variable isroll_no
with value 888.
Java Data Types
A data type defines which type of data a variable can store and it has a special name such as int, boolean, float, etc. Java data type has two types: primitive or non-primitive
Primitive Data Types
There are 8 types of the primitive data type in Java:
- boolean
- byte
- short
- int
- long
- double
- float
- char
Data Type | Default Size | Default Value |
---|---|---|
boolean | 1 bit | false |
byte | 1 byte | 0 |
short | 2 bytes | 0 |
int | 4 bytes | 0 |
long | 8 bytes | 0L |
double | 8 bytes | 0.0d |
float | 4 bytes | 0.0f |
char | 2 bytes | ‘\u0000’ |