Java Notes
Java Notes
Introduction
This comprehensive guide covers the fundamental concepts of programming
languages, with a focus on Java. Understanding these concepts is crucial for:
• Data Structures and Algorithms
• Software Development
• Technical Interviews
• Memory Management
• Object-Oriented Programming
Core Concepts Covered:
• How computers work internally (binary)
• Different types of programming languages
• Memory management (Stack vs Heap)
• Objects and reference variables
• Garbage collection
Types of Languages
Procedural Languages
De nition:
Speci es a series of well-structured steps and procedures to compose a program.
Characteristics:
• Contains an ordered sequence of statements, functions, and commands
• Follows a step-by-step approach to complete tasks
• Uses loops, statements, cases, and functions
Example Flow:
Step 1: Input first number
Step 2: Input second number
Step 3: Add the two numbers
Step 4: Print the result
Visual Representation:
Input Number 1 Input Number 2 Calculate Sum Print Result
Functional Languages
De nition:
Writing programs using pure functions only.
Key Concepts:
What are Functions?
fi
fi
fi
→
→
→
→
→
• Bundle of code that can be reused multiple times
• Saves time and effort
• Easy to maintain and debug
Example Scenario:
Problem: Need to add two numbers in 10 different files
Solution: Write the function once, use it 10 times
Benefit: If there's an error, fix it in one place
Use Cases:
• Machine Learning: Operating on datasets without modifying original data
• Data Processing: Performing multiple operations on the same dataset
• Mathematical Computations: Where data integrity is crucial
Languages that Support Functional Programming:
• Python ✅ (has rst-class functions, not purely functional)
Object-Oriented Languages
De nition:
Programming paradigm that revolves around objects.
What is an Object?
fi
fi
An object combines:
• Code (methods/functions)
• Data (properties/attributes)
Real-World Example:
Problem: Create a collection of student data where each student has:
• Name (String)
• Roll Number (Integer)
• Marks (Float/Decimal)
Question: What data type can store all these different types
together? Answer: A custom data type created using classes!
Classes vs Objects:
Class Object
Class Example:
class Student {
// Properties
String name;
int rollNumber;
float marks;
// Methods (functions)
void displayInfo() {
// Display student information
}
}
Object Example:
// Creating objects (instances) of Student class
Student kunal = new Student(); // Object 1
Student rahul = new Student(); // Object 2
fi
fi
Bene ts of Object-Oriented Programming:
1. Modularity: Divide code into chunks
2. Easy to Debug: Fix speci c parts without affecting others
3. Reusability: Use same code in multiple places
4. Maintainability: Easy to update and modify
Real-World Analogy - Car Example:
Car Program Components:
- Engine (separate code base)
- Steering (separate code base)
- Wheels (separate code base)
Key Question: How does the programming language know what type these variables
are?
Static Languages
Characteristics:
• Type checking at compile time
• Must declare data types before use
• More control over types
• Compile-time error detection
What is Compile Time?
The process of converting source code → machine code
Example:
// Static typing - must specify type
int a = 10; // ✅ Correct
Memory Representation:
Compile Time Runtime
┌
─
─
─
─
─
─
─
fi
─
─
─
─
─
─
┐
┌
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
int a 10
(type check) (actual
value)
Error Detection:
int a = 10;
a = "Kunal"; // ❌ Compile-time error
// Error: Cannot assign string to integer variable
Advantages:
• ✅ More control over data types
• ✅ Reduced runtime errors
• ✅ Better performance
• ✅ Early error detection
Disadvantages:
• ❌ More code to write
• ❌ Less exibility
Examples of Static Languages:
• Java
• C++
• C#
Dynamic Languages
Characteristics:
• Type checking at runtime
• No need to declare data types
• More exibility
• Runtime error detection
What is Runtime?
When the program is actually running (after compilation)
Example:
# Dynamic typing - no type declaration needed
a = 10 # a is integer
│
│
└
─
─
─
─
fl
─
─
fl
─
─
─
─
─
─
─
│
│
┘
→
│
│
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
│
│
│
┘
a = "Kunal" # a is now string - No error!
a = 13.5 # a is now float - Still no error!
Why No Error?
a = 10 # 'a' points to integer object 10
a = "Kunal" # 'a' now points to string object "Kunal"
# Previous object (10) becomes eligible for garbage
collection
Error Detection:
a = "Kunal"
result = a + 10 # ❌ Runtime error
# Error: Cannot add string and integer
Advantages:
• ✅ Less code to write
• ✅ More exibility
• ✅ Faster development
Disadvantages:
• ❌ Runtime errors possible
• ❌ Less control over types
• ❌ Potential performance overhead
Examples of Dynamic Languages:
• Python
• JavaScript
• Ruby
Summary Table:
Memory Management
Understanding how programs store and manage data in computer memory.
Stack and Heap Memory
Two Types of Memory:
1. Stack Memory
2. Heap Memory
Computer Memory
Stack Memory
(Reference Variables)
Heap Memory
(Actual Objects)
a 10
(reference) (object)
How It Works:
1. Reference variable a is created in Stack memory
2. Object 10 is created in Heap memory
3. a points to the memory address where 10 is stored
4. When you access a, it follows the pointer to get the value 10
"Kunal"
My Body
"Son" (Physical
Object)
"Brother"
"Baby"
Key Insights:
1. Multiple names can refer to the same person
2. If any name makes a change (like getting a haircut), all names see that change
3. There's only one physical object (my body), not separate bodies for each name
Programming Example:
┌
│
│
└
┌
│
├
│
├
│
├
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
┼
│
┘
┐
│
┤
│
┤
│
┤
│
┘
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
→
┐
│
┼
│
┤
│
┘
─
┌
│
│
└
─
─
─
─
─
─
→
─
─
─
─
─
─
→
─
─
─
─
┌
│
│
│
│
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
│
│
┘
─
─
─
─
─
─
─
─
─
─
─
─
┐
│
│
│
│
│
┘
// Creating objects and references
int a = 10;
int b = 37;
Memory Visualization:
Stack Memory Heap Memory
a 10
c 10 (same object)
b 37
Memory Diagram:
Stack Memory Heap Memory
list1 [99, 3, 5, 9]
(List Object)
┌
│
├
│
├
│
└
┌
│
├
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
┼
┤
┼
┤
┼
┘
┐
┼
┤
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
→
→
→
┐
│
┌
│
├
│
├
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┌
│
│
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
│
┤
│
┤
│
┘
─
─
─
─
─
─
─
─
┐
│
│
list2
Garbage Collection
What is Garbage Collection?
Automatic memory management system that removes unused objects from memory.
When Objects Become "Garbage":
Scenario: The Lost Reference
Person kunal = new Person("Kunal");
Person baby = kunal; // Both point to same object
Memory Visualization:
Before:
Stack Memory Heap Memory
Key Takeaways
1. Programming Language Fundamentals
• Purpose: Convert human-readable code to machine code (binary)
• Types: Procedural, Functional, Object-Oriented
• Flexibility: Languages can support multiple paradigms
2. Static vs Dynamic Languages
Static (Java, C++):
- Type checking at compile time
- Must declare types
- More control, fewer runtime errors
3. Memory Management
Stack Memory: Heap Memory:
- Reference Variables - Actual Objects
- Function Calls - Object Data
- Local Variables - Arrays, Objects
Practice Exercises
Exercise 1: Identify Language Types
Classify these languages by their supported paradigms:
• Java
• Python
• C++
• JavaScript
Exercise 2: Memory Management
Draw memory diagrams for:
int x = 5;
int y = x;
x = 10;
// What are the values of x and y?
╱ ╲ ← Input/Output operations
╱ Parallelgram ╲
╱_______________╲
Rectangle ← Processing/Calculations
(Processing)
START
INPUT
Name
OUTPUT
"Hello"+
Name
STOP
Step-by-Step Process:
1. Start the program
2. Input name from user
3. Process concatenate "Hello" with name
4. Output the greeting message
5. Stop the program
START
┌
│
└
┌
│
│
└
┌
│
│
│
└
┌
│
└
┌
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
↓
─
─
↓
─
─
↓
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
│
┘
┐
│
│
┘
┐
│
│
│
┘
┐
│
┘
┐
│
┘
┌
│
│
└
┌
│
│
└
┌
│
│
│
└
┌
│
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
↓
─
─
↓
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
│
↓
─
─
│
└
─
─
─
─
┌
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
│
│
┘
┐
│
│
┘
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
╱
┬
↓
─
─
↓
─
─
↓
─
─
┌
│
│
└
─
─
─
─
─
─
─
╱╲
─
─
─
─
─
─
─
─
─
╲
─
─
─
─
─
─
─
─
─
1500
INPUT
─
─
─
─
─
─
─
┐
─
Salary
─
─
─
┐
│
│
│
┘
┐
│
│
┘
─
Bonus =
╱Salary╲
─
─
─
─
╱ > 10000╲
↓
─
─
│
─
│
┐
Salary
Bonus
No
╱__________╲
─
─
│
┘
OUTPUT New
─
─
─
─
Old Salary +
New Salary =
┐
│
│
┘
Yes
2000
Bonus =
STOP
Logic Flow:
1. Start program
2. Input salary from user
3. Check condition: Is salary > 10000?
◦ If Yes: Bonus = 2000
◦ If No: Bonus = 1500
4. Calculate: New Salary = Old Salary + Bonus
5. Output the new salary
6. Stop program
START
INPUT
Number
i = 2
╱╲
┌
│
└
┌
│
│
└
┌
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
↓
─
─
↓
─
─
↓
─
─
─
─
─
─
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
fi
─
┐
│
┘
┐
│
│
┘
┐
│
┘
─
─
─
─
─
─
│
┘
╱ ╲
╱ i < ╲ No
╱ Number╲
╱_________╲
Yes
╱╲ OUTPUT
╱ ╲ "Prime"
╱Number╲ No
╱ % i ==0╲
╱__________╲
Yes
OUTPUT
"Not Prime"
STOP
Pseudocode
What is Pseudocode?
Pseudocode is a way to write algorithms using:
• Plain English (or any natural language)
┌
│
│
└
─
─
─
─
─
─
─
─
─
─
│
↓
│
↓
─
─
│
└
─
─
─
─
─
─
┌
│
└
─
─
─
─
─
┐
│
┘
─
─
─
─
─
─
│
─
─
─
─
─
─
─
─
─
┬
↓
─
─
─
─
─
─
─
─
─
┌
─
─
─
─
│
│
└
─
─
─
─
─
─
─
─
─
─
┐
│
┘
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
↓
─
│
│
│
│
│
│
│
┘
│
┐
─
│
┐
─
─
─
─
─
─
┐
│
│
┘
• Programming-like structure
• No speci c syntax requirements
Bene ts:
• ✅ Language independent - Can be understood by anyone
• ✅ Easy to write - No syntax restrictions
• ✅ Clear logic - Focus on algorithm, not syntax
• ✅ Communication tool - Share ideas with non-programmers
Pseudocode Examples
Question 3: Prime Number Checker (Basic Method)
BEGIN
START program
INPUT number
SET i = 2
OUTPUT "Prime"
STOP
END
OUTPUT "Prime"
STOP
END
INPUT salary
STOP
END
Key Programming Concepts
1. Modulo Operator (%)
The modulo operator returns the remainder of division:
Examples:
7 % 2 = 1 (7 ÷ 2 = 3 remainder 1)
8 % 3 = 2 (8 ÷ 3 = 2 remainder 2)
9 % 3 = 0 (9 ÷ 3 = 3 remainder 0)
If-Else Structure:
IF condition THEN
// statements for true case
ELSE
// statements for false case
END IF
3. Algorithm Optimization
Time Complexity Comparison:
Basic Prime Check:
• Time Complexity: O(n)
• Steps for number 1000: ~998 checks
Optimized Prime Check (√n method):
• Time Complexity: O(√n)
• Steps for number 1000: ~31 checks
Example: Checking if 36 is Prime
Basic Method: Check 2, 3, 4, 5, 6, 7, 8, 9, 10... 35
Optimized Method: Check 2, 3, 4, 5, 6 (√36 = 6)
Practice Problems
Problem 1: Even/Odd Checker
Create a owchart and pseudocode to check if a number is even or odd.
Hint: Use modulo operator with 2
Problem 2: Grade Calculator
Create a owchart for grade calculation:
• Score ≥ 90: Grade A
• Score ≥ 80: Grade B
• Score ≥ 70: Grade C
• Score < 70: Grade F
Problem 3: Factorial Calculator
Create a owchart to calculate factorial of a number.
Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
Problem 4: Number Pattern
Create a owchart to print numbers from 1 to n.
How It Works:
1. Source Code: Written in .java les
2. Compilation: javac creates .class les with bytecode
3. Distribution: Share .class les (not source code)
4. Execution: Run on any system with JVM installed
Platform Independence Comparison:
JDK
JRE
JVM
Steps:
1. Loading: Read .class le from storage
2. Veri cation: Check bytecode validity and security
3. Preparation: Allocate memory for static variables
4. Resolution: Replace symbolic references with direct references
5. Initialization: Execute static blocks and initialize static variables
2. Memory Areas
Stack Memory:
• Function calls and local variables
• Reference variables (pointers to objects)
• Created per thread
• LIFO (Last In, First Out) structure
Heap Memory:
• Objects and instance variables
• Shared among all threads
• Garbage collection happens here
3. Execution Engine
Components:
• Interpreter: Executes bytecode line by line
fi
fi
→
fi
fi
→
fi
• JIT Compiler: Optimizes frequently used code
• Garbage Collector: Removes unused objects
Memory Representation:
Stack Memory Heap Memory
Human Object
name="Jane"
Static Memory
population
= 7000000000 ← Shared by all
┌
│
├
│
└
─
─
─
─
─
─
fi
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
┼
┤
┼
┘
─
─
─
─
─
─
─
─
→
┐
│
└
┌
│
│
└
→
─
─
┌
│
│
└
┌
│
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
│
│
┘
─
─
─
─
┐
│
│
┘
┐
│
│
┘
Key Insight: Population is the same for all humans, regardless of individual differences.
Garbage Collection
Memory Management in Java
What is Garbage Collection?
Automatic process that reclaims memory by removing objects that are no longer
referenced.
When Objects Become Garbage:
// Creating objects
String greeting = "Hello";
String name = "World";
2. Compile (javac)
↓
↓
fi
fl
3. Generate Bytecode (.class)
7. Execute on Hardware
8. Display Output
Compon
Full Form Purpose Contains
ent
↓
↓
↓
↓
↓
fi
fi
fi
Java Development Development + JRE + Development
JDK
Kit Execution Tools
Java Runtime
JRE Execution Only JVM + Libraries
Environment
Compilation vs Interpretation
Execution Steps:
1. Compile: javac HelloWorld.java → HelloWorld.class
2. Load: Class Loader loads HelloWorld.class
3. Verify: JVM veri es bytecode integrity
4. Execute: JIT compiles main method
5. Output: "Hello, World!" displayed
2. Calculator Application
// Calculator.java
public class Calculator {
public static int add(int a, int b) {
return a + b; // Frequently called - JIT optimized
}
}
JIT Optimization:
• First few calls: Interpreted line by line
• After threshold: Compiled to machine code
• Subsequent calls: Execute optimized machine code
// Class declaration
public class Main {
// Main method - entry point of program
public static void main(String[] args) {
// Your code here
System.out.println("Hello World!");
}
}
Key Rules:
1. File name must match public class name
2. One public class per le
3. Main method required to run the program
4. Case sensitive - Main ≠ main
2. static Keyword
Meaning: Belongs to class, not to individual objects
public class Human {
static int population = 7000000000; // Shared by all humans
Why main is static: Program needs to start without creating objects rst.
3. void Keyword
Meaning: Method returns nothing
public static void printMessage() {
System.out.println("Hello");
// No return statement needed
}
Breakdown:
• System = Class containing system-related functionality
• out = PrintStream object for standard output
• println() = Method to print with new line
Input - Scanner Class
import java.util.Scanner;
// Integer input
System.out.print("Enter your age: ");
int age = input.nextInt();
// String input
System.out.print("Enter your name: ");
String name = input.nextLine();
// Float input
System.out.print("Enter your marks: ");
float marks = input.nextFloat();
float
nextFloat() Float
price = input.nextFloat();
nextDouble( double
Double
) salary = input.nextDouble();
String (single
next() String word = input.next();
word)
nextBoolean boolean
Boolean
() flag = input.nextBoolean();
2
short -32,768 to 32,767 short year = 2024;
bytes
4
int -2.1B to 2.1B int population = 1000000;
bytes
8 long
long Very large numbers
bytes distance = 123456789L;
4
float Decimal numbers float price = 99.99f;
bytes
8 Large decimal
double double salary = 50000.50;
bytes numbers
Examples:
public class DataTypesExample {
public static void main(String[] args) {
// Integer types
byte temperature = 30;
int rollNumber = 12345;
long phoneNumber = 9876543210L; // Note: L suffix for
long
Examples:
public class TypeCastingExample {
public static void main(String[] args) {
// Automatic conversion
int a = 100;
→
→
→
→
→
→
→
→
→
→
→
→
float b = a; // int float
System.out.println(b); // 100.0
// Explicit casting
double salary = 50000.75;
int basicSalary = (int) salary; // double int
System.out.println(basicSalary); // 50000
float x = 10.5f;
int y = 5;
float result = x + y; // y promoted to float
Control Statements
1. Conditional Statements
→
→
If Statement:
int age = 18;
If-Else Statement:
int marks = 75;
If-Else-If Ladder:
int score = 85;
2. Loop Statements
While Loop:
Syntax:
while (condition) {
// code to repeat
// update condition
}
Example:
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++; // Increment count
}
// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5
For Loop:
Syntax:
for (initialization; condition; increment/decrement) {
// code to repeat
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
// Same output as while loop above
while You don't know how many times loop will run
Examples:
// for loop - known iterations
for (int i = 1; i <= 10; i++) {
System.out.println(i * 2); // Print even numbers
}
Practical Examples
1. Sum of Two Numbers:
import java.util.Scanner;
2. Temperature Conversion:
import java.util.Scanner;
3. Grade Calculator:
import java.util.Scanner;
4. Number Pattern:
public class NumberPattern {
public static void main(String[] args) {
// Print numbers 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
System.out.println(); // New line
Comments in Java
Types of Comments:
// Single line comment
/*
Multi-line comment
Can span multiple lines
*/
/**
* Documentation comment
* Used for generating documentation
*/
public class CommentsExample {
public static void main(String[] args) {
System.out.println("Hello"); // This prints hello
/*
* This is a block comment
* explaining the next line
*/
int x = 10;
}
}
// Invalid identifiers
// int 2age; // Cannot start with digit
// int roll-number; // Hyphen not allowed
// int class; // 'class' is reserved keyword
Key Takeaways
1. Java Program Structure:
• Every program needs a main method
• File name must match public class name
• Case-sensitive language
2. Data Types:
स्ते
• 8 primitive types: byte, short, int, long, oat, double, char, boolean
• Choose appropriate type based on data size and precision needs
3. Type Conversion:
• Automatic: smaller → larger type
• Manual casting: larger → smaller type (data loss possible)
• Expression promotion: smaller types promoted to int or larger
4. Input/Output:
• System.out.println() for output
• Scanner class for input
• Different methods for different data types
5. Control Statements:
• if-else: Decision making
• for loop: Known iterations
• while loop: Unknown iterations
6. Best Practices:
• Use meaningful variable names
• Add comments for clarity
• Follow Java naming conventions
• Handle type conversion carefully
Note: These foundational concepts are crucial for understanding Java and object-
oriented programming. Take time to understand memory management and object
references, as they form the basis for advanced Java concepts. Master owcharts and
pseudocode as they are essential tools for planning and communicating algorithms
effectively. Understanding how Java executes code internally will help you write more
ef cient programs and debug issues effectively. Practice these basic concepts with
simple programs before moving to advanced topics like OOP, collections, and exception
handling.
FUNCTIONS
Introduction to Functions
Functions (also called Methods in Java) are fundamental building blocks of
programming that help us organize code ef ciently and avoid repetition.
Key Bene ts:
• ✅ Code Reusability - Write once, use multiple times
fi
fi
fl
fi
fl
• ✅ Better Organization - Break large problems into smaller parts
• ✅ Easy Maintenance - Fix bugs in one place
• ✅ Reduced Code Duplication - DRY (Don't Repeat Yourself) principle
// Place 2
int a2 = 10, b2 = 20;
int sum2 = a2 + b2;
System.out.println(sum2);
Problems:
• ❌ Code repetition - Same logic written multiple times
• ❌ Hard to maintain - If logic changes, update 10 places
• ❌ Error-prone - Easy to make mistakes while copying
• ❌ Large le size - Unnecessary code bloat
Solution With Functions:
public class Calculator {
public static void main(String[] args) {
// Use function multiple times
System.out.println(sum(5, 3)); // Place 1
System.out.println(sum(10, 20)); // Place 2
System.out.println(sum(15, 25)); // Place 3
// ... use anywhere needed
}
Bene ts:
• ✅ No repetition - Logic written once
• ✅ Easy to maintain - Change in one place
• ✅ Clean code - More readable and organized
• ✅ Reusable - Call from anywhere in the program
Syntax of a Method
fi
fi
Complete Method Structure:
access_modifier static/non-static return_type
method_name(parameter_list) {
// Method body
// Statements to execute
return value; // (if return type is not void)
}
Components Explained:
Simple Example:
public static int add(int a, int b) {
return a + b;
}
Breakdown:
• public: Can be accessed from anywhere
• static: Belongs to class, no object needed
• int: Returns an integer value
• add: Method name
• (int a, int b): Takes two integer parameters
• return a + b: Returns sum of a and b
fi
fi
Program Examples
Sum of Two Numbers
Problem Statement:
Create a function that takes two numbers as input and returns their sum.
import java.util.Scanner;
// Function definition
public static int sum(int a, int b) {
return a + b;
}
}
Output:
Enter first number: 15
Enter second number: 25
Sum = 40
Greetings Function
Example 1: Void Function (No Return Value)
public class GreetingExample {
public static void main(String[] args) {
// Calling greeting function
greetings();
greetings(); // Can call multiple times
}
Output:
Hello! Welcome to Java programming!
Hello! Welcome to Java programming!
Key Points:
• void means the function doesn't return any value
• Function just performs an action (printing)
• Can be called multiple times
Returning Values
Example 2: Function That Returns a Value
public class ReturnExample {
public static void main(String[] args) {
// Function call and storing returned value
int answer = sum(10, 20);
System.out.println("Answer: " + answer);
// Direct usage in print statement
System.out.println("Direct result: " + sum(5, 15));
}
Output:
Answer: 30
Direct result: 20
Important Concepts:
1. Return Statement: return keyword sends value back to caller
2. Function Call Value: When function is called, it "becomes" the returned value
3. Function Termination: return statement ends function execution
4. Unreachable Code: Any code after return statement won't execute
Example of Unreachable Code:
public static int badExample(int a, int b) {
return a + b;
System.out.println("This will never execute!"); // Error!
}
String Functions
Example: Function Returning String
public class StringFunctions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Output:
Enter your name: Kunal
Hello Kunal, how are you?
Key Points:
• Function can return any data type (String in this case)
• Return type must match the actual returned value
• String concatenation using + operator
// Parameters: a and b
public static int multiply(int a, int b) {
return a * b;
}
}
Return Types
Common Return Types:
// String return
public static String getFullName() {
return "John Doe";
}
// Boolean return
public static boolean isEven(int number) {
return number % 2 == 0;
}
// Double return
public static double calculatePrice(double cost, double tax)
{
return cost + (cost * tax / 100);
}
}
Memory Visualization:
Stack Memory (Function Calls):
Pass by Value
Important Concept: Java Always Passes by Value
Example 1: Primitive Data Types
public class PassByValueExample {
┌
│
│
│
└
┌
│
│
│
└
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
│
│
│
┘
┐
│
│
│
┘
public static void main(String[] args) {
int original = 10;
System.out.println("Before: " + original); // 10
changeValue(original);
System.out.println("After: " + original); // Still 10!
}
Output:
Before: 10
Inside function: 50
After: 10
Memory Explanation:
Stack Memory:
swap(a, b);
System.out.println("After swap: a=" + a + ", b=" + b);
}
Output:
Before swap: a=10, b=20
Inside function: x=20, y=10
After swap: a=10, b=20
changeName(name);
System.out.println("After: " + name);
}
Output:
Before: Kunal
Inside function: Rahul
After: Kunal
main():
"Kunal" ← name
changeName():
┌
│
└
┌
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
─
┐
│
┘
┐
─
─
─
─
─
─
─
─
─
─
─
"Rahul" ← n (after assignment)
Scope in Java
What is Scope?
Scope determines where variables can be accessed in your program.
Types of Scope:
1. Method Scope - Variables inside methods
2. Block Scope - Variables inside { } blocks
3. Class Scope - Variables at class level
Method Scope
Variables declared inside a method are only accessible within that method.
public class MethodScope {
public static void main(String[] args) {
int mainVar = 10;
someMethod();
Block Scope
Variables declared inside { } blocks are only accessible within those blocks.
public class BlockScope {
public static void main(String[] args) {
int mainVar = 10;
if (true) {
int blockVar = 20;
System.out.println(mainVar); // OK - outer scope
System.out.println(blockVar); // OK - same block
}
Important Rules:
Rule 1: Inner blocks can access outer variables
public static void scopeExample() {
int outer = 10;
if (outer > 5) {
int inner = 20;
System.out.println(outer); // ✅ OK - can access outer
if (true) {
// int x = 20; // ❌ Error! x already declared in outer
scope
x = 20; // ✅ OK - modifying existing variable
}
}
System.out.println(count); // Output: 5
}
Loop Scope
Variables declared in loop initializers have loop scope only.
public class LoopScope {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Shadowing
Shadowing occurs when a variable in an inner scope has the same name as a variable
in an outer scope.
public class ShadowingExample {
public static void main(String[] args) {
int x = 10; // Outer scope
if (true) {
int x = 20; // Inner scope - shadows outer x
System.out.println(x); // Prints 20 (inner x)
}
Better Practice:
// Clear and understandable
public static void clearExample() {
int originalValue = 100;
Output:
Sum of 2 numbers: 30
Sum of 4 numbers: 10
Sum of 5 numbers: 75
Varargs Syntax:
public static return_type methodName(dataType... variableName) {
// Method body
}
Key Points:
• int... numbers - three dots indicate varargs
• Internally treated as an array
• Can pass 0 or more arguments
• Must be the last parameter if multiple parameters exist
Varargs with Other Parameters:
public class MixedParameters {
// Correct: varargs as last parameter
public static void processData(String message, int...
numbers) {
System.out.println(message);
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
}
Output:
Numbers:
1 2 3 4 5
More numbers:
10 20
No numbers:
// ✅ Correct
public static void correct(String message, int... numbers) { }
Method Overloading
What is Method Overloading?
Method Overloading allows multiple methods with the same name but different
parameters.
Example: Multiple Sum Methods
public class MethodOverloading {
public static void main(String[] args) {
System.out.println(sum(10, 20)); // Calls int
version
System.out.println(sum(10, 20, 30)); // Calls 3-
parameter version
System.out.println(sum(10.5, 20.3)); // Calls double
version
}
// Method 1: Two integers
public static int sum(int a, int b) {
System.out.println("Two integer sum called");
return a + b;
}
Output:
Two integer sum called
30
Three integer sum called
60
Double sum called
30.8
Practice Questions
Question 1: Prime Number Checker
Create a method that checks if a number is prime.
import java.util.Scanner;
if (result) {
System.out.println(number + " is a prime number");
} else {
System.out.println(number + " is not a prime
number");
}
}
Test Cases:
Input: 7 Output: 7 is a prime number
Input: 8 Output: 8 is not a prime number
Input: 17 Output: 17 is a prime number
Input: 25 Output: 25 is not a prime number
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong
number");
} else {
→
→
→
→
System.out.println(number + " is not an Armstrong
number");
}
}
while (n > 0) {
int digit = n % 10;
sum += digit * digit * digit;
n /= 10;
}
while (n > 0) {
int digit = n % 10;
sum += digit * digit * digit;
n /= 10;
}
Output:
All 3-digit Armstrong numbers:
153 371 407
Key Takeaways
1. Function Fundamentals
• Purpose: Break code into reusable, organized blocks
• Bene ts: Code reusability, better organization, easier maintenance
• Java Term: Called "methods" because they belong to classes
2. Method Components
access_modifier static return_type method_name(parameters) {
// method body
return value; // if not void
}
3. Parameter vs Arguments
• Parameters: Variables in method de nition
• Arguments: Actual values passed when calling method
4. Return Types
• void: No return value
fi
fi
• Primitive types: int, double, boolean, char, etc.
• Reference types: String, arrays, objects
5. Memory Management
• Stack: Stores method calls and local variables
• Function calls: Create new stack frames
• Return: Removes stack frame and returns value
6. Pass by Value
• Java always passes by value
• Primitives: Copy of value passed
• Objects: Copy of reference passed (not the object itself)
• Important: Original variables don't change for primitives
7. Scope Rules
General Rule: Inner blocks can access outer variables, but not vice versa.
8. Advanced Concepts
• Varargs: Handle variable number of arguments with type... varName
• Method Overloading: Same method name, different parameters
• Shadowing: Inner variable hides outer variable (avoid this!)
9. Best Practices
• ✅ Use descriptive method names
• ✅ Keep methods focused on single task
• ✅ Limit parameters (ideally 3 or fewer)
• ✅ Use appropriate return types
• ✅ Avoid shadowing variables
• ✅ Document complex methods with comments
10. Common Mistakes to Avoid
• ❌ Missing return statement for non-void methods
• ❌ Unreachable code after return statement
• ❌ Scope violations - accessing variables outside scope
• ❌ Incorrect overloading - only return type different
• ❌ Multiple varargs or varargs not as last parameter