Java Variables and Data Types with EXAMPLE
What is a Variable?
A variable can be thought of as a container which holds value for you, during the life of a Java
program. Every variable is assigned a data type which designates the type and quantity of value
it can hold.
In order to use a variable in a program you to need to perform 2 steps
Variable Declaration
Variable Initialization
In this tutorial, you will learn-
Variable Declaration
Variable Initialization
Types of variables
Data Types in Java
Type Conversion & Type Casting
Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.
Examples of other Valid Declarations are
int a,b,c;
float pi;
double d;
char a;
Variable Initialization:
To initialize a variable, you must assign it a valid value.
Example of other Valid Initializations are
pi =3.14f;
do =20.22d;
a=’v’;
You can combine variable declaration and initialization.
Example :
int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;
Types of variables
In Java, there are three types of variables:
Local Variables
Instance Variables
Static Variables
1) Local Variables
Local Variables are a variable that are declared inside the body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword .They are defined Outside a method
declaration. They are Object specific and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the program execution. These variables
should be initialized first, before the initialization of any instance variables.
Example: Types of Variables in Java
class Guru99 {
int data = 99; //instance variable
static int a = 1; //static variable
void method() {
int b = 90; //local variable
Data Types in Java
Data types classify the different values to be stored in the variable. In java, there are two types
of data types:
Primitive Data Types
Non-primitive Data Types
Primitive Data Types
Primitive Data Types are predefined and available within the Java language. Primitive values do
not share state with other primitive values.
There are 8 primitive types: byte, short, int, long, char, float, double, and boolean Integer data
types
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
Floating Data Type
float (4 bytes)
double (8 bytes)
Textual Data Type
char (2 bytes)
Logical
boolean (1 byte) (true/false)
Java Data Types
Data Type Default Value Default size
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes
float 0.0f 4 bytes
double 0.0d 8 bytes
boolean false 1 bit
char '\u0000' 2 bytes