Variables and Data Types in Java

During programming, you might need an entity to store some value into it for this you can use variables. Each variable has a capacity that is determined by the data type assigned to it during declaration.

Variables in Java

The name assigned to a memory location is known as a variable. Java provides two types of variables-

  • Primitive Variables- It is also known as object references. It holds the value for a primitive data type.
  • Reference Variables- Reference variables holds the reference to an object stored elsewhere in memory.

The name we choose for a variable, methods, classes, interfaces, and packages is called an identifier.

Rules for naming variables

  • A variable name must start with a letter, underscore sign or currency sign.
  • From second character onwards, you can use digits, letters, underscore, and currency sign.
  • You cannot use keywords as a variable name.
  • Variables names are case sensitive.
  • Examples of valid identifiers are- $price, happy2help, _123, etc. Examples of invalid identifiers are- int, 2morrow, [email protected], etc.

Data types in Java

The data type determines the maximum value a variable can store. There are two type of data types in Java-

  • Primitive data type
  • Non-primitive data type

A type of value a variable can store is also determined by the data type.

Data Types in Java

Following table displays the size, range, and default value of primitive data types.

Data Type Size Range Default Value
boolean 1 bit true or false false
byte 1 byte -128 to 127 0
short 2 byte -32768 to 32767 0
char 2 byte 0 to 65535 '\u0000'
int 4 byte -231 to 231 - 1 0
long 8byte -263 to 263 - 1 0L
float 4 byte -231 to 231 - 1 0.0f
double 8 byte -263 to 263 - 1 0.0d

How to declare variable in Java

datatype variable_name;

Example

int numberofballs;

Without initialization, a variable holds default value which is listed above in the table. Also, you can initialize variables at the time of declaration.

int a = 10; //We are doing initialization at the point of declaration.
int b; //We are only declaring it.
b = 12; //Later we initialize variable b with 12.