0% found this document useful (0 votes)
7 views81 pages

Java Notes

This document provides a comprehensive overview of Java programming fundamentals, covering essential concepts such as programming languages, memory management, and different programming paradigms including procedural, functional, and object-oriented programming. It explains the importance of programming languages in translating human-readable code into machine code and discusses the differences between static and dynamic languages, as well as stack and heap memory management. The guide emphasizes the significance of understanding these concepts for software development, technical interviews, and efficient coding practices.

Uploaded by

mukeshchevula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views81 pages

Java Notes

This document provides a comprehensive overview of Java programming fundamentals, covering essential concepts such as programming languages, memory management, and different programming paradigms including procedural, functional, and object-oriented programming. It explains the importance of programming languages in translating human-readable code into machine code and discusses the differences between static and dynamic languages, as well as stack and heap memory management. The guide emphasizes the significance of understanding these concepts for software development, technical interviews, and efficient coding practices.

Uploaded by

mukeshchevula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Java Programming Fundamentals

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

What are Programming Languages?


De nition
Programming languages allow us to:
• Write ideas in the form of code
• Get desired output from programs
• Create instructions for computers
Why Do We Need Programming Languages?
Computer's Internal Structure:
• Computers internally work with zeros and ones (binary numbers)
• Everything is stored as binary in memory
• Writing directly in binary would be extremely dif cult
Solution: Programming languages provide a human-readable format that gets
translated into machine code (zeros and ones).
Examples of Programming Tasks:
// Taking input from students
// Creating multiplication tables
// Displaying messages
// Calculating dates and times
fi
fi
The Translation Process:
Human-Readable Code Programming Language Machine Code
(Binary)

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

Languages that Support Procedural Programming:


• Java ✅
• Python ✅
• C++ ✅
• C✅

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

Characteristics of Pure Functions:


1. Never modify variables - only create new ones as output
2. Don't change original data - create copies for operations
3. Support First-Class Functions
What are First-Class Functions?
Functions can be treated like variables:
# Example of reassigning functions like variables
a = 10
b = 30
c = b # c now equals 30

# Similarly with functions


function1 = some_function
function2 = function1 # function2 now refers to same function

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

Template/Blueprint Instance of a class

Human (general concept) You (speci c person)

Student (template) Kunal (speci c student)

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)

To change engine type (diesel petrol):


- Only modify engine code
- Don't need to change entire car

Languages that Support Object-Oriented Programming:


• Java ✅
• Python ✅
• C++ ✅

Different Languages can be of Different Types


Important Concept:
A single programming language can support multiple programming paradigms!
Examples:
Java:
• ✅ Object-Oriented
• ✅ Procedural
Python:
• ✅ Object-Oriented
• ✅ Procedural
• ✅ Functional
C++:
fi
fi

• ✅ Object-Oriented
• ✅ Procedural
• ✅ Some Functional Programming
Hybrid Nature:
Languages are hybrid - they follow multiple theories and paradigms, not just one!

Static vs Dynamic Languages


This classi cation is based on when and how type checking is performed.
Understanding Variables and Types:
name = "Kunal" // String type
rollNumber = 56 // Integer type
marks = 93.6 // Float/Decimal type

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

String name = "Kunal"; // ✅ Correct

int a = "Kunal"; // ❌ Error at compile time

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:

Aspect Static Languages Dynamic Languages

Type Checking Compile time Runtime

Type Declaration Required Not required

Error Detection Compile time Runtime


fl
Flexibility Less More

Performance Better Potentially slower

Code Length More Less

Examples Java, C++ Python, JavaScript

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)

Memory Allocation Rules:


• Variables and function calls → Stored in Stack
Actual objects and values → Stored in Heap

Objects and Reference Variables
Fundamental Concept:
a = 10

In this simple statement:


• a = Reference Variable (stored in Stack)
• 10 = Object (stored in Heap)
Important: a is NOT the object - a is the reference variable that points to the object!
Memory Representation:

















































































































Stack Memory Heap Memory

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

Important Memory Examples


Real-World Analogy
The Human Example:
• My physical body = Object (stored in "heap memory" of the world)
• My name "Kunal" = Reference variable (points to my body)
Multiple Reference Variables:
Reference Variables Object

"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;

// Multiple references to same object


int c = a; // c now points to same object as a

Memory Visualization:
Stack Memory Heap Memory

a 10

c 10 (same object)

b 37

Critical Memory Rules:


Rule 1: Multiple References to Same Object
List<Integer> list1 = Arrays.asList(1, 3, 5, 9);
List<Integer> list2 = list1; // list2 points to same object as
list1

Rule 2: Changes Through Any Reference Affect All


list1.set(0, 99); // Change first element to 99
System.out.println(list2); // Output: [99, 3, 5, 9]
// list2 also shows the change!

Memory Diagram:
Stack Memory Heap Memory

list1 [99, 3, 5, 9]
(List Object)






































































































































































































































list2

Why This Matters:


Understanding this concept is crucial for:
• Pass by reference behavior
• Avoiding unexpected side effects
• Memory ef ciency
• Understanding object mutations

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

// Now imagine kunal "goes to forest and gives up his name"


kunal = null; // kunal reference is removed

// baby still points to the object, so it's NOT garbage

baby = null; // Now NO reference points to the object


// Object becomes GARBAGE

Memory Visualization:
Before:
Stack Memory Heap Memory

kunal Person Object


("Kunal")
baby







































fi



























































































































After kunal = null:
Stack Memory Heap Memory

kunal: null Person Object


("Kunal")
baby
(Still accessible)

After baby = null:


Stack Memory Heap Memory

kunal: null Person Object


("Kunal")
baby: null [GARBAGE]

How Garbage Collection Works:


Automatic Process:
1. Java automatically identi es objects with no references
2. Garbage Collector runs periodically
3. Removes unreferenced objects from memory
4. Frees up memory for new objects
Example:
// Creating objects
String a = "Hello";
String b = "World";

a = "Hi"; // "Hello" object becomes garbage (no reference)


// Garbage collector will remove it automatically

When Garbage Collection Happens:


• Automatically when memory is needed












































































































fi























































































• Cannot be forced immediately
• Can be suggested using System.gc() (but not guaranteed)
• Happens in background without stopping your program
Bene ts:
• ✅ Automatic memory management
• ✅ Prevents memory leaks
• ✅ No manual memory deallocation needed
• ✅ Safer than manual memory management

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

Dynamic (Python, JavaScript):


- Type checking at runtime
- No type declaration needed
- More flexibility, potential runtime errors

3. Memory Management
Stack Memory: Heap Memory:
- Reference Variables - Actual Objects
- Function Calls - Object Data
- Local Variables - Arrays, Objects

4. Objects and References


• Reference Variable ≠ Object
fi
• Multiple references can point to same object
• Changes through any reference affect all references
• Understanding this prevents bugs and unexpected behavior
5. Garbage Collection
• Automatic memory cleanup
• Removes objects with no references
• Prevents memory leaks
• Happens automatically in Java
6. Why This Matters for Java Programming
Understanding these concepts is essential for:
• Object-Oriented Programming
• Memory-ef cient coding
• Debugging reference-related issues
• Understanding Java's behavior
• Technical interviews

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?

Exercise 3: Reference Variables


Predict the output:
List<String> list1 = new ArrayList<>();
list1.add("Hello");
List<String> list2 = list1;
fi
list1.add("World");
System.out.println(list2.size()); // What will this print?

Exercise 4: Garbage Collection


Identify when objects become eligible for garbage collection:
String a = "First";
String b = "Second";
String c = a;
a = null;
b = null;
// Which objects are now garbage?

Flowcharts and Pseudocode


What are Flowcharts?
Flowcharts are visual representations used to:
• Visualize thought processes and work ows
• Plan program logic before writing code
• Communicate algorithms to others
• Debug complex problems by breaking them down
Bene ts of Flowcharts:
• ✅ Visual clarity - Easy to understand logic ow
• ✅ Problem solving - Break complex problems into simple steps
• ✅ Communication - Share ideas without language barriers
• ✅ Debugging - Identify logical errors before coding
Flowchart Symbols
Understanding the standard symbols used in owcharts:
1. Start/Stop (Terminal)

Oval ← Program Start/End


(Terminal)












fi






















fl
fl
fl
Usage: Beginning and end of programs
2. Input/Output (Parallelogram)

╱ ╲ ← Input/Output operations
╱ Parallelgram ╲
╱_______________╲

Usage: Taking input from user or displaying output


3. Processing (Rectangle)

Rectangle ← Processing/Calculations
(Processing)

Usage: Calculations, assignments, processing data


4. Decision (Diamond)
╱╲
╱ ╲ ← Conditions/Decisions
╱ ╲
╱ Diamond ╲
╲ ╱
╲ ╱
╲ ╱
╲╱

Usage: If-else conditions, loops, comparisons


5. Flow Lines (Arrows)
← ↑ ← Direction of program flow

Usage: Show direction from one step to another

Problem Solving with Flowcharts


Question 1: Simple Greeting Program
Problem: Take user's name as input and display "Hello [Name]"















































Flowchart:

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

Question 2: Salary Bonus Calculator


Problem: Input employee salary. If salary > 10000, give bonus of Rs.2000, otherwise
give bonus of Rs.1500.
Flowchart:

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

Question 3: Prime Number Checker


Problem: Input a number and check whether it's a prime number or not.
Prime Number De nition: A number that is only divisible by 1 and itself.
Examples:
• 7 is prime (divisible by 1, 7 only)
• 6 is not prime (divisible by 1, 2, 3, 6)
Basic Approach Flowchart:

START

INPUT
Number

i = 2

╱╲







































































fi



















╱ ╲
╱ i < ╲ No
╱ Number╲
╱_________╲
Yes

╱╲ OUTPUT
╱ ╲ "Prime"
╱Number╲ No
╱ % i ==0╲
╱__________╲
Yes

OUTPUT
"Not Prime"

STOP

Optimized Approach (Square Root Method):


Instead of checking all numbers from 2 to n-1, we only check from 2 to √n.
Why this works: If a number n has a factor greater than √n, it must also have a
corresponding factor smaller than √n.

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

WHILE i < number DO


IF number % i == 0 THEN
OUTPUT "Not Prime"
STOP
END IF
SET i = i + 1
END WHILE

OUTPUT "Prime"
STOP
END

Question 3: Prime Number Checker (Optimized Method)


BEGIN
START program
fi
fi
INPUT number
SET i = 2

WHILE i <= square_root(number) DO


IF number % i == 0 THEN
OUTPUT "Not Prime"
STOP
END IF
SET i = i + 1
END WHILE

OUTPUT "Prime"
STOP
END

Question 2: Salary Bonus Calculator


BEGIN
START program

INPUT salary

IF salary > 10000 THEN


SET bonus = 2000
ELSE
SET bonus = 1500
END IF

SET new_salary = salary + bonus


OUTPUT new_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)

Usage in Prime Checking:


IF number % i == 0 THEN
// number is divisible by i
// Therefore, not prime
END IF

2. Loops and Conditions


While Loop Structure:
WHILE condition DO
// statements to execute
// update condition variable
END WHILE

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)

Result: 36 % 2 = 0, so 36 is not prime


Optimization: Stopped at 6 instead of checking till 35

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.

Programming Fundamentals Covered


Essential Elements:
1. Sequential Execution - Steps executed one after another
2. Conditional Statements - Decision making (if-else)
3. Loops - Repetitive execution (while, for)
4. Input/Output - User interaction
5. Variables - Data storage
fl
fl
fl
fl
6. Operators - Mathematical and logical operations
These Building Blocks Can Solve:
• ✅ Complex algorithms
• ✅ Data processing
• ✅ Mathematical computations
• ✅ Business logic
• ✅ Game development
• ✅ Any computational problem

Why Flowcharts and Pseudocode Matter


For Programming:
1. Plan before coding - Avoid logical errors
2. Clear thinking - Organize thoughts systematically
3. Team collaboration - Share ideas effectively
4. Documentation - Record problem-solving approach
For Problem Solving:
1. Break complex problems into simple steps
2. Identify patterns and repetitive tasks
3. Optimize solutions before implementation
4. Debug logic before writing code
For Learning:
1. Language independence - Focus on logic, not syntax
2. Visual learning - See the ow of execution
3. Step-by-step approach - Build understanding gradually
4. Foundation building - Essential for advanced concepts

Java Code Execution and Architecture


How Java Code Executes
Understanding the complete Java execution process from source code to running
application.
The Java Execution Journey
Source Code (.java) Compiler (javac) Bytecode (.class) JVM
Machine Code Output


fl



Step-by-Step Process:
1. Write Java Code: Create .java les with human-readable code
2. Compilation: Java compiler (javac) converts source code to bytecode
3. Bytecode Generation: Creates .class les containing platform-independent
code
4. JVM Execution: Java Virtual Machine interprets/compiles bytecode to machine
code
5. Program Output: Application runs and produces results

Platform Independence in Java


What is Platform Independence?
Platform Independence means that Java code can run on any operating system
without modi cation.
Key Concept: "Write Once, Run Anywhere" (WORA)
Java Source Code Compile Once Run on Any Platform

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:

Language Compilation Result Platform Dependent?

C/C++ Machine Code (.exe) ✅ Yes - OS speci c

Java Bytecode (.class) ❌ No - Platform independent

Why Java is Platform Independent


Traditional Languages (C/C++):
Source Code Compiler Machine Code (Platform Specific)

• Direct compilation to machine code


• Different executable needed for each operating system
• Platform dependent - Windows .exe won't run on Linux
Java Approach:
fi

fi

fi

fi
fi
fi
fi

Source Code Java Compiler Bytecode JVM Machine Code

• Intermediate bytecode instead of direct machine code


• Same bytecode runs on all platforms
• JVM handles platform-speci c conversion

Java Architecture Components


Overview of Java Ecosystem

JDK

JRE

JVM

JDK (Java Development Kit)


De nition:
Complete development environment to develop and run Java programs.
Components of JDK:
1. JRE (Java Runtime Environment)
2. Development Tools:
◦ javac (Java Compiler)
◦ java (Java Application Launcher)
◦ javadoc (Documentation Generator)
◦ jar (Archive Tool)
3. Libraries and APIs
4. Sample Code and Demos
When to Use JDK:
















fi





















































































































fi





























































































• ✅ Developing Java applications
• ✅ Compiling source code
• ✅ Creating new programs
• ✅ Learning Java programming

JRE (Java Runtime Environment)


De nition:
Execution environment to run Java programs (not create them).
Components of JRE:
1. JVM (Java Virtual Machine)
2. Core Libraries:
◦ Base classes
◦ Utility classes
◦ I/O libraries
3. Deployment Technologies
4. User Interface Toolkits
5. Integration Libraries
When to Use JRE:
• ✅ Running existing Java applications
• ✅ End-user systems
• ❌ Cannot compile new programs
• ❌ Cannot develop applications
JDK vs JRE:

Aspect JDK JRE

Purpose Development + Execution Execution Only

Compiler ✅ Included ❌ Not Included

Can Develop ✅ Yes ❌ No

Can Run ✅ Yes ✅ Yes

Size Larger Smaller


fi
Target Users Developers End Users

JVM (Java Virtual Machine)


De nition:
Runtime engine that executes Java bytecode and converts it to machine code.
Key Characteristics:
1. Platform Speci c: Different JVM for each operating system
2. Bytecode Interpreter: Converts bytecode to machine code
3. Memory Manager: Handles memory allocation and garbage collection
4. Security Manager: Provides security features
JVM Components:
1. Class Loader
Loads .class les into memory
Process:
Loading Linking Initialization

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

Compiler vs Interpreter in Java


Understanding the Terminology
Compile Time:
• When: Source code is converted to bytecode
• Tool: javac compiler
• Output: .class les with bytecode
• Errors: Syntax errors detected here
Runtime:
• When: Program is actually executing
• Tool: JVM
•Process: Bytecode → Machine Code → Execution
• Errors: Logic errors, exceptions occur here
How JVM Executes Code
Traditional Interpretation Problem:
Problem: Repeated code blocks get interpreted multiple times
Function called 100 times = Same code interpreted 100 times
Result: Slow execution

JVM Solution: Just-In-Time (JIT) Compilation


Smart Optimization:
1. Initially: Interpret bytecode line by line
2. Detection: Identify frequently used code blocks
3. Compilation: Convert hot spots to machine code
4. Caching: Store compiled machine code
5. Reuse: Use cached machine code for subsequent calls
Bene ts:
• ✅ Faster execution for repeated operations
• ✅ Adaptive optimization based on usage patterns
• ✅ Memory ef cient - only compile what's needed

Static Variables and Memory Management


fi
fi
fi
Understanding Static Variables
De nition:
Variables that belong to the class, not to individual objects.
Characteristics:
• ✅ Shared among all objects of the class
• ✅ Memory allocated once when class is loaded
• ✅ Independent of object creation
• ✅ Initialized during class loading
Real-World Example:
class Human {
String name; // Instance variable (different for
each person)
static int population; // Static variable (same for all
humans)
}

Memory Representation:
Stack Memory Heap Memory

person1 Human Object


name="John"
person2

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";

// Object becomes garbage


greeting = "Hi"; // "Hello" object now has no reference
// Eligible for garbage collection

Garbage Collection Process:


1. Detection: Find objects with no references
2. Marking: Mark unreachable objects
3. Sweeping: Remove marked objects from memory
4. Compaction: Reorganize memory to reduce fragmentation
Bene ts:
• ✅ Automatic memory management
• ✅ Prevents memory leaks
• ✅ No manual deallocation needed
• ✅ Safer than manual memory management

Complete Java Architecture Work ow


Development to Execution Process:
1. Write Code (IDE)

2. Compile (javac)


fi
fl
3. Generate Bytecode (.class)

4. Load Classes (Class Loader)

5. Verify Bytecode (JVM)

6. Interpret/Compile (Execution Engine)

7. Execute on Hardware

8. Display Output

Tools Required for Java Development


Essential Software:
1. JDK (Java Development Kit)
◦ Download from Oracle website
◦ Choose version based on project requirements
◦ Includes compiler, runtime, and development tools
2. IDE (Integrated Development Environment)
◦ IntelliJ IDEA (Recommended)
◦ Eclipse
◦ Visual Studio Code
◦ NetBeans
Installation Steps:
1. Download JDK from of cial Oracle website
2. Install JDK according to your operating system
3. Download IDE (IntelliJ IDEA Community Edition is free)
4. Install IDE and con gure JDK path
5. Create rst project and start coding

Key Differences Summary


JDK vs JRE vs JVM

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

JVM Java Virtual Machine Code Execution Execution Engine

Compilation vs Interpretation

Aspect Compilation Interpretation

When Before execution During execution

Tool javac compiler JVM interpreter

Output Bytecode (.class) Machine code

Speed Slower initially Faster startup

Optimization Static Dynamic (JIT)

Important Java Execution Concepts


1. Bytecode Advantages
• ✅ Platform independent - same code runs everywhere
• ✅ Compact size - smaller than source code
• ✅ Security - can be veri ed before execution
• ✅ Optimization - JIT compiler can optimize during runtime
2. JVM Bene ts
• ✅ Memory management - automatic garbage collection
• ✅ Security - sandboxed execution environment
• ✅ Performance - JIT compilation for optimization
• ✅ Portability - write once, run anywhere
3. Class Loading Process
Dynamic Loading:
• Classes loaded on demand (when rst referenced)
• Lazy loading - improves startup time
• Runtime linking - exible and modular
4. Memory Ef ciency
fi
fi
fl
fi
fi
Stack vs Heap Usage:
• Stack: Fast access, limited size, automatic cleanup
• Heap: Flexible size, garbage collection, shared memory

Real-World Application Examples


1. Hello World Program Journey
// HelloWorld.java (Source Code)
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

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

Best Practices for Java Development


1. Memory Management
fi
• ✅ Avoid memory leaks - remove unused references
• ✅ Use appropriate data structures - choose right collections
• ✅ Monitor garbage collection - tune for performance
2. Code Organization
• ✅ Follow naming conventions - camelCase for variables
• ✅ Use meaningful names - self-documenting code
• ✅ Organize packages - logical grouping of classes
3. Performance Optimization
• ✅ Pro le your application - identify bottlenecks
• ✅ Optimize hot spots - focus on frequently used code
• ✅ Use appropriate algorithms - choose ef cient solutions

Troubleshooting Common Issues


1. ClassNotFoundException
Cause: Class le not found in classpath Solution: Verify le location and classpath
settings
2. OutOfMemoryError
Cause: Insuf cient heap memory Solution: Increase heap size with -Xmx ag
3. Compilation Errors
Cause: Syntax errors in source code Solution: Check error messages and x syntax
issues

Next Steps in Java Learning


Immediate Next Topics:
1. Java Syntax Fundamentals
◦ Variables and data types
◦ Operators and expressions
◦ Control structures
2. Object-Oriented Programming
◦ Classes and objects
◦ Inheritance and polymorphism
◦ Encapsulation and abstraction
3. Advanced Concepts
fi
fi
fi
fi
fi
fl
fi
◦ Exception handling
◦ Collections framework
◦ Multithreading
4. Development Tools
◦ IDE usage and features
◦ Debugging techniques
◦ Build tools (Maven, Gradle)

Java Programming Basics and Syntax


Java File Structure
Every Java program must follow a speci c structure:
Basic Java File Template:
// Package declaration (optional)
package com.company;

// 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

Understanding Java Keywords


1. public Keyword
Meaning: Class/method can be accessed from anywhere
public class Demo { // Accessible from any package
fi
fi
public static void main(String[] args) { // Accessible from
anywhere
// code
}
}

2. static Keyword
Meaning: Belongs to class, not to individual objects
public class Human {
static int population = 7000000000; // Shared by all humans

public static void main(String[] args) {


// Can run without creating Human object
System.out.println("Population: " + population);
}
}

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
}

public static int addNumbers(int a, int b) {


return a + b; // Returns integer value
}

Input and Output in Java


Output - System.out.println()
System.out.println("Hello World"); // Prints with new line
fi
System.out.print("Hello "); // Prints without new
line
System.out.print("World"); // Same line: "Hello
World"

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;

public class InputExample {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// 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();

System.out.println("Name: " + name + ", Age: " + age +


", Marks: " + marks);
}
}
Scanner Methods:

Method Data Type Example

nextInt() Integer int num = input.nextInt();

float
nextFloat() Float
price = input.nextFloat();

nextDouble( double
Double
) salary = input.nextDouble();

String (single
next() String word = input.next();
word)

nextLine() String (full line) String line = input.nextLine();

nextBoolean boolean
Boolean
() flag = input.nextBoolean();

Primitive Data Types in Java


Numeric Data Types:

Type Size Range Example

byte 1 byte -128 to 127 byte age = 25;

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

Non-Numeric Data Types:


char grade = 'A'; // Single character
boolean passed = true; // true or false
String name = "Kunal"; // Text (not primitive, but commonly
used)

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

// Floating point types


float height = 5.8f; // Note: f suffix for
float
double weight = 65.5;

// Character and boolean


char section = 'A';
boolean isStudent = true;

System.out.println("Roll: " + rollNumber);


System.out.println("Height: " + height + " feet");
System.out.println("Is student: " + isStudent);
}
}

Type Conversion and Casting


1. Automatic Type Conversion (Implicit)
Conditions:
• Types must be compatible
• Destination type must be larger than source type
int num = 100;
float decimal = num; // int float (automatic)
System.out.println(decimal); // Output: 100.0

long bigNum = num; // int long (automatic)


double precise = decimal; // float double (automatic)

Valid Automatic Conversions:


byte short int long float double
char int long float double

2. Type Casting (Explicit)


When needed: Converting larger type to smaller type
double price = 99.99;
int rupees = (int) price; // Explicit casting
System.out.println(rupees); // Output: 99 (decimal part lost)

float marks = 85.7f;


int finalMarks = (int) marks; // Output: 85

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

// Information loss in casting


int largeNum = 300;
byte smallNum = (byte) largeNum; // Overflow!
System.out.println(smallNum); // 44 (300 % 256 = 44)
}
}

3. Type Promotion in Expressions


Rules:
1. byte, short, char → promoted to int in expressions
2. If one operand is long → whole expression becomes long
3. If one operand is float → whole expression becomes float
4. If one operand is double → whole expression becomes double
byte a = 10;
byte b = 20;
// byte c = a + b; // Error! Expression promotes to int
int c = a + b; // Correct

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 (age >= 18) {


System.out.println("You can vote!");
}

If-Else Statement:
int marks = 75;

if (marks >= 60) {


System.out.println("Pass");
} else {
System.out.println("Fail");
}

If-Else-If Ladder:
int score = 85;

if (score >= 90) {


System.out.println("Grade A");
} else if (score >= 80) {
System.out.println("Grade B");
} else if (score >= 70) {
System.out.println("Grade C");
} else {
System.out.println("Grade F");
}

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

When to Use Which Loop:

Loop Type Use When

for You know exact number of iterations

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
}

// while loop - unknown iterations


Scanner input = new Scanner(System.in);
int number;
while (true) {
System.out.print("Enter number (0 to exit): ");
number = input.nextInt();
if (number == 0) break;
System.out.println("You entered: " + number);
}

Practical Examples
1. Sum of Two Numbers:
import java.util.Scanner;

public class AddNumbers {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = input.nextInt();

System.out.print("Enter second number: ");


int num2 = input.nextInt();

int sum = num1 + num2;


System.out.println("Sum = " + sum);
}
}

2. Temperature Conversion:
import java.util.Scanner;

public class TemperatureConverter {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter temperature in Celsius: ");


float celsius = input.nextFloat();

float fahrenheit = (celsius * 9/5) + 32;

System.out.println(celsius + "°C = " + fahrenheit +


"°F");
}
}

3. Grade Calculator:
import java.util.Scanner;

public class GradeCalculator {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter your marks: ");


int marks = input.nextInt();

if (marks >= 90) {


System.out.println("Grade: A");
} else if (marks >= 80) {
System.out.println("Grade: B");
} else if (marks >= 70) {
System.out.println("Grade: C");
} else if (marks >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}

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

// Print multiplication table of 5


for (int i = 1; i <= 10; i++) {
System.out.println("5 x " + i + " = " + (5 * i));
}
}
}

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;
}
}

Literals and Identi ers


Literals (Actual Values):
int age = 25; // 25 is integer literal
float price = 99.99f; // 99.99f is float literal
char grade = 'A'; // 'A' is character literal
String name = "Kunal"; // "Kunal" is string literal
boolean flag = true; // true is boolean literal

// Large numbers with underscores for readability


int million = 1_000_000; // Same as 1000000
long billion = 1_000_000_000L; // Same as 1000000000L

Identi ers (Names):


Rules for naming variables, methods, classes:
// Valid identifiers
int age;
fi
fi
int roll_number;
int rollNumber; // camelCase (preferred)
int $price;
int _count;

// Invalid identifiers
// int 2age; // Cannot start with digit
// int roll-number; // Hyphen not allowed
// int class; // 'class' is reserved keyword

Java Unicode Support


Java supports Unicode, allowing international characters:
public class UnicodeExample {
public static void main(String[] args) {
System.out.println("Hello"); // English
System.out.println("नम "); // Hindi
System.out.println("你好"); // Chinese

char hindi = 'अ';


char chinese = '中';
System.out.println("Hindi: " + hindi);
System.out.println("Chinese: " + chinese);
}
}

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

What are Functions/Methods?


De nition:
A function (or method in Java) is a block of code that performs a speci c task and can
be called/invoked when needed.
Real-World Analogy:
Think of a function like a machine:
• Input: Raw materials (parameters)
• Process: What the machine does (function body)
• Output: Finished product (return value)
Why "Methods" in Java?
In Java, functions are called methods because they are always associated with a class.
Everything in Java is inside a class, so we use the term "method" instead of "function."

Why Do We Need Functions?


Problem Without Functions:
Imagine you need to add two numbers in 10 different places in your code:
// Without functions - Code duplication
public class Calculator {
public static void main(String[] args) {
// Place 1
int a1 = 5, b1 = 3;
int sum1 = a1 + b1;
System.out.println(sum1);

// Place 2
int a2 = 10, b2 = 20;
int sum2 = a2 + b2;
System.out.println(sum2);

// Place 3... and so on (Copy-paste 10 times!)


fi
fi
}
}

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
}

// Function defined once, used everywhere


public static int sum(int a, int b) {
return a + b;
}
}

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:

Component Description Example


Access
Controls visibility public, private, protected
Modi er

Belongs to class (not


static static (optional)
object)

Return Type Type of value returned int, String, void

sum, greetUser, calculateAr


Method Name Identi er for the method
ea

Parameters Input values (int a, int b)

Method Body Code to execute { return a + b; }

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;

public class MathOperations {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = input.nextInt();

System.out.print("Enter second number: ");


int num2 = input.nextInt();

// Calling the function


int result = sum(num1, num2);
System.out.println("Sum = " + result);
}

// 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
}

// Function that prints but doesn't return anything


public static void greetings() {
System.out.println("Hello! Welcome to Java
programming!");
}
}

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));
}

public static int sum(int a, int b) {


int result = a + b;
return result; // Returning the calculated value
}
}

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);

System.out.print("Enter your name: ");


String name = input.nextLine();

// Calling string function


String message = greet(name);
System.out.println(message);
}

public static String greet(String name) {


String greeting = "Hello " + name + ", how are you?";
return greeting;
}
}

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 and Arguments


Understanding the Difference:

Term De nition Example

Parameters Variables in function de nition int a, int b

Arguments Actual values passed to function sum(10, 20)

Parameter Passing Example:


public class ParameterExample {
public static void main(String[] args) {
// Arguments: 15 and 25
int result = multiply(15, 25);
fi
fi
System.out.println("Result: " + result);
}

// Parameters: a and b
public static int multiply(int a, int b) {
return a * b;
}
}

How Parameter Passing Works:


1. Function Call: multiply(15, 25)
2. Parameter Assignment:
◦ a = 15
◦ b = 25
3. Function Execution: Uses values of a and b
4. Return: Calculated result sent back

Return Types
Common Return Types:

Return Type Description Example

void No return value public static void printMessage()

int Integer number public static int calculate()

double Decimal number public static double getPrice()

String Text value public static String getName()

boolean True/False public static boolean isValid()

Examples of Different Return Types:


public class ReturnTypes {
// Void - no return value
public static void displayInfo() {
System.out.println("This is information");
}
// Integer return
public static int getAge() {
return 25;
}

// 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 Management in Functions


Stack Memory and Function Calls
How Functions Work in Memory:
public class MemoryExample {
public static void main(String[] args) {
int x = 10;
int y = 20;
int result = add(x, y);
System.out.println(result);
}

public static int add(int a, int b) {


int sum = a + b;
return sum;
}
}

Memory Visualization:
Stack Memory (Function Calls):

← add() function call


a = 10
b = 20
sum = 30

← main() function call


x = 10
y = 20
result = 30

Function Call Lifecycle:


1. Function Called: New stack frame created
2. Parameters Copied: Values passed to function parameters
3. Local Variables: Created in function's stack frame
4. Function Execution: Code runs with local data
5. Return Value: Sent back to caller
6. Stack Frame Removed: Function's memory cleaned up

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!
}

public static void changeValue(int num) {


num = 50; // Changes only the copy, not original
System.out.println("Inside function: " + num); // 50
}
}

Output:
Before: 10
Inside function: 50
After: 10

Memory Explanation:
Stack Memory:

main() function: changeValue() function:

original=10 num = 10 ← Copy of original


(later=50)


































































Key Points:
• Function receives a copy of the value
• Changes to the copy don't affect the original
• Original variable remains unchanged
Example 2: Swapping Numbers (Won't Work)
public class SwapExample {
public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Before swap: a=" + a + ", b=" + b);

swap(a, b);
System.out.println("After swap: a=" + a + ", b=" + b);
}

public static void swap(int x, int y) {


int temp = x;
x = y;
y = temp;
System.out.println("Inside function: x=" + x + ", y=" +
y);
}
}

Output:
Before swap: a=10, b=20
Inside function: x=20, y=10
After swap: a=10, b=20

Why Swapping Doesn't Work:


• Function works with copies of a and b
• Swapping happens between copies x and y
• Original variables a and b remain unchanged
Example 3: String Parameters
public class StringPassExample {
public static void main(String[] args) {
String name = "Kunal";
System.out.println("Before: " + name);

changeName(name);
System.out.println("After: " + name);
}

public static void changeName(String n) {


n = "Rahul"; // Creates new String object
System.out.println("Inside function: " + n);
}
}

Output:
Before: Kunal
Inside function: Rahul
After: Kunal

Why String Doesn't Change:


• Strings are immutable in Java
• n = "Rahul" creates a new String object
• Original string object remains unchanged
• Reference copy n points to new object, but original name still points to "Kunal"
Memory Visualization for Strings:
Heap Memory: Stack Memory:

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();

// System.out.println(methodVar); // Error! Can't access


methodVar
}

public static void someMethod() {


int methodVar = 20;

// System.out.println(mainVar); // Error! Can't access


mainVar
System.out.println(methodVar); // OK - within same
method
}
}




























Rules:
• ✅ Variables declared in a method are local to that method
• ❌ Cannot access variables from other methods
• ✅ Each method has its own separate scope

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
}

// System.out.println(blockVar); // Error! blockVar not


accessible
System.out.println(mainVar); // OK - same method
}
}

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

System.out.println(inner); // ✅ OK - same block


}

System.out.println(outer); // ✅ OK - same method

// System.out.println(inner); // ❌ Error - inner not


accessible
}

Rule 2: Cannot redeclare same variable in same scope


public static void variableRedeclaration() {
int x = 10;

if (true) {
// int x = 20; // ❌ Error! x already declared in outer
scope
x = 20; // ✅ OK - modifying existing variable
}
}

Rule 3: Can modify outer variables from inner blocks


public static void modifyOuter() {
int count = 0;

for (int i = 0; i < 5; i++) {


count++; // ✅ Modifying outer 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);
}

// System.out.println(i); // Error! i not accessible


outside loop

// Can declare i again


for (int i = 10; i < 15; 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)
}

System.out.println(x); // Prints 10 (outer x)


}
}
What Happens:
• Inner x shadows (hides) the outer x
• Inside the block, only inner x is accessible
• Outside the block, outer x is accessible again
• Important: This is not good practice - avoid shadowing!
Why Avoid Shadowing:
// Confusing code - avoid this!
public static void confusingExample() {
int value = 100;

if (value > 50) {


int value = 200; // Shadows outer value
value = value + 10; // Which value? (inner one)
}

System.out.println(value); // Which value? (outer one -


still 100)
}

Better Practice:
// Clear and understandable
public static void clearExample() {
int originalValue = 100;

if (originalValue > 50) {


int calculatedValue = 200;
calculatedValue = calculatedValue + 10;
}

System.out.println(originalValue); // Clear what this refers


to
}
Variable Arguments (Varargs)
Problem: Unknown Number of Arguments
Sometimes we don't know how many arguments will be passed to a function:
// What if we want to add different numbers of values?
sum(2, 3); // 2 numbers
sum(1, 2, 3, 4); // 4 numbers
sum(5, 10, 15, 20, 25); // 5 numbers

Solution: Variable Arguments (Varargs)


public class VarargsExample {
public static void main(String[] args) {
System.out.println("Sum of 2 numbers: " + sum(10, 20));
System.out.println("Sum of 4 numbers: " + sum(1, 2, 3,
4));
System.out.println("Sum of 5 numbers: " + sum(5, 10, 15,
20, 25));
}

// Varargs method - can accept any number of integers


public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
}

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();
}

public static void main(String[] args) {


processData("Numbers: ", 1, 2, 3, 4, 5);
processData("More numbers: ", 10, 20);
processData("No numbers: "); // Empty varargs
}
}

Output:
Numbers:
1 2 3 4 5
More numbers:
10 20
No numbers:

Important Varargs Rules:


1. Only one varargs parameter per method
2. Must be last parameter
3. Treated as array internally
// ❌ Wrong - multiple varargs
public static void wrong(int... a, String... b) { }

// ❌ Wrong - varargs not last


public static void wrong(int... numbers, String message) { }

// ✅ 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;
}

// Method 2: Three integers


public static int sum(int a, int b, int c) {
System.out.println("Three integer sum called");
return a + b + c;
}

// Method 3: Two doubles


public static double sum(double a, double b) {
System.out.println("Double sum called");
return a + b;
}
}

Output:
Two integer sum called
30
Three integer sum called
60
Double sum called
30.8

How Method Overloading Works:


Compile-Time Decision: Java compiler determines which method to call based on:
1. Number of parameters
2. Type of parameters
3. Order of parameters
Valid Overloading Examples:
public class ValidOverloading {
// Different number of parameters
public static void print(int a) { }
public static void print(int a, int b) { }

// Different types of parameters


public static void print(int a) { }
public static void print(String a) { }

// Different order of parameters


public static void print(int a, String b) { }
public static void print(String a, int b) { }
}

Invalid Overloading Examples:


public class InvalidOverloading {
// ❌ Error: Only return type different
public static int calculate(int a, int b) { return a + b; }
public static double calculate(int a, int b) { return a + b;
} // Error!

// ❌ Error: Only parameter names different


public static int sum(int a, int b) { return a + b; }
public static int sum(int x, int y) { return x + y; } //
Error!
}

Method Overloading Rules:

Criteria Can Differentiate Methods?

Number of parameters ✅ Yes


Type of parameters ✅ Yes

Order of parameters ✅ Yes

Return type only ❌ No

Parameter names only ❌ No

Practice Questions
Question 1: Prime Number Checker
Create a method that checks if a number is prime.
import java.util.Scanner;

public class PrimeChecker {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();

boolean result = isPrime(number);

if (result) {
System.out.println(number + " is a prime number");
} else {
System.out.println(number + " is not a prime
number");
}
}

public static boolean isPrime(int n) {


// Handle special cases
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;

// Check odd divisors up to sqrt(n)


for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}

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

Question 2: Armstrong Number Checker


Create a method that checks if a number is an Armstrong number.
Armstrong Number: Sum of cubes of digits equals the original number
• Example: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
public class ArmstrongChecker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();

if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong
number");
} else {




System.out.println(number + " is not an Armstrong
number");
}
}

public static boolean isArmstrong(int n) {


int original = n;
int sum = 0;

while (n > 0) {
int digit = n % 10;
sum += digit * digit * digit;
n /= 10;
}

return sum == original;


}
}

Question 3: Print All 3-Digit Armstrong Numbers


public class AllArmstrongNumbers {
public static void main(String[] args) {
System.out.println("All 3-digit Armstrong numbers:");

for (int i = 100; i <= 999; i++) {


if (isArmstrong(i)) {
System.out.print(i + " ");
}
}
}

public static boolean isArmstrong(int n) {


int original = n;
int sum = 0;

while (n > 0) {
int digit = n % 10;
sum += digit * digit * digit;
n /= 10;
}

return sum == original;


}
}

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

Scope Type Accessibility

Method Scope Within method only

Block Scope Within { } block only

Loop Scope Within loop only

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

You might also like