0% completed
In Java, primitive data types are the most basic data types provided by the language. They directly store the value and are not objects. Java supports eight primitive data types, and each type has a specific size and range. Understanding these data types is crucial as they form the foundation of data handling in Java.
The general syntax for declaring and initializing a variable with a primitive data type is as follows:
type variableName = value;
int, char, double).The byte data type is an 8-bit signed integer. It is typically used to save memory in large arrays where the memory savings matter.
In this example, we declare a byte variable and print its value.
The short data type is a 16-bit signed integer. It is used when memory savings are important, and the range of values is sufficient.
In this example, we declare a short variable myShort and assign it the value 20000.
The int data type is a 32-bit signed integer. It is one of the most commonly used data types for numeric operations.
In this example, we declare an int variable named myInt and initialize it with 100000.
The long data type is a 64-bit signed integer. It is used for values that exceed the range of int.
In this example, we declare a long variable named myLong and assign it the value 10000000000L. The L at the end indicates it’s a long literal.
The float data type is a 32-bit floating-point number. It is used for precise calculations with fractional numbers.
In this example, we declare a float variable myFloat and assign it the value 5.75f. The f indicates it’s a float literal.
The double data type is a 64-bit floating-point number. It is the default data type for decimal values and is used for precise calculations.
In this example, we declare a double variable named myDouble and assign it the value 19.99.
The char data type is a 16-bit Unicode character. It is used to store a single character.
In this example, we declare a char variable named myChar and assign it the value 'A'.
The boolean data type has only two possible values: true or false. It is used for conditional statements.
true or falseIn this example, we declare a boolean variable named myBoolean and assign it the value true.
| Data Type | Size (bits) | Range/Precision | Example Value |
|---|---|---|---|
| byte | 8 | -128 to 127 | 100 |
| short | 16 | -32,768 to 32,767 | 30000 |
| int | 32 | -2,147,483,648 to 2,147,483,647 | 100000 |
| long | 64 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 10000000000L |
| float | 32 | 6-7 decimal digits (approx.) | 5.75f |
| double | 64 | 15 decimal digits (approx.) | 19.99 |
| char | 16 | '\u0000' to '\uffff' (Single Unicode character) | 'A' |
| boolean | – | Only true or false | true |
.....
.....
.....