Variables in Java

Objectives

Declaring a Variable

Assigning a Value to Variable

Initializing a Variable

Primitive or Reference

Primitive Types

Type Purpose Size (bytes) Examples
boolean Store true or false 1 boolean b = true;
char Store a single unicode character 2 char c = 'A';
byte Store a number within this range: [−27,  27) = [−128,  128) = [−128,  127] 1 byte b = 12;
short Store a number within this range: [−215,  215) = [−32,768,  32,768) = [−32,768,  32,767] 2 short s = -25000;
int Store a number within this range: [−231,  231) = [−2,147,483,648,  2,147,483,647] 4 int i = 4013;
long Store a number within this range: [−263,  263) = [−9,223,372,036,854,775,808,  9,223,372,036,854,775,807] 8 long n = 3;
float
A floating-point number is a number with digits after the decimal separator.
Store a floating-point number with approximately 7 decimal digits of precision within the following range: [−3.4028235×1038,  3.4028235×1038]
float can store exact integers within the following range without approximation: [−16,777,216,  16,777,216]
Integers that are more negative or more positive than the previous range are approximated in a float.
4 float f = 4.15f;
double
More precise than float. Store a floating-point number with approximately 15 decimal digits of precision within the following range: [−1.7976931348623157×10308,  1.7976931348623157×10308]
double can store exact integers within the following range without approximation: [−9,007,199,254,740,992,  9,007,199,254,740,992]
Integers that are more negative or more positive than the previous range are approximated in a double.
8 double d = 76.178032;

Automatic Promotion of Primitive Variables

Type Casting Primitive Variables