Java Data Types
Java Data Types
stored and
manipulated. Java categorizes data types into two main groups: primitive data types and non-primitive (or
reference) data types.
1. Primitive Data Types:
A primitive data type specifies the type of a variable and the kind of values it can hold. There are eight
primitive data types in Java.
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid
types are byte, short, int and long. Which type you should use, depends on the numeric value.
int: 32-bit signed integer, the most commonly used integer type. Stores whole numbers from
-2,147,483,648 to 2,147,483,647.
Example:
int myNum = 100000;
System.out.println(myNum);
long: 64-bit signed integer, used for very large integer values. Stores whole numbers from
–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Example:
long myNum = 15000000000L;
System.out.println(myNum);
Floating point types represents numbers with a fractional part, containing one or more decimals. There
are two types: float and double.
float: 32-bit single-precision floating-point number (Stores fractional numbers.), used for decimal
values. Sufficient for storing 6 to 7 decimal digits. A floating point number can also be a scientific
number with an "e" to indicate the power of 10:
Example:
float myNum = 5.75f;
System.out.println(myNum);
double: 64-bit double-precision floating-point number, the default type for decimal numbers and
offers higher precision than float. Sufficient for storing 15 to 16 decimal digits.
Example:
double myNum = 19.99d;
System.out.println(myNum);
Example:
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
O/P: 35000.0
120000.0
char: 16-bit Unicode character, used to store a single character/letter or ASCII values.
Exmaple:
char myGrade = 'B';
System.out.println(myGrade);
The main differences between primitive and non-primitive data types are:
Primitive types in Java are predefined and built into the language, while non-primitive types are
created by the programmer (except for String).
Non-primitive types can be used to call methods to perform certain operations, whereas primitive
types cannot.
Primitive types start with a lowercase letter (like int), while non-primitive types typically starts
with an uppercase letter (like String).
Primitive types always hold a value, whereas non-primitive types can be null.