Primitive types in Java consist of boolean and numeric types: char, byte, short, int, long, float, and double.
Unlike reference types, the number of primitive types is limited and predefined in the language.
Memory location for primitive types directly stores the actual data held by the variable, not a reference to it.
Differences
Number and Definition:
Reference Types: Unlimited number, defined by the user.
Primitive Types: Limited and predefined in the language.
Memory Location:
Reference Types: Stores a reference to the data in memory.
Primitive Types: Stores the actual data held by the variable.
Assignment (Note the Difference!):
Reference Types: When assigned to another reference type, both references point to the same object in memory.
Primitive Types: When assigned to another variable of the same type, a copy of the data is made.
Method Parameter Passing:
Reference Types: When an object is passed into a method, the method can change the contents of the object, but not the address/reference of the object.
Primitive Types: When a primitive is passed into a method, only a copy of the primitive is passed. The called method does not have access to the original primitive value and can only change the copied value.
public class PrimitiveTypesExample {
public static void main(String[] args) {
// Declaration and initialization of primitive variables
boolean isJavaFun = true;
char grade = 'A';
byte byteValue = 127; // byte range: -128 to 127
short shortValue = 32000; // short range: -32,768 to 32,767
int intValue = 42;
long longValue = 123456789L; // The 'L' indicates a long literal
float floatValue = 3.14f; // The 'f' indicates a float literal
double doubleValue = 2.71828;
// Displaying values
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Grade: " + grade);
System.out.println("Byte Value: " + byteValue);
System.out.println("Short Value: " + shortValue);
System.out.println("Int Value: " + intValue);
System.out.println("Long Value: " + longValue);
System.out.println("Float Value: " + floatValue);
System.out.println("Double Value: " + doubleValue);
}
}
Value Types (Primitive Types)
General Information
Differences
Number and Definition:
Memory Location:
Assignment (Note the Difference!):
Method Parameter Passing: