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.
Think of variables as labeled boxes that hold values.
๐ Types of Variables in Java
Type | Description | Example |
---|---|---|
๐ง Local Variable | Declared inside a method | int total = 0; |
๐ Instance Variable | Declared inside a class but outside methods | String name; |
๐️ Static Variable | Declared with static keyword, shared across objects | static int count; |
๐ค Java Data Types
Java is statically typed, so you must declare the type of each variable.
๐งฑ Java Data Types Categories
1️⃣ Primitive Data Types (8 Types)
Data Type | Size | Description | Example |
---|---|---|---|
byte | 1 byte | Small integer (-128 to 127) | byte b = 10; |
short | 2 bytes | Medium integer | short s = 1000; |
int | 4 bytes | Default integer type | int age = 25; |
long | 8 bytes | Large integers | long population = 7000000000L; |
float | 4 bytes | Decimal numbers (less precise) | float pi = 3.14f; |
double | 8 bytes | Decimal numbers (more precise) | double price = 99.99; |
char | 2 bytes | Single character | char grade = 'A'; |
boolean | 1 bit | true or false | boolean isValid = true; |
2️⃣ Non-Primitive (Reference) Data Types
Type | Example |
---|---|
String | String name = "Java"; |
Arrays | int[] scores = {90, 80, 70}; |
Classes , Objects | Student 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
๐ Summary Table
Category | Examples |
---|---|
Primitive Types | int , float , char , boolean |
Reference Types | String , Arrays , Objects |
Variable Types | Local, Instance, Static |