Variables are reserved memory locations for storing values. When a variable is created, it reserves some space in memory. Based on the variable's data type, the operating system allocates memory and decides what can be stored in reserved memory. Therefore, by assigning different data types to variables, it is possible to store integers, decimals or characters in these variables.
There are two data types in Java −
Java supports eight primitive data types. Primitive data types are predefined by the language and named by keywords. Let's understand and learn these eight primitive data types in detail.
Types of | describe | range of values | Defaults | example |
---|---|---|---|---|
byte | Represents a 8 1-bit signed two's complement integer |
-128 (-2^7) -127 (2^7 -1) |
0 |
byte a = 100, byte b = -50 |
short | Represents a 16 1-bit signed two's complement integer |
-2^15 -2^15 -1 |
0 |
short s = 10000, short r = -20000 |
int | Represents a 32 1-bit signed two's complement integer |
-2^31 -2^31 -1 |
0 |
int a = 100000, int b = -200000 |
long | Represents 64 a signed two's complement integer |
-2^63 -2^63 -1 |
0L |
long a = 100000L, long b = -200000L |
float | Represents a single-precision 32 bit IEEE 754 floating-point number |
- | 0.0f |
float f1 = 234.5f |
double | Represents a double- 64 bit IEEE 754 floating-point number |
- | 0.0d |
double d1 = 123.4 |
boolean | Represents a bit of information | true /false |
false |
boolean one = true |
char | Represents a single 16-bit Unicode character | \u0000 -\uffff |
- | char letterA = 'A' |
Employee
, Dog
class, etc.null
.Dog dog = new Dog("ask");
A literal is a source code representation of a fixed value. They are represented directly in the code without any calculations. Literals can be assigned to any primitive type variable. E.g -
byte a = 68;
char a = 'A';
byte
, int
, long
and short
can also be expressed in decimal (base 10
), hexadecimal (base 16
), or octal (base 8
) numbers.
The prefixes 0
are used to indicate octal and the prefixes 0x
indicate hexadecimal when using these number systems for literals. E.g-
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
"Hello World"
"two\nlines"
""This is in quotes""
char a = '\u0001';
String a = "\u0001";
Symbol | Character |
---|---|
|
line break(0x0a) |
|
Return (0x0d) |
|
form feed(0x0c) |
|
backspace(0x08) |
|
Space (0x20) |
|
Tabs |
|
Double quotes |
|
Apostrophe |
|
backslash |
|
octal(ddd) |
|
hexadecimal UNICODE (xxxx) |