Beginner
Variables and Data Types
📂 Phase 1: Java Foundations (Days 1–5) · JavaJava is statically typed — every variable must be declared with a type before use, and that type cannot change. This catches many errors at compile time rather than at runtime.
The 8 Primitive Data Types
| Type | Size | Range / Use | Example |
|---|---|---|---|
| byte | 1 byte | -128 to 127 | byte b = 100; |
| short | 2 bytes | -32,768 to 32,767 | short s = 5000; |
| int | 4 bytes | ~ -2.1B to 2.1B | int age = 21; |
| long | 8 bytes | Very large whole numbers | long pop = 8000000000L; |
| float | 4 bytes | Decimal, less precision | float pi = 3.14f; |
| double | 8 bytes | Decimal, default for decimals | double price = 99.99; |
| char | 2 bytes | Single character | char grade = 'A'; |
| boolean | 1 bit | true or false | boolean isPassed = true; |
Declaring and Initializing Variables
int score = 95;
String name = "Vishwas"; // non-primitive (object) type
double percentage = 87.5;
boolean isActive = true;
char initial = 'V';
Variable Naming Rules
- Must start with a letter, $ or _ (never a digit)
- Case-sensitive:
ageandAgeare different variables - Convention: camelCase for variables (
totalMarks, nottotal_marks) - Cannot use Java reserved keywords (
class,int,return, etc.)
Primitive vs Non-Primitive Types
Primitives (int, char, boolean, etc.) store actual values directly in memory. Non-primitive types like String, arrays, and objects store a reference to where the data lives in memory — this distinction becomes important later when learning about pass-by-value behavior in method calls.
Interview tip: Java has no unsigned types (unlike C/C++) — every numeric primitive except char is signed by default.