Understanding variables and data types is a core foundation in Java programming. Variables store values, and data types define what kind of data those variables can hold.


๐Ÿ“ฆ What is a Variable?

A variable in Java is a container that stores data during program execution.

java
int age = 25; String name = "PrepCampusPlus";

Think of variables as labeled boxes that hold values.


๐Ÿ“š Types of Variables in Java

TypeDescriptionExample
๐Ÿง Local VariableDeclared inside a methodint total = 0;
๐ŸŒ Instance VariableDeclared inside a class but outside methodsString name;
๐Ÿ›️ Static VariableDeclared with static keyword, shared across objectsstatic int count;

๐Ÿ”ค Java Data Types

Java is statically typed, so you must declare the type of each variable.

java
int count = 100; double price = 99.99; char grade = 'A'; boolean isPassed = true;

๐Ÿงฑ Java Data Types Categories

1️⃣ Primitive Data Types (8 Types)

Data TypeSizeDescriptionExample
byte1 byteSmall integer (-128 to 127)byte b = 10;
short2 bytesMedium integershort s = 1000;
int4 bytesDefault integer typeint age = 25;
long8 bytesLarge integerslong population = 7000000000L;
float4 bytesDecimal numbers (less precise)float pi = 3.14f;
double8 bytesDecimal numbers (more precise)double price = 99.99;
char2 bytesSingle characterchar grade = 'A';
boolean1 bittrue or falseboolean isValid = true;

2️⃣ Non-Primitive (Reference) Data Types

TypeExample
StringString name = "Java";
Arraysint[] scores = {90, 80, 70};
Classes, ObjectsStudent s = new Student();

These types reference memory locations and can hold multiple values or behaviors.


๐Ÿง  Variable Naming Rules

✅ Must start with a letter, $, or _
✅ Can contain numbers but not at the start
❌ No Java keywords (like class, int)
✅ Use meaningful names (age, not a)


๐Ÿ“˜ Best Practices

  • Use camelCase for variable names: studentName

  • Use UPPER_CASE for constants: PI = 3.14159

  • Always initialize your variables before using them


๐Ÿงช Code Example

java
public class DataTypeExample { public static void main(String[] args) { int age = 22; float gpa = 8.5f; boolean passed = true; String name = "John"; System.out.println(name + " is " + age + " years old."); } }

๐Ÿ“Œ Summary Table

CategoryExamples
Primitive Typesint, float, char, boolean
Reference TypesString, Arrays, Objects
Variable TypesLocal, Instance, Static