Variables and datatypes
Variable:
A variable is a named block of memory which is used to store the data,
It serves as a container that holds a value that can be changed during the execution of a
program.
Examples:
age = 21; a 21
5.2
height = 5.2; b
One variable can able to store one data at a time, further if we try to store another
value in the same variable the value will get reinitialized and old value will not be
available .
Note:
if you directly use the above example in the program the compiler will give the compile time
error because we have to also specify the datatype of the variable.
Datatypes:
Data Types represent the type of data that can be stored in a variable.
Data Types are classified into 2 types. They are
1. Primitive data types.
2. Non-Primitive data types.
1)Primitive datatypes
● Primitive data types are keywords.
● The memory capacity of primitive datatypes is predefined.
There are total 8 primitive data types are available in java.
pg. 1
Data types with memory size and default values:
Sl. Data Memory Range Default Value
No. type size Value Type
1 byte 1 byte -128 to 127 0 20
2 shot 2 bytes -32,768 to 32,767 0 36
3 int 4 bytes -2,147,483,648 to 0 66
2,147,483,647
4 long 8 bytes - 0 55l
9,223,372,306,854,775,808
to
9,223,372,306,854,775,807
5 float 4 bytes Up to 7 decimal digit 0.0 44.12f
6 double 8 bytes Up to 16 decimal digit 0.0 65.12
7 char 2 bytes Single character / ASCII \u0000 ‘A’
value, 0 - 255
8 boolean 1 bit true or false value false true
2)Non-primitive datatypes
● Non-primitive data types are called as user defined datatypes these are not
predefined .
Example
Class, Interface, String
Note: String is the only non-primitive predefined datatype.
● The memory capacity of non-primitive datatypes is not predefined.
pg. 2
Now lets see how to write a variable along with datatype
1)variable declaration
Syntax:
datatype variableName ;
example
1) int age;
2) double height;
2)Variable initialization:
Syntax:
variableName = value;
example
1) int age = 21 ;
2) double height = 5.2;
3)variable declaration and initialization
Syntax:
datatype variableName = value;
Example memory diagram
21
1) int age = 21; age
2) double height =5.2; 5.2
height
3) char gender = ‘M’;
‘M’
gender
4) String name = “Smith”; name “Smith”
pg. 3
Example program:
class Student
{
public static void main(String[] args)
{
String name = "Smith";
int age = 22;
char section = 'a';
String dob = "01/01/2001";
char gender ='M';
double height = 5.3;
[Link](name);
[Link](age);
[Link](section);
[Link](dob);
[Link](gender);
[Link](height);
Output:
Smith
22
a
01/01/2001
M
5.3
pg. 4