FB : Gamma Maths style
COMPREHENSIVE JAVA NOTES
1. Introduction to Java
Definition: Let Java be a high-level, object-oriented programming language developed by Sun
Microsystems (now Oracle). It follows the core principle of "Write Once, Run Anywhere" (WORA).
Key Features Matrix:
• Platform independent (JVM): Code compiled on one platform runs seamlessly on any machine.
• Object-oriented: Modeled entirely around real-world data and reusable modular elements.
• Robust: Safe structures featuring highly proactive memory checks and built-in exception blocks.
• Secure: Devoid of raw pointer usage, fully verifying incoming compilation segments via bytecode
guards.
• Multi-threaded: Executes multi-process instructions concurrently over matching pipelines.
• Automatic garbage collection: Continuously manages system lifecycles automatically.
2. Java Execution Process
Step-by-step Execution Blueprint:
Pipeline Architecture
1. Source code is authored inside standard .java files. Source ( .java )
2. The native compiler engine ( javac ) translates data ↓
pathways into bytecode blocks ( .class ). Compiler ( javac )
3. JVM interprets or compiles bytecode configurations ↓
natively. Bytecode ( .class )
4. Dynamic native operations run efficiently across targeted ↓
hardware configurations. JVM Operations
↓
Target Platform OS
3. Variables & Declarations
Definition: A named, explicitly partitioned block of memory allocated to handle structural values
susceptible to dynamic alterations during standard execution phases.
Comprehensive Java Study Guide 1
3.1 Variable Declaration & Initialization
// Declaration Examples
int age;
String name;
// Declaration + Initialization Block
int score = 100;
double pi = 3.14159;
char grade = 'A';
boolean isActive = true;
3.2 Naming Rules (Identifiers)
• Allowed properties encompass valid alphanumeric values, underscores _ , or currency markers $ .
• Must NOT initiate with numeric variables.
• Highly case-sensitive bounds (e.g., total ≠ Total ).
• Strictly reserved framework key phrases cannot be substituted as functional handles.
• Requires standard camelCase signatures (e.g., studentName , totalMarks ).
3.3 Types of Variables (by scope)
Memory Allocation
Type Scope Location Default Value Allocation
Area
No default (Must initialize before
Local Inside explicit method / code block Stack
read)
Inside enclosing class, outside
Instance Yes (0, null, false constants) Heap
methods
Class level definition (Shared
Static Yes (0, null, false constants) Method area
uniformly)
public class VariableDemo {
static int staticVar = 100; // static variable
int instanceVar; // instance variable (default 0)
public void show() {
int localVar = 50; // local variable (must initialize)
[Link](localVar);
}
}
3.4 Type Casting Mechanisms
// Implicit (widening conversion) – execution is completely automatic
int a = 10;
double b = a; // Conversions: int → double (10.0)
// Explicit (narrowing conversion) – manual definition required
double x = 9.78;
int y = (int) x; // Conversions: double → int (9)
Comprehensive Java Study Guide 2
4. Data Types Matrix
Definition: Specifications defining structural resource boundaries, dimensions, and standard
value limits acceptable inside target storage scopes.
4.1 Primitive Data Types (8 Base Implementations)
Type Memory Footprint Acceptable Value Ranges Code Syntax Sample
byte 1 byte -128 to 127 byte b = 100;
short 2 bytes -32,768 to 32,767 short s = 5000;
int 4 bytes -2³¹ to 2³¹-1 int i = 100000;
long 8 bytes -2⁶³ to 2⁶³-1 long l = 100000L;
float 4 bytes ±3.4e-38 to ±3.4e+38 float f = 3.14f;
double 8 bytes ±1.7e-308 to ±1.7e+308 double d = 3.14159;
char 2 bytes 0 to 65,535 (Unicode encoding) char c = 'A';
boolean 1 bit true or false literal values boolean flag = true;
// Primitive Declarations Example
byte a = 120;
short b = 30000;
int c = 2_000_000; // Underlines optimize visual scanning layout
long d = 9876543210L; // Requires trailing L token
float e = 12.5f; // Requires explicit f indicator flag
double f = 45.678;
char g = 'Z';
boolean h = false;
4.2 Reference Data Types
• String: An immutable sequence string block storing specific text arrays.
• Arrays: Homogeneous groupings keeping linear components bounded together.
• Classes: Custom object structural definitions.
• Interfaces: Decoupled abstraction blueprints detailing contractual interfaces.
String msg = "Hello Java";
int[] numbers = {1, 2, 3};
Student s1 = new Student(); // instantiation mapping a reference point
5. Operators Breakdown
Definition: Functional structural symbols designed to compute data across one, two, or three
sequential variable expressions.
Comprehensive Java Study Guide 3
5.1 Arithmetic & 5.2 Relational Blocks
Op Meaning Example Pattern Op Relational Result Status
+ Addition 10 + 3 = 13 == Equal to 5 == 5 → true
- Subtraction 10 - 3 = 7 != Not equal 5 != 3 → true
* Multiplication 10 * 3 = 30 > Greater than 10 > 5 → true
/ Division 10 / 3 = 3 (int) < Less than 3 < 7 → true
% Modulus 10 % 3 = 1 >= Greater or equal 8 >= 8 → true
<= Less or equal 4 <= 6 → true
// Code Evaluations Sample
int a = 15, b = 4;
[Link](a + b); // Output: 19
[Link](a / b); // Output: 3 (Truncated via integer operations)
int x = 10, y = 20;
[Link](x == y); // Output: false
[Link](x < y); // Output: true
5.3 Logical & 5.4 Assignment Expressions
Operator Meaning / Structural Mapping Example Statement Context
&& Logical AND (Short-circuit optimization evaluated) (true && false) → false
|| Logical OR (Short-circuit optimization evaluated) (true || false) → true
! Logical NOT inversion mechanics !true → false
+= , -= Compound functional value modifiers x += 3 ⇒ x = x + 3
*= , /= Compound scaling assignments x *= 4 ⇒ x = x * 4
5.5 Unary & 5.6 Ternary Implementations
// Unary Increments
int p = 5;
[Link](p++); // Prints base value 5, updates container state to 6
[Link](++p); // Upgrades context state to 7, prints out 7 directly
// Ternary Inline Assignments
condition ? expression1 : expression2
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor"; // Evaluations output: "Adult"
Comprehensive Java Study Guide 4
5.7 Bitwise Operators & 5.8 instanceof Check
int bitA = 5; // Binary footprint: 0101
int bitB = 3; // Binary footprint: 0011
[Link](bitA & bitB); // 1 (Bitwise AND outputs: 0001)
[Link](bitA | bitB); // 7 (Bitwise OR outputs: 0111)
[Link](bitA << 1); // 10 (Bitwise Left Shift multiply behavior)
String text = "Hello";
[Link](text instanceof String); // Validates type hierarchy structure: true
5.9 Precedence Evaluation Hierarchy
Precedence Rank Target Logic Operators
1 (Highest Priority) ++ -- + - (unary) ! ~
2 * / %
3 + -
4 << >> >>>
5 < > <= >= instanceof
6 == !=
10 &&
11 ||
12 ? :
13 (Lowest Priority) = += -= *= /= %=
6 & 7. Conditional Flows & Iterative Loops
Definition: Logical flow mechanisms restricting execution paths until custom runtime
prerequisites are met.
6. If/Else Branches Syntax: Practical Example:
if (condition) { int marks = 85;
// block if (marks >= 90) {
} else if (condition2) { [Link]("Grade
// block A");
} else { } else if (marks >= 75) {
// block [Link]("Grade
} B"); // Triggers
} else {
[Link]("Grade
C");
}
Comprehensive Java Study Guide 5
7. Loop Mechanics (for, while, do-while)
// 7.1 standard for loop configuration (Utilized when iteration limits are known upfront)
for (int i = 0; i < 5; i++) {
[Link]("Iteration: " + i);
}
// 7.2 baseline while loop configuration (Evaluates conditions prior to code blocks)
int iw = 0;
while (iw < 5) {
[Link](iw);
iw++;
}
// 7.3 do-while loop structure (Guarantees execution runs at least once)
int id = 0;
do {
[Link](id);
id++;
} while (id < 5);
Loop Exercise - Summation of Initial 10 Digits:
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
[Link]("Sum: " + sum); // Computes mathematical totals layout: 55
8 & 9. Arrays & Modularity Frameworks
8. Array Definition: A static storage container holding sequence configurations of matching
reference variables or primitives layout formats.
// Allocation Strategy Forms
int[] numbers = new int[5]; // Strategy 1
numbers[0] = 10;
int[] values = {1, 2, 3, 4, 5}; // Strategy 2
int[] arr = new int[]{10, 20, 30}; // Strategy 3
// Reading indices using standard loops versus enhanced loops
int[] scores = {95, 87, 92, 78, 88};
for (int s : scores) {
[Link](s); // Sequentially prints structural scores
}
9. Method Definition: Isolated segments wrapping custom routines designed to optimize
codebase reusability and operational modularity across pipelines.
Comprehensive Java Study Guide 6
public class MethodDemo {
// Accepts parameter models and hands back processed returns values
public static int add(int a, int b) {
return a + b;
}
// Void identifiers run instructions without output feedback
public static void greet(String name) {
[Link]("Hello, " + name);
}
public static void main(String[] args) {
int sum = add(5, 3);
[Link]("Sum: " + sum); // Out: 8
greet("Alice");
}
}
10 & 11. Object-Oriented Blueprint Foundations
Class Template: Abstract structural system blueprint mapping states and operational behaviors.
Object Instance: Isolated physical entities activated inside system heaps holding separate state
properties.
class Car { 11. Inheritance Layers
String brand; // State Metric
String color; Passes parameters downwards from base
int speed; parental definitions to explicit child
extensions.
void accelerate() { // Behavioral Blueprint
speed += 10;
Keyword Flag: extends
[Link](brand + " speed: " +
speed);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Spawning specific operational instance mappings
[Link] = "Toyota";
[Link] = "Red";
[Link](); // Output tracking logs: Toyota speed: 10
}
}
Comprehensive Java Study Guide 7
11. Inheritance Code Sample
class Animal {
void eat() { [Link]("This animal eats food"); }
}
class Dog extends Animal {
void bark() { [Link]("Dog barks"); }
}
// Execution block tracing
Dog myDog = new Dog();
[Link](); // Inherited logic executes seamlessly
[Link](); // Invokes local subclass methods directly
12 & 13. Advanced OOP Core Pillars
12. Polymorphism: Interface abstractions executing contextual implementation versions
depending on target runtime types bindings.
Compile-Time Polymorphism (Method Overloading)
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // Overloaded via altered parameters
signature
int add(int a, int b, int c) { return a + b + c; }
}
Runtime Polymorphism (Method Overriding)
class Animal {
void sound() { [Link]("Animal makes sound"); }
}
class Cat extends Animal {
@Override
void sound() { [Link]("Cat meows"); } // Specific overridden implementation
}
// Application framework
Animal a = new Cat();
[Link](); // Overridden context calls dispatch: "Cat meows" at execution phase
13. Encapsulation: Securing internal component logic boundaries by blinding fields behind private
modifiers, exposed carefully via public Accessor channels.
Comprehensive Java Study Guide 8
public class Person {
private String name; // Bounded internal variables state
private int age;
public String getName() { return name; } // Getter channel
public void setName(String name) { [Link] = name; } // Setter channel
public int getAge() { return age; }
public void setAge(int age) {
if (age > 0) { [Link] = age; } // Strategic state data validation checks embedded
}
}
14. Exception Handling Mechanics
Definition: System intercept paradigms built to catch runtime errors gracefully without causing
thread failures.
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // Generates structural ArithmeticException anomalies
[Link](result);
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!"); // Handles intercept safely
} finally {
[Link]("This block always executes"); // Cleanup blocks run
unconditionally
}
// Multiple Catch Configurations Sequence
try {
int[] arr = new int[2];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error encountered");
} catch (Exception e) {
[Link]("Fallback safety general block invoked");
}
}
}
Checked vs Unchecked Classifications
• Checked Exceptions: Structural blocks validated during compilation phases (e.g., IOException ,
SQLException ). Failure to capture or propagate terminates compilation.
• Unchecked Exceptions: Real-time operations glitches tracked strictly during processing lifecycles
(e.g., NullPointerException , ArithmeticException ).
Comprehensive Java Study Guide 9
Explicit Assertions Tracking ( throw and throws )
void validateAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative"); // Disrupts linear
execution tracking
}
}
15. Complete Integrated Architecture Blueprint
This comprehensive sandbox consolidates all definitions covered across previous sections into one clean
execution compilation script.
Comprehensive Java Study Guide 10
public class CompleteDemo {
// 3.3 Static & Private Instance Fields Layout Setup
static int studentCount = 0;
private String name;
private int[] marks;
// Constructor Model Initialization Mapping
public CompleteDemo(String name, int[] marks) {
[Link] = name;
[Link] = marks;
studentCount++; // Tracking total allocation counts
}
// Method processing custom loops blocks
public double calculateAverage() {
int sum = 0;
for (int m : marks) {
sum += m; // Accumulation routine
}
return (double) sum / [Link]; // Explicit Type Casting evaluation
}
// Encapsulation Accessor Port
public String getName() {
return name;
}
public static void main(String[] args) {
// Initializing raw structural array containers
int[] scores = {85, 90, 78, 92};
// Activating object targets references over structural heaps
CompleteDemo student = new CompleteDemo("Alice", scores);
// Structured exception interception logic
try {
double avg = [Link]();
[Link]([Link]() + "'s average: " + avg);
// Ternary flow computation routing
String result = (avg >= 85) ? "Excellent" : "Good";
[Link]("Performance: " + result);
} catch (Exception e) {
[Link]("Error detected: " + [Link]());
} finally {
[Link]("Total students: " + studentCount);
}
}
}
Standard System Trace Output Logs:
Comprehensive Java Study Guide 11
Alice's average: 86.25
Performance: Excellent
Total students: 1
Hence, Java successfully combines structural platform independence, strict compile safety
matrices, and intuitive object paradigms!
Comprehensive Java Study Guide 12