Skip to main content

1. Java Types

In Java, data types are divided into two main categories: Primitive Types and Reference (Object) Types. Understanding these types is crucial for effective programming in Java.

1. Primitive Types

Primitive types are the basic data types provided by Java. They are not objects and hold their values directly in memory. Java has eight primitive data types:

TypeSize (in bytes)Default ValueDescription
byte108-bit signed integer
short2016-bit signed integer
int4032-bit signed integer
long80L64-bit signed integer
float40.0fSingle-precision 32-bit floating-point
double80.0Double-precision 64-bit floating-point
char2'\u0000'Single 16-bit Unicode character
boolean1 (not precisely defined)falseRepresents true or false values
public class PrimitiveExample {
public static void main(String[] args) {
int number = 10; // Integer
char letter = 'A'; // Character
boolean isActive = true; // Boolean
}
}

2. Object (Reference) Types

Reference types, also known as object types, refer to objects and hold a reference to the memory location where the object is stored. They can be created from classes, interfaces, and arrays. Key characteristics include:

  • Dynamic Size: The size of an object is determined at runtime.
  • Null Reference: A reference type can be assigned a null value, indicating that it does not point to any object.

Common Object Types:

TypeDescription
ClassesUser-defined data types that encapsulate data and behavior.
InterfacesAbstract types that define a contract for classes to implement.
ArraysA collection of elements of the same type, stored in contiguous memory locations.
public class ObjectExample {
public static void main(String[] args) {
String text = "Hello, World!"; // String object
Integer number = new Integer(10); // Integer object
int[] numbers = {1, 2, 3, 4, 5}; // Array of integers
}
}

3. Summary of Java Types

Type CategoryDescriptionExamples
Primitive TypesBasic data types holding their values directly.int, char, boolean
Reference TypesHold references to objects in memory.String, Array, Custom Class

4. Key Differences Between Primitive and Reference Types

FeaturePrimitive TypesReference Types
StorageDirectly stores valuesStores references to objects
SizeFixed size (defined by type)Dynamic size (depends on object)
Default ValueHas a default valueDefault is null
Null ValueCannot be nullCan be null