Skip to main content

Java Data Types

Java is a statically typed language, meaning every variable must be declared with a data type. Data types define the kind of data a variable can hold.

πŸ”° Categories of Data Types​

Java data types are divided into two main categories:

  1. Primitive Data Types
  2. Non-Primitive (Reference) Data Types

🧱 1. Primitive Data Types​

Java has 8 built-in (primitive) data types:

Data TypeSizeDescriptionExample
byte1 byteStores whole numbers from -128 to 127byte b = 100;
short2 bytesStores whole numbers from -32,768 to 32,767short s = 30000;
int4 bytesStores whole numbers from -2^31 to 2^31-1int i = 500000;
long8 bytesStores very large whole numberslong l = 10000000000L;
float4 bytesStores fractional numbers (6-7 decimal digits)float f = 5.75f;
double8 bytesStores fractional numbers (15 decimal digits)double d = 19.99;
boolean1 bitStores true or false valuesboolean isJavaFun = true;
char2 bytesStores a single characterchar grade = 'A';

🧭 2. Non-Primitive (Reference) Data Types​

These refer to objects and include:

  • Strings
  • Arrays
  • Classes
  • Interfaces
String name = "InitCareer";
int[] numbers = {1, 2, 3};

Non-primitive types are created by the programmer and have methods associated with them.


πŸš€ Real World Example​

Think of primitive types as basic ingredients like rice, sugar, and salt. Non-primitive types are like recipes you create using those ingredients.


🧠 Explain Like I'm Five​

Primitive types are like LEGO blocks. Each one is a fixed shape and color. You can combine them to build something bigger (non-primitive types), like a LEGO house or car.


πŸ’‘ Fun Fact​

Java's primitive types are not objects, which makes them faster for computationβ€”great for performance-critical applications like games or real-time systems.


πŸ§ͺ Exercise​

  1. Declare a variable of each primitive type.
  2. Print their default values.
  3. Create a String and an array, then print them.
public class DataTypesExample {
public static void main(String[] args) {
byte b = 10;
short s = 1000;
int i = 100000;
long l = 10000000000L;
float f = 5.75f;
double d = 19.99;
boolean bool = true;
char c = 'A';

String name = "InitCareer";
int[] numbers = {1, 2, 3};

System.out.println("Byte: " + b);
System.out.println("Short: " + s);
System.out.println("Int: " + i);
System.out.println("Long: " + l);
System.out.println("Float: " + f);
System.out.println("Double: " + d);
System.out.println("Boolean: " + bool);
System.out.println("Char: " + c);
System.out.println("String: " + name);
System.out.println("Array element: " + numbers[0]);
}
}