Java Variables and Data Types with EXAMPLE

What is a Variable in Java?

Variable in Java is a data container that stores the data values during Java program execution. Every variable is assigned data type which designates the type and quantity of value it can hold. Variable is a memory location name of the data. The Java variables have mainly three types : Local, Instance and Static.

In order to use a variable in a program you to need to perform 2 steps

  1. Variable Declaration
  2. Variable Initialization

In this tutorial, you will learn-

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.
 

  1. Primitive Data Types :- which include integer, character, boolean, and float
  2. Non-primitive Data Types :- which include classes, arrays and interfaces.
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)
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

Points to Remember:

Java Variable Type Conversion & Type Casting

A variable of one type can receive the value of another type. Here there are 2 cases -

Case 1) Variable of smaller capacity is be assigned to another variable of bigger capacity.
  This process is Automatic, and non-explicit is known as Conversion

Case 2) Variable of larger capacity is be assigned to another variable of smaller capacity
 

YOU MIGHT LIKE: