Java Variables And Data Types
Data types in every programming language tell what type of values can be stored in a variable. Variables are placeholders that can hold data in a memory location. Two types of data types are available in Java
- Primitive data types
- Object(reference) data types
Primitive data types
There are 8 primitive data types in Java.
byte
- A
byte
is an 8-bit signed integer - Ranging from -128 to 127
- The default value is 0
- Example:
byte value = 5;
short
short
is a 16-bit signed integer- ranging from -32,768 to 32,767
- The default value is 0
- example:
short value = 2500;
int
int
is a 32-bit signed integer- Ranging from - 2,147,483,648 to - 2,147,483,647
- The default value is 0
- Example:
int value = 32540785;
long
long
is a 64-bit signed integer- Ranging from -9,223,372,036,854,775,808 to -9,223,372,036,854,775,807
- The default value is 0L
- Example:
long value = -250000L
float
float
is a 32-bit floating point with precision- The default value is 0.0f
- Example:
float value = 45.2f;
double
double
is a 64-bit floating-point with precision- The default value is 0.0d
- Example:
double value = 458.23;
boolean
boolean
type is a 1-bit informationboolean
has two values.true
andfalse
- The default value is false
- Example:
boolean status = true;
char
char
is a single 16-bit Unicode character- char data type is used to hold a single character
- Example:
char value = 'x';
Object(Reference) data types
Object data types represent a variable with its type as an object that is the combination of other object data types and primitive types.
Object types can be created by using the constructors of Java classes.
Object types are used to access properties and methods defined inside a java class.
The The default value of an object type is null
.
Example: Car benz = new Car();
Here benz
is an object of type Car
.
String
String
is a reference type that can store character strings. All string literals in Java are the instances of the inbuilt String
class
Keep the below points in mind while creating Java variables.
- We can create a java variable by using 0-9, A-Z,a-z, _ and $
- Variable names must start with a letter,- or $.
- Variable names are case-sensitive. name and Name are two different variables.
- Java reserved keywords like class, public, int, boolean ... are not allowed to be variable names.
Examples: