Variables & Primitive Types
Primitive data types, type system, naming conventions, two's complement
- Understand Java's static and strong type system
- Master all 8 primitive data types with ranges and defaults
- Apply variable naming conventions
- Understand two's complement representation
These notes are derived from the Concept and Coding Java lecture series on Variables. They are designed to be fully self-contained — no prior lecture viewing is required.
Table of Contents
- What is a Variable?
- Java as a Statically Typed & Strongly Typed Language
- Variable Declaration Syntax
- Variable Naming Conventions
- Types of Variables in Java
- Primitive Data Types — Deep Dive
- Member (Instance) Variables
- Local Variables
- Static (Class) Variables
- Method Parameters
- Constructor Parameters
- Default Values
- Float & Double — The Precision Warning
- Quick-Reference Tables
- Mermaid Diagrams
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Cheat Sheet
1. What is a Variable?
Overview
A variable is the most fundamental building block of any Java program. Before you can write any meaningful logic, you must understand what variables are and how Java manages them.
Real-World Analogy
Think of a variable as a labelled container (like a jar with a name written on it). The container has:
- A label (the variable name) — so you can refer to it later.
- A type of content it can hold (the data type) — a jar labelled water can only hold water; a jar labelled coins can only hold coins.
- The actual content (the value) — e.g., the number
32.
Definition
A variable in Java is a named memory location that holds a value of a specific data type.
Syntax
1dataType variableName = value;Example
1int var = 32;Line-by-Line Explanation
| Part | Meaning |
|---|---|
int | Data type — tells Java the variable will hold whole (integer) numbers |
var | Variable name — the label you use to refer to this container |
= | Assignment operator — puts the value into the container |
32 | The value stored in the container |
; | Semicolon — required at the end of every Java statement |
Memory Representation
When int var = 32; is executed:
- Java allocates 4 bytes of memory on the stack (for local variables) or heap (for instance variables inside objects).
- The value
32is stored in binary (00000000 00000000 00000000 00100000). - The name
varis a reference to that memory location.
2. Java as a Statically Typed & Strongly Typed Language
Overview
Java has two important type-related properties that distinguish it from dynamically typed languages like Python or JavaScript.
Static Typing
Static type language
: Every variable must have its data type declared at compile time.
In Java, you cannot write:
1var = 10; // ❌ ERROR — data type not specifiedYou must always write:
1int var = 10; // ✅ data type 'int' declared explicitlyThe compiler knows the type of every variable before the program runs. This allows the compiler to catch type errors early.
Contrast with Python (dynamically typed):
1var = 10 # Python infers the type at runtime — no declaration needed2var = "hello" # Python allows reassigning a different type to the same variableIn Java, this is impossible — once var is declared as int, it can only hold integers.
Strong Typing
Strongly typed language
: Every data type has a defined range, and you cannot assign a value outside that range without explicit handling.
In Java, each primitive data type has strict limits:
intcan hold values approximately from −2.1 billion to +2.1 billion.- You cannot store a value like
99999999999999in anintwithout a compile-time error.
Strong typing prevents accidental data corruption and makes Java programs more predictable and safe.
Interview Question
Q: Is Java a statically typed language? Is Java a strongly typed language?
A: Yes to both.
- Static: All variable types must be declared at compile time.
- Strong: Each type has a fixed range and implicit out-of-range assignments are not allowed.
3. Variable Declaration Syntax
Full Syntax
1dataType variableName = value;Variations
1int age; // Declaration only (no value assigned yet)2int age = 25; // Declaration + initialization3int a, b, c; // Multiple variables of the same type in one line4int a = 1, b = 2; // Multiple variables with initial valuesSyntax Breakdown
| Element | Description |
|---|---|
dataType | One of Java's 8 primitive types, or a reference type (class/interface/array) |
variableName | A legal Java identifier following naming conventions |
= | The assignment operator |
value | A literal, expression, or result of a method call compatible with dataType |
; | Statement terminator — mandatory in Java |
4. Variable Naming Conventions
Java has both rules (enforced by the compiler) and conventions (followed by professional developers).
Rules Compiler Enforced
Rule 1: Variable Names Are Case-Sensitive
1int age = 10;2int Age = 20; // This is a DIFFERENT variable from 'age'3int AGE = 30; // This is yet another DIFFERENT variableAll three are distinct variables because Java differentiates uppercase and lowercase letters.
Rule 2: Legal Characters
Variable names may contain:
- Unicode letters (A–Z, a–z, and letters from any human language)
- Digits (0–9) — but NOT as the first character
- Dollar sign (
$) - Underscore (
_)
1int myVar = 1; // ✅ starts with letter2int _myVar = 2; // ✅ starts with underscore3int $myVar = 3; // ✅ starts with dollar sign4int myVar9 = 4; // ✅ digit is NOT the first character5
6int 9myVar = 5; // ❌ ILLEGAL — cannot start with a digit7int my-Var = 6; // ❌ ILLEGAL — hyphen is not allowed8int my Var = 7; // ❌ ILLEGAL — space is not allowedRule 3: Cannot Use Java Reserved Words
Java reserves certain keywords for its own syntax. You cannot use them as variable names.
Examples of reserved words:
| Category | Keywords |
|---|---|
| Data types | int, float, double, char, boolean, byte, short, long |
| OOP | class, interface, extends, implements, new, this, super |
| Control flow | if, else, for, while, do, switch, case, break, continue, return |
| Access modifiers | public, private, protected |
| Others | static, final, void, null, true, false |
1int int = 5; // ❌ 'int' is a reserved word — compiler error2int class = 5; // ❌ 'class' is a reserved word — compiler errorConventions Professional Standards
Convention 1: Single-Word Variable Names All Lowercase
1int age = 25;2String city = "Jaipur";3double price = 99.99;Convention 2: Multi-Word Variable Names camelCase
When a variable name consists of multiple words, start with lowercase and capitalize each subsequent word.
1int jaipur = 2; // single word — all lowercase ✅2int jaipurCity = 2; // two words — camelCase ✅3int userAccountBalance; // three words — camelCase ✅Convention 3: Constant Variables ALL_CAPS with Underscores
When a variable is declared static final (meaning its value can never change), it should be named in ALL CAPITAL LETTERS, with words separated by underscores.
1static final int MAX_SPEED = 120;2static final double PI = 3.14159;3static final String APP_NAME = "MyApp";static final makes a variable a constant — its value is fixed for the lifetime of the program.
We will cover static and final keywords in detail in later sections.5. Types of Variables in Java
Java has two broad categories of variable types:
| Category | Description | Examples |
|---|---|---|
| Primitive | Basic, built-in data types; store actual values directly | int, double, char, boolean, etc. |
| Non-Primitive (Reference) | Store a reference (memory address) to an object | String, arrays, any class instance |
6. Primitive Data Types Deep Dive
Java has exactly 8 primitive data types:
1char | byte | short | int | long | float | double | booleanThey fall into three functional groups:
| Group | Types |
|---|---|
| Integral (whole numbers) | char, byte, short, int, long |
| Floating-point (decimal numbers) | float, double |
| Boolean (true/false) | boolean |
6.1 `char`
Overview
char stores a single character. Internally, Java stores characters as their Unicode / ASCII integer value, not as the visual symbol itself.
Size & Range
| Property | Value |
|---|---|
| Size | 2 bytes (16 bits) |
| Range | 0 to 65,535 |
| Default value | '\u0000' (null character) |
| Type | Unsigned (no negative values) |
Why 65,535?
With 16 bits, the maximum unsigned value is:
12^15 + 2^14 + ... + 2^1 + 2^0 = 65,5352(all 16 bits set to 1)This covers all standard ASCII characters (0–127) plus the extended Unicode characters.
Syntax
1char variableName = 'A'; // character literal (use single quotes)2char variableName = 65; // integer literal — Java converts to 'A'3char variableName = '\u0041'; // Unicode escape for 'A'char literals. Double quotes ("A") are for String — a completely different type.ASCII Quick Reference
| Decimal | Character |
|---|---|
| 65 | A |
| 66 | B |
| 97 | a |
| 98 | b |
| 48 | 0 (digit zero) |
| 64 | @ |
Code Examples
1public class CharExample {2 public static void main(String[] args) {3 char c1 = 'A'; // Assign a character literal4 char c2 = 65; // Assign an integer — internally treated as 'A'5 char c3 = 97; // 97 is the ASCII code for 'a'6
7 System.out.println(c1); // Output: A8 System.out.println(c2); // Output: A9 System.out.println(c3); // Output: a10 }11}A A a
Line-by-Line Explanation
char c1 = 'A';— Declares a char and directly assigns the characterA.char c2 = 65;— The integer65is the ASCII code forA. Java internally stores65and displaysAwhen printed.char c3 = 97;— The integer97is the ASCII code for lowercasea.
6.2 `byte`
Overview
byte is the smallest integer type in Java. It is useful when memory is critical and values are known to be small (e.g., raw binary data, file I/O).
Size & Range
| Property | Value |
|---|---|
| Size | 1 byte (8 bits) |
| Range | −128 to 127 |
| Default value | 0 |
| Representation | Signed two's complement |
Why 128 to 127 (Not 0 to 255)?
With 8 bits, you can represent 256 (2^8) distinct values. Because byte is signed (allows negative numbers), half the range is negative:
- Positive side: 0 to 127 (128 values)
- Negative side: −128 to −1 (128 values)
- Total: 256 values
The most significant bit (MSB) — the leftmost bit — acts as the sign bit:
- MSB =
0→ positive number - MSB =
1→ negative number
This is called two's complement representation (explained in detail in Section 7).
Syntax
1byte variableName = 100;2byte variableName = -50;Code Example Default Value
1public class Employee {2 byte memberVar; // class member variable — automatically initialized to 03
4 void dummy() {5 System.out.println(memberVar); // prints 06 }7}8
9public class Main {10 public static void main(String[] args) {11 Employee emp = new Employee();12 emp.dummy();13 }14}0
0 for byte) are only assigned to class member variables (instance variables). Local variables inside methods do NOT get default values — you must assign them manually before use.Code Example Local Variable Must Be Initialized
1void myMethod() {2 byte localVar; // declared but NOT initialized3 System.out.println(localVar); // ❌ COMPILE ERROR: variable localVar might not have been initialized4}Correct:
1void myMethod() {2 byte localVar = 7; // ✅ initialized before use3 System.out.println(localVar); // Output: 74}6.3 `short`
Overview
short is rarely used in modern Java but exists for memory optimization in large arrays.
Size & Range
| Property | Value |
|---|---|
| Size | 2 bytes (16 bits) |
| Range | −32,768 to 32,767 |
| Default value | 0 |
| Representation | Signed two's complement |
Syntax
1short s = 200;2short s = -1000;6.4 `int`
Overview
int is the most commonly used integer type in Java. When you write a whole number literal in Java code, the compiler treats it as int by default.
Size & Range
| Property | Value |
|---|---|
| Size | 4 bytes (32 bits) |
| Range | −2,147,483,648 to 2,147,483,647 (approximately ±2.1 billion) |
| Default value | 0 |
| Representation | Signed two's complement |
Range Formula
1Minimum: −2^31 = −2,147,483,6482Maximum: 2^31 − 1 = 2,147,483,647Syntax
1int age = 25;2int temperature = -5;3int population = 1_000_000; // underscores allowed in Java 7+ for readabilityCode Example
1public class IntExample {2 public static void main(String[] args) {3 int a = 100;4 int b = 200;5 int sum = a + b;6 System.out.println("Sum: " + sum); // Output: Sum: 3007 }8}6.5 `long`
Overview
Use long when your value exceeds the range of int (greater than ~2.1 billion). Common use cases include timestamps (milliseconds since epoch), large file sizes, and population counters.
Size & Range
| Property | Value |
|---|---|
| Size | 8 bytes (64 bits) |
| Range | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (approximately ±9.2 × 10^18) |
| Default value | 0L |
| Representation | Signed two's complement |
Syntax
1long bigNumber = 500L; // 'L' suffix tells Java this is a long literal2long worldPopulation = 8_000_000_000L;L (uppercase) or l (lowercase, but avoid — it looks like the digit 1) when writing long literals that exceed int's range.
Without L, Java tries to interpret the literal as an int first, which will cause a compile-time error if the value is too large.Code Example
1public class LongExample {2 public static void main(String[] args) {3 long var = 100L;4 System.out.println(var); // Output: 1005 }6}6.6 `float`
Overview
float stores single-precision 32-bit floating-point numbers (decimal values). It follows the IEEE 754 standard.
Size & Range
| Property | Value |
|---|---|
| Size | 4 bytes (32 bits) |
| Precision | ~6–7 significant decimal digits |
| Default value | 0.0f |
| Standard | IEEE 754 single precision |
Syntax
1float price = 63.20f; // 'f' suffix is REQUIRED2float pi = 3.14f;f suffix is mandatory for float literals. Without it, Java treats the decimal number as a double by default, causing a compile error when assigning to a float variable.1float x = 3.14; // ❌ ERROR — 3.14 is a double literal; incompatible types2float x = 3.14f; // ✅ CORRECTPrecision Warning
Float and double should NEVER be used for precise financial or currency calculations. See Section 11 for a detailed explanation.
6.7 `double`
Overview
double stores double-precision 64-bit floating-point numbers. It is the default type for decimal literals in Java and provides roughly twice the precision of float.
Size & Range
| Property | Value |
|---|---|
| Size | 8 bytes (64 bits) |
| Precision | ~15–16 significant decimal digits |
| Default value | 0.0d |
| Standard | IEEE 754 double precision |
Syntax
1double price = 63.20; // no suffix needed — double is the default2double price = 63.20d; // 'd' suffix is optional but validPrecision Warning
Same as float — do not use for currency. See Section 11.
6.8 `boolean`
Overview
boolean stores one of only two possible values: true or false. It is used for all conditional logic.
Size & Range
| Property | Value |
|---|---|
| Size | Conceptually 1 bit (JVM implementation may vary) |
| Values | true or false only |
| Default value | false |
Syntax
1boolean isLoggedIn = true;2boolean hasError = false;Code Example
1public class BooleanExample {2 public static void main(String[] args) {3 boolean isJavaFun = true;4 boolean isHard = false;5
6 System.out.println("Java is fun: " + isJavaFun); // Output: Java is fun: true7 System.out.println("Java is hard: " + isHard); // Output: Java is hard: false8
9 if (isJavaFun) {10 System.out.println("Let's keep learning!");11 }12 }13}Java is fun: true Java is hard: false Let's keep learning!
7. Two's Complement & Signed Representation
Why This Matters
This is one of the most important (and confusing) concepts for beginners. Java's integer types (byte, short, int, long) are all signed two's complement integers. Understanding this explains why the ranges are asymmetric and what happens during overflow.
The Sign Bit
In any signed binary number:
- The most significant bit (MSB) — leftmost — is the sign bit.
0in MSB → positive number1in MSB → negative number
For a byte (8 bits):
10 1 1 1 1 1 1 1 = +127 (MSB = 0, so positive)21 0 0 0 0 0 0 0 = −128 (MSB = 1, so negative)What is Two's Complement?
Two's complement is the method Java uses to represent negative numbers in binary.
Step-by-Step: How to Find Two's Complement of a Number
Example: Represent −3 in binary using 4 bits
Step 1: Write +3 in binary (4 bits):
1+3 = 0011Step 2: Flip all the bits (this gives the one's complement):
10011 → 1100Step 3: Add 1 (this gives the two's complement):
11100 + 0001 = 1101So, −3 = 1101 in 4-bit two's complement.
Verification: +3 + ( 3) Should Equal 0
1 0011 (+3)2+ 1101 (−3)3------4 10000With 4-bit representation, we discard the 5th bit (carry overflow), leaving:
10000 = 0 ✅byte (8 bits), any carry into the 9th bit is similarly discarded.Why 128 to 127 (Not 127 to 127)?
- Positive values:
00000001to01111111→ 1 to 127 (127 values) - Zero:
00000000→ 0 (1 value) - Negative values:
10000000to11111111→ −128 to −1 (128 values)
This gives 256 total values, and the range −128 to 127.
There is one more negative value than positive because zero is counted on the positive side.
Overflow Behavior
When a value exceeds the maximum (127 for byte), it wraps around to the minimum:
1127 + 1 = 128 → overflows to −1282127 + 2 = 129 → overflows to −1278. Type Conversion
Overview
Java frequently requires converting values between different data types. There are three kinds of conversions:
- Widening (automatic)
- Narrowing (explicit / casting)
- Promotion (during expressions)
8.1 Widening (Automatic) Conversion
Definition
When you assign a value of a smaller data type to a larger data type, Java automatically converts it. No data is lost.
The Widening Hierarchy
You can always move to the right in this chain automatically.
Why No Data Loss?
The larger type has more bits, so it can fully contain the value of the smaller type.
Example: A byte (8 bits) value fits perfectly in an int (32 bits) — Java just pads the extra bits with zeros.
Code Examples
1public class WideningExample {2 public static void main(String[] args) {3 byte x = 10;4 int intVar = x; // ✅ automatic widening — no cast needed5 System.out.println(intVar); // Output: 106
7 int a = 500;8 long b = a; // ✅ int → long, automatic9 System.out.println(b); // Output: 50010
11 int c = 100;12 double d = c; // ✅ int → double, automatic13 System.out.println(d); // Output: 100.014 }15}10 500 100.0
8.2 Narrowing (Explicit / Downcasting)
Definition
When you assign a value of a larger data type to a smaller data type, Java does NOT convert automatically. You must explicitly tell Java to cast it. This is called explicit casting or narrowing.
Why Is This Manual?
The smaller type might not be able to hold the value — data could be lost. Java forces you to acknowledge this risk explicitly.
Syntax
1smallerType varName = (smallerType) largerTypeValue;Code Example Successful Cast
1public class NarrowingExample {2 public static void main(String[] args) {3 int intVar = 10;4 byte byteVar = (byte) intVar; // explicit cast5 System.out.println(byteVar); // Output: 106 }7}10
Code Example Data Loss During Cast
1public class OverflowExample {2 public static void main(String[] args) {3 int intVar = 128; // 128 is outside byte's range (max 127)4 byte byteVar = (byte) intVar; // explicit cast5 System.out.println(byteVar); // Output: -1286 }7}-128
Why Did 128 Become 128?
128 in binary (using 8 bits): 10000000
In two's complement, 10000000 represents −128.
So Java stored the bits as-is, and those bits mean −128 in a signed byte.
1128 → 10000000 → interpreted as −128 in two's complement2129 → 10000001 → interpreted as −1273130 → 10000010 → interpreted as −1268.3 Promotion During Expressions
Definition
When smaller types (byte, short, char) are used in arithmetic expressions, Java automatically promotes them to int before performing the calculation.
Why Does Java Do This?
To prevent overflow during intermediate calculations. If two byte values (each max 127) are added, their sum could be 254 — which overflows byte. By promoting to int, the calculation is safe.
Rule 1: byte and short Always Promoted to int
1byte a = 127;2byte b = 1;3byte sum = a + b; // ❌ ERROR — the expression (a + b) is of type int, not byteTo fix:
1byte a = 127;2byte b = 1;3int sum = a + b; // ✅ store result in int4System.out.println(sum); // Output: 128OR force it back to byte (with possible overflow):
1byte sum = (byte)(a + b); // explicit downcast — result is -128 due to overflow2System.out.println(sum); // Output: -128Rule 2: If Any Operand Is a Larger Type, the Whole Expression Promotes
1int + double → double2long + float → float3int + long → longThe expression result is always the largest type present.
1public class PromotionExample {2 public static void main(String[] args) {3 int a = 34;4 double b = 20.0;5
6 // a + b → int + double → promoted to double7 // int sum = a + b; // ❌ ERROR — result is double8 double sum = a + b; // ✅ CORRECT9 System.out.println(sum); // Output: 54.010 }11}If you need an int result:
1int sum = (int)(a + b); // explicit downcast to int2System.out.println(sum); // Output: 54Summary Flowchart
9. Kinds of Variables
Beyond type (primitive vs. reference), Java variables are also classified by where they are declared and how they behave. There are five kinds:
9.1 Member (Instance) Variables
Definition
Variables declared directly inside a class, but outside any method or constructor. Each object (instance) of the class gets its own private copy.
Key Characteristics
| Property | Detail |
|---|---|
| Declared in | Class body (outside any method) |
| Default value | Yes (see Section 10) |
| Scope | Accessible from any method in the class |
| Lifetime | Lives as long as the object lives |
| Copies | One per object |
Code Example
1public class Employee {2 int memberVariable = 10; // instance/member variable3}4
5public class Main {6 public static void main(String[] args) {7 Employee obj1 = new Employee();8 Employee obj2 = new Employee();9
10 obj1.memberVariable = 50;11 obj2.memberVariable = 100;12
13 System.out.println(obj1.memberVariable); // Output: 5014 System.out.println(obj2.memberVariable); // Output: 10015 }16}50 100
Explanation
Even though both obj1 and obj2 are created from the same Employee class, each has its own independent copy of memberVariable. Changing one does not affect the other.
9.2 Local Variables
Definition
Variables declared inside a method, constructor, or block. They are created when the method is called and destroyed when the method returns.
Key Characteristics
| Property | Detail |
|---|---|
| Declared in | Inside a method or block { } |
| Default value | None — must initialize before use |
| Scope | Only within the { } block where declared |
| Lifetime | Exists only during the execution of that method |
Code Example
1public class LocalExample {2 void myMethod() {3 byte localVar = 100; // must initialize manually4 System.out.println(localVar); // Output: 1005 } // localVar is destroyed here6}java
void myMethod() {
byte localVar;
System.out.println(localVar); // ❌ COMPILE ERROR
}
``9.3 Static (Class) Variables
Definition
Variables declared with the static keyword inside a class. There is only one copy for the entire class, shared by all objects.
Key Characteristics
| Property | Detail |
|---|---|
| Declared with | static keyword |
| Default value | Yes (same as member variables) |
| Scope | Class-wide |
| Lifetime | Entire program lifetime |
| Access | Via class name: ClassName.variableName |
| Copies | One per class (not per object) |
Code Example
1public class Employee {2 static int staticVar = 100; // one copy for all Employee objects3 int memberVar = 10; // one copy per Employee object4}5
6public class Main {7 public static void main(String[] args) {8 Employee obj1 = new Employee();9 Employee obj2 = new Employee();10
11 // Access static variable via class name12 System.out.println(Employee.staticVar); // Output: 10013
14 // Both objects share the same static variable15 Employee.staticVar = 999;16 System.out.println(Employee.staticVar); // Output: 99917
18 // Member variables are independent per object19 obj1.memberVar = 50;20 obj2.memberVar = 75;21 System.out.println(obj1.memberVar); // Output: 5022 System.out.println(obj2.memberVar); // Output: 7523 }24}100 999 50 75
Memory Diagram
1Method Area (JVM)2┌─────────────────────────┐3│ Employee class │4│ staticVar = 100 │ ← Only ONE copy5└─────────────────────────┘6
7Heap (JVM)8┌─────────────┐ ┌─────────────┐9│ obj1 │ │ obj2 │10│ memberVar=50│ │ memberVar=75│ ← Each object has its OWN copy11└─────────────┘ └─────────────┘9.4 Method Parameters
Definition
Variables listed in a method's parameter list. They receive values when the method is called.
Code Example
1public class Calculator {2 int add(int a, int b) { // a and b are method parameters3 return a + b;4 }5}6
7public class Main {8 public static void main(String[] args) {9 Calculator calc = new Calculator();10 int result = calc.add(2, 5); // 2 → a, 5 → b11 System.out.println(result); // Output: 712 }13}Key Points
- Method parameters behave like local variables — they are created when the method is called and destroyed when it returns.
- They have no default value — they are always provided by the caller.
9.5 Constructor Parameters
Definition
Variables listed in a constructor's parameter list. They receive values when a new object is created.
Code Example
1public class Employee {2 int id;3 String name;4
5 // Default constructor (no parameters)6 Employee() {7 id = 0;8 name = "Unknown";9 }10
11 // Parameterized constructor12 Employee(int id, String name) {13 this.id = id;14 this.name = name;15 }16}17
18public class Main {19 public static void main(String[] args) {20 Employee e1 = new Employee(); // calls default constructor21 Employee e2 = new Employee(101, "Alice"); // calls parameterized constructor22
23 System.out.println(e1.id + " " + e1.name); // Output: 0 Unknown24 System.out.println(e2.id + " " + e2.name); // Output: 101 Alice25 }26}this keyword will be covered in detail in later sessions.10. Default Values
Default values are automatically assigned by Java to class member variables and static variables when they are not explicitly initialized.
| Data Type | Default Value |
|---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' (null character) |
boolean | false |
| Object references | null |
Code Example
1public class DefaultValues {2 byte b;3 short s;4 int i;5 long l;6 float f;7 double d;8 char c;9 boolean bool;10
11 void printDefaults() {12 System.out.println("byte: " + b);13 System.out.println("short: " + s);14 System.out.println("int: " + i);15 System.out.println("long: " + l);16 System.out.println("float: " + f);17 System.out.println("double: " + d);18 System.out.println("char: " + (int)c); // print as int to see 019 System.out.println("boolean: " + bool);20 }21
22 public static void main(String[] args) {23 DefaultValues dv = new DefaultValues();24 dv.printDefaults();25 }26}byte: 0 short: 0 int: 0 long: 0 float: 0.0 double: 0.0 char: 0 boolean: false
11. Float & Double The Precision Warning
The Problem
Both float and double follow the IEEE 754 standard for floating-point arithmetic. This standard uses binary (base-2) representation for decimal numbers.
The problem is that many decimal fractions cannot be represented exactly in binary, just like 1/3 cannot be represented exactly in base-10 (0.3333...).
This leads to tiny rounding errors that accumulate during arithmetic operations.
Demonstration
1public class PrecisionProblem {2 public static void main(String[] args) {3 float var1 = 0.3f;4 float var2 = 0.1f;5 float var3 = var1 - var2; // expected: 0.26
7 System.out.println(var3); // Actual output: 0.200000028 }9}0.20000002
We expected 0.2, but got 0.20000002. The same issue occurs with double.
Why Does This Happen? (IEEE 754)
The value 0.3 in binary is a repeating fraction (similar to 1/3 in decimal). The computer stores an approximation, and when you subtract another approximation, the tiny errors compound.
Real-World Impact
This is NOT a minor academic concern. In financial systems:
- Wrong:
0.1 + 0.2 = 0.30000000000000004(float/double) - Correct:
0.1 + 0.2 = 0.3(BigDecimal)
Imagine a banking system charging a customer $0.30000000000000004 instead of $0.30 — multiplied across millions of transactions, this is catastrophic.
Solution: Use `BigDecimal`
For any application requiring exact decimal arithmetic (financial, scientific, medical):
1import java.math.BigDecimal;2
3public class BigDecimalExample {4 public static void main(String[] args) {5 BigDecimal a = new BigDecimal("0.3");6 BigDecimal b = new BigDecimal("0.1");7 BigDecimal result = a.subtract(b);8 System.out.println(result); // Output: 0.2 ✅9 }10}0.2
float or double for currency, financial calculations, or any domain requiring exact decimal precision. Use BigDecimal instead.BigDecimal from a String (new BigDecimal("0.3")), not from a double (new BigDecimal(0.3)) — the latter still carries the float/double imprecision into the BigDecimal.12. Quick-Reference Tables
All 8 Primitive Data Types
| Type | Size | Range | Default | Use Case |
|---|---|---|---|---|
byte | 1 byte (8 bits) | −128 to 127 | 0 | Raw binary data, small integers |
short | 2 bytes (16 bits) | −32,768 to 32,767 | 0 | Large arrays where memory matters |
int | 4 bytes (32 bits) | −2,147,483,648 to 2,147,483,647 | 0 | General-purpose integer (most common) |
long | 8 bytes (64 bits) | −9.2×10^18 to 9.2×10^18 | 0L | Large numbers, timestamps |
float | 4 bytes (32 bits) | ~±3.4×10^38 | 0.0f | Approximate decimals (avoid for money) |
double | 8 bytes (64 bits) | ~±1.8×10^308 | 0.0d | Approximate decimals (avoid for money) |
char | 2 bytes (16 bits) | 0 to 65,535 | '\u0000' | Single character |
boolean | ~1 bit (JVM-dependent) | true / false | false | Logical flags, conditions |
Type Suffixes
| Type | Suffix Required | Example |
|---|---|---|
long | L | 100L |
float | f | 3.14f |
double | d (optional) | 3.14d or 3.14 |
Variable Kinds at a Glance
| Kind | Declared In | Default Value? | Scope | Lifetime |
|---|---|---|---|---|
| Member (instance) | Class body | ✅ Yes | Whole class | Lifetime of object |
| Static (class) | Class body with static | ✅ Yes | Whole class | Whole program |
| Local | Inside method/block | ❌ No | That block only | Duration of method call |
| Method parameter | Method signature | ❌ No (caller provides) | Inside method | Duration of method call |
| Constructor parameter | Constructor signature | ❌ No (caller provides) | Inside constructor | During construction |
Type Conversion Summary
| Conversion | Direction | Manual Cast? | Data Loss Risk? |
|---|---|---|---|
| Widening | Small → Large | ❌ Not needed | None |
| Narrowing | Large → Small | ✅ Required | Yes (possible overflow) |
| Promotion | During expression | ❌ Automatic | None (result in larger type) |
13. Mermaid Diagrams
Primitive Type Hierarchy
Widening Conversion Chain
Type Conversion Decision Flowchart
Variable Scope Diagram
14. Common Mistakes
Mistake 1: Starting a Variable Name with a Digit
1int 1stValue = 10; // ❌ COMPILE ERROR2int firstValue = 10; // ✅ CORRECTMistake 2: Using a Reserved Word as a Variable Name
1int int = 5; // ❌ COMPILE ERROR — 'int' is reserved2int myInt = 5; // ✅ CORRECTMistake 3: Using float/double for Currency
1float price = 0.3f - 0.1f;2System.out.println(price); // ❌ Prints 0.20000002 — NOT 0.2!3
4// ✅ Correct:5import java.math.BigDecimal;6BigDecimal price = new BigDecimal("0.3").subtract(new BigDecimal("0.1"));7System.out.println(price); // Prints 0.2Mistake 4: Forgetting the `L` Suffix for long Literals
1long bigNum = 10000000000; // ❌ COMPILE ERROR — too big for int2long bigNum = 10000000000L; // ✅ CORRECTMistake 5: Forgetting the `f` Suffix for float
1float f = 3.14; // ❌ COMPILE ERROR — 3.14 is a double literal2float f = 3.14f; // ✅ CORRECTMistake 6: Using a Local Variable Without Initializing
1void myMethod() {2 int x;3 System.out.println(x); // ❌ COMPILE ERROR — x not initialized4}5
6void myMethod() {7 int x = 0;8 System.out.println(x); // ✅ CORRECT9}Mistake 7: Expecting Narrowing to Happen Automatically
1int bigValue = 200;2byte b = bigValue; // ❌ COMPILE ERROR — possible loss of value3
4byte b = (byte) bigValue; // ✅ explicit cast — but b will be -56 (overflow!)Mistake 8: Confusing Single vs. Double Quotes for char
1char c = "A"; // ❌ COMPILE ERROR — "A" is a String, not a char2char c = 'A'; // ✅ CORRECT — single quotes for charMistake 9: Accessing Static Variables Through Object References
1Employee.staticVar = 10; // ✅ Access through class name (recommended)2obj1.staticVar = 10; // ⚠️ Works but is misleading — avoid this style15. Best Practices
- Use the most appropriate data type. Don't use
longwhenintsuffices. Don't usedoublewhen you only need an integer.
- Always use
BigDecimalfor money and precise decimals. Neverfloatordouble.
- Follow camelCase for variable names and ALL_CAPS for constants.
- Initialize local variables immediately upon declaration to avoid accidentally using uninitialized values.
- Access static variables using the class name, not through object references, for clarity.
- Prefer
intoverbyteorshortfor general integers — the JVM often promotes them anyway, andintis more readable.
- Use meaningful variable names.
customerAgeis better thanaorx.
- Declare each variable on its own line for readability:
1 // ❌ Hard to read2 int a = 1, b = 2, c = 3;3
4 // ✅ Easier to maintain5 int a = 1;6 int b = 2;7 int c = 3;- Mark truly constant values with
static finaland name them in ALL_CAPS.
16. Interview Notes
Most Frequently Asked Questions
Q1: Is Java statically typed or dynamically typed? A: Java is statically typed — all variable types must be declared at compile time.
Q2: Is Java strongly typed or weakly typed? A: Java is strongly typed — each data type has a defined range, and you cannot implicitly assign a value outside that range.
Q3: How many primitive types does Java have? Name them. A: 8 — byte, short, int, long, float, double, char, boolean.
Q4: What is the default value of int, boolean, char? A: int → 0, boolean → false, char → '\u0000'.
Q5: Do local variables get default values? A: No. Only instance (member) and static variables get default values.
Q6: What is widening conversion? A: Automatic conversion from a smaller to a larger data type with no data loss.
Q7: What is narrowing conversion? A: Explicit (manual) cast from a larger to a smaller data type, with possible data loss.
Q8: What is promotion during expressions? A: Java automatically promotes byte and short to int in arithmetic expressions. If any operand is double, the whole expression becomes double.
Q9: Why should we not use float/double for currency? A: IEEE 754 binary floating-point cannot represent many decimal fractions exactly, leading to rounding errors. Use BigDecimal for precise decimal arithmetic.
Q10: What is two's complement? A: The method Java uses to represent negative integers in binary. To find two's complement: flip all bits (one's complement) and add 1.
Q11: What is the range of byte? A: −128 to 127. (8 bits, signed two's complement)
Q12: What happens when a byte overflows? A: It wraps around. 127 + 1 in a byte becomes −128.
Q13: What is the difference between member variables and static variables? A: Member variables — each object gets its own copy. Static variables — one copy shared by the entire class.
Q14: Can a variable name start with a digit in Java? A: No. Variable names must start with a letter, $, or _.
Q15: What is char's range and why? A: 0 to 65,535. It is 2 bytes (16 bits) and unsigned (no negative values), designed to hold Unicode characters.
17. Practice Questions
Easy
- Declare a variable of type
intnamedscoreand assign it the value100. Print it. - What is the output of
System.out.println((char) 65);? - Declare a
booleanvariableisActiveand set it totrue. - What is the default value of a
doublemember variable? - Which is larger:
intorlong?
Medium
- What is the output of the following code?
1 byte a = 127;2 byte b = 1;3 int c = a + b;4 System.out.println(c);- Predict the output:
1 int x = 128;2 byte y = (byte) x;3 System.out.println(y);- Why does the following code not compile?
1 float f = 3.14;How do you fix it?
- What is the output?
1 float a = 0.1f;2 float b = 0.2f;3 System.out.println(a + b);- Write code that demonstrates that two objects of a class have independent member variables but share a static variable.
Hard
- Explain why the range of
byteis −128 to 127 (not 0 to 255) using two's complement.
- Given a
bytevalue of200(which is outside byte's range), what value will be stored afterbyte b = (byte) 200? Show your working.
- Will the following compile? Explain:
1 byte x = 10;2 byte y = 20;3 byte z = x + y;- Explain the difference between
float f = 3.14fanddouble d = 3.14. Which is more precise, and why?
- Write a program using
BigDecimalthat correctly computes0.1 + 0.2and verify it equals0.3.
18. Summary Cheat Sheet
1┌─────────────────────────────────────────────────────────────────────────────┐2│ JAVA VARIABLES — QUICK SUMMARY │3├─────────────────────────────────────────────────────────────────────────────┤4│ Variable = named memory container holding a typed value │5│ Syntax: dataType variableName = value; │6├──────────────────────────┬──────────────────────────────────────────────────┤7│ JAVA TYPE SYSTEM │ Static: type declared at compile time │8│ │ Strong: each type has a range; enforced strictly│9├──────────────────────────┴──────────────────────────────────────────────────┤10│ 8 PRIMITIVE TYPES │11│ Integral: char(2B) | byte(1B) | short(2B) | int(4B) | long(8B) │12│ Floating: float(4B, IEEE754) | double(8B, IEEE754) │13│ Boolean: boolean — true / false │14├─────────────────────────────────────────────────────────────────────────────┤15│ NAMING RULES │16│ ✓ Case-sensitive ✓ Unicode letters/digits/$/_ │17│ ✓ Cannot start with digit ✗ No reserved words │18│ Convention: camelCase (vars), ALL_CAPS (constants) │19├─────────────────────────────────────────────────────────────────────────────┤20│ DEFAULT VALUES (member & static variables only) │21│ int/byte/short/long → 0 float/double → 0.0 │22│ char → '\u0000' boolean → false Object → null │23├─────────────────────────────────────────────────────────────────────────────┤24│ TYPE CONVERSION │25│ Widening (small→large): automatic — no data loss │26│ Narrowing (large→small): manual cast — possible overflow │27│ Promotion (expressions): byte/short→int; largest type wins │28├─────────────────────────────────────────────────────────────────────────────┤29│ KINDS OF VARIABLES │30│ Member — per object, has default value │31│ Static — per class, shared, has default value │32│ Local — inside method, NO default, must initialize │33│ Parameter — receives value from caller (method or constructor) │34├─────────────────────────────────────────────────────────────────────────────┤35│ ⚠️ FLOAT/DOUBLE WARNING │36│ IEEE 754 cannot represent all decimals exactly │37│ 0.3f - 0.1f = 0.20000002 ← WRONG for currency! │38│ USE BigDecimal for money and precise decimals │39└─────────────────────────────────────────────────────────────────────────────┘End of Chapter — Java Variables
Next Topics: Non-Primitive / Reference Types · Wrapper Classes ·finalkeyword · Arrays
Practice & Implement
Apply what you learned in Variables & Primitive Types
Declare an `int` with value 2147483647 (Integer.MAX_VALUE). Add 1 to it and print the result — observe integer overflow. Then use a `long` to hold the correct value and print it.
-2147483648 2147483648
Mastery check
How well can you recall this?
Finished this lesson?