Java Module2
Java Module2
MVJCE
1 / 81
Table of Contents
1 Class Fundamentals
2 Declaring Objects
3 Assigning Object Reference Variables
4 Introducing Methods
5 Constructors
6 The this Keyword
7 Garbage Collection
2 / 81
Understanding Classes: The Foundation of Java
Core Concept
The class is at the core of Java. It is the logical construct upon which the
entire Java language is built because it defines the shape and nature of an
object.
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
type methodnameN(parameter-list) {
// body of method
}
} 4 / 81
Components:
Instance Variables: Data defined within a class
Methods: Code contained within the class
Members: Collective term for methods and variables
Understanding Instance Variables
What are Instance Variables?
Variables defined within a class
Called ”instance” variables because each instance (object) of the class
contains its own copy
Data for one object is separate and unique from data for another
Acted upon and accessed by methods defined for that class
Key Principle:
Methods determine how a class’s data can be used
Instance variables are accessed through methods (encapsulation)
Each object maintains its own set of instance variables
Important Notes:
Most methods will not be specified as static or public
Classes don’t need a main() method unless they’re the starting point
Some Java applications don’t require main() at all
5 / 81
A Simple Class Example
The Box Class:
class Box {
double width;
double height;
double depth;
}
What This Defines:
A new data type called ”Box”
Three instance variables: width, height, depth
Currently contains no methods
Creates a template - no actual objects exist yet
Critical Understanding:
Class declaration only creates a template
Does not create actual objects
Objects must be explicitly created using specific statements
6 / 81
Object Creation: A Two-Step Process
Step 1: Declaration
Declare a variable of the class type
This variable does not define an object
It’s simply a variable that can refer to an object
Step 2: Instantiation
Acquire an actual, physical copy of the object
Assign it to the variable using the new operator
The new operator dynamically allocates memory at runtime
7 / 81
Object Declaration Syntax
Two-Step Approach:
What Happens:
First line declares mybox as a reference to a Box object
At this point, mybox does not refer to an actual object
Second line allocates an object and assigns reference to mybox
After second line executes, you can use mybox as a Box object
In reality, mybox holds the memory address of the actual Box object
8 / 81
Understanding the ’new’ Operator
General Form:
class-var = new classname();
Components:
class-var: Variable of the class type being created
classname: Name of the class being instantiated
Parentheses: Specify the constructor for the class
Constructor Behavior:
Constructor defines what occurs when object is created
If no explicit constructor is specified, Java provides default constructor
Default constructor is what Box uses initially
Memory Management:
new allocates memory during runtime
Program can create as many or as few objects as needed
If insufficient memory exists, runtime exception occurs
9 / 81
Primitive Types vs. Object Types
Why Don’t Primitives Need ’new’ ?
Java’s primitive types are not implemented as objects
They are implemented as ”normal” variables for efficiency
Objects have many features and attributes requiring special treatment
By not applying object overhead to primitives, Java implements them
more efficiently
Object Benefits:
Flexibility in memory allocation
Dynamic creation during program execution
Automatic memory management through garbage collection
class BoxDemo {
public static void main(String[] args) {
Box mybox = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
12 / 81
Important Compilation and Execution Notes
File Naming:
File should be called [Link] (contains main() method)
Java compiler automatically puts each class in its own .class file
Will create both [Link] and [Link]
Class File Organization:
Not necessary for both classes to be in same source file
Could separate into [Link] and [Link]
Execute [Link] to run the program
Program Output:
Volume is 3000.0
Object Independence:
Each object has its own copies of instance variables
Changes to one object’s variables don’t affect another object
This is fundamental to object-oriented programming
13 / 81
Multiple Objects Example
// Demonstration with two Box objects
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;
Volume is 3000.0
Volume is 162.0
Key Insights:
mybox1 and mybox2 are completely separate objects
Each maintains its own set of instance variables
[Link] is completely different from [Link]
Modifying one object has no effect on the other
Memory Visualization:
Two separate memory locations allocated
Each contains width, height, and depth variables
Variables in each object can hold different values
This separation is automatically maintained by Java
15 / 81
Object Reference Assignment: A Common Misconception
Consider This Code:
Box b1 = new Box();
Box b2 = b1;
What You Might Think:
b2 is assigned a reference to a copy of the object referred to by b1
b1 and b2 refer to separate and distinct objects
Reference Independence:
Although b1 and b2 refer to same object, they are not linked
otherwise
Subsequent assignment to b1 unhooks it from original object
This doesn’t affect the object or b2
17 / 81
Reference Reassignment Example
After b1 = null:
b1 becomes null
b2 still points to the same Box
Object is still accessible via b2
b1 no longer references anything
Key Point
Assigning one object reference to another copies the reference, not the object.
Memory Note:
Object stays in memory while a reference exists
Becomes eligible for garbage collection when no references remain
18 / 81
Introduction to Methods
19 / 81
General Form of a Method
Basic Method Syntax:
type name(parameter-list) {
// body of method
}
Components Explained:
type: Specifies the type of data returned by the method
Can be any valid type, including class types you create
Must be void if method doesn’t return a value
name: The method identifier
Can be any legal identifier
Must not conflict with other items in current scope
parameter-list: Sequence of type and identifier pairs separated by
commas
Parameters receive values of arguments passed to method
Empty if method has no parameters
20 / 81
Return Statement
Returning Values:
Methods with return type other than void must return a value
Use the return statement to return values
Return Statement Syntax:
return value;
Key Points:
value is the actual value being returned
Return type must match method declaration
void methods don’t need return statement
return statement transfers control back to caller
Coming Up:
How to create methods that take parameters
How to create methods that return values
Practical examples of both types
21 / 81
Why Add Methods to Classes?
Class Design Principles:
Classes containing only data are rare
Methods provide controlled access to instance variables
Methods define the interface to most classes
Hide specific layout of internal data structures
Provide cleaner method abstractions
Method Types:
Methods that provide access to data
Methods used internally by the class itself
Both types essential for well-designed classes
22 / 81
Adding volume() Method to Box Class
class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
[Link]("Volume is ");
[Link](width * height * depth);
}}
class BoxDemo3 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to instance variables
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;
// display volume
[Link]();
[Link]();
}}
23 / 81
Program Output and Analysis
Program Output:
Volume is 3000.0
Volume is 162.0
Key Code Analysis:
[Link](); - invokes volume() method on mybox1
[Link](); - invokes volume() method on mybox2
Same output as previous version but better design
Important Note:
This generates the same output as the previous version
But represents much better object-oriented design.
24 / 81
Understanding Method Calls
Method Call Mechanism:
When [Link]() is executed:
1 Java runtime system transfers control to volume() code
2 Statements inside volume() execute
3 Control returns to calling routine
4 Execution resumes with line following the call
Methods as Subroutines:
In the most general sense, methods are Java’s way of implementing
subroutines
Provide modular code organization
Enable code reuse and structured programming
Concept Clarification:
If unfamiliar with method calling concepts, take time to experiment
Method invocation, parameters, and return values are fundamental
These concepts are essential to Java programming
25 / 81
Instance Variable Access in Methods
Key Observation in volume() Method:
Instance variables width, height, and depth are referenced directly
No object name or dot operator needed inside the method
This is a very important concept to understand
Better Approach:
Have volume() compute the volume
Return the result to the caller
Caller can then decide what to do with the value
Much more flexible and reusable design
Efficiency Note:
Actually no need for the vol variable
Can use method call directly in println() statement
29 / 81
Direct Method Use in Expressions
More Efficient Approach:
[Link]("Volume is " + [Link]());
What Happens:
When println() is executed
[Link]() is called automatically
Its return value is passed directly to println()
No intermediate variable needed
Key Understanding:
Methods that return values can be used anywhere their return type is
expected.
30 / 81
Need for Parameters in Methods
Method Generalization:
While some methods don’t need parameters, most do
Parameters allow a method to be generalized
Parameterized method can operate on variety of data
Can be used in number of slightly different situations
Key Benefits:
Single method works with different input values
No need to write separate methods for each possible value
Method behavior adapts based on input parameters
Demonstrates power of parameterized methods 32 / 81
Parameters vs Arguments - Important Distinction
Parameter:
Variable defined by a method that receives a value when method is
called
Example: In square(int i), i is a parameter
Part of method definition/declaration
Acts as placeholder for incoming values
Argument:
Value that is passed to a method when it is invoked
Example: In square(100), 100 is an argument
Actual data provided at method call time
Gets copied into corresponding parameter
Relationship:
When method called, argument values copied to parameters
Inside square(), parameter i receives the argument value
This copying mechanism is fundamental to method operation
33 / 81
Improving Box Class with Parameters
Current Problem with Box Initialization:
Dimensions must be set separately with sequence of statements:
[Link] = 10;
[Link] = 20;
[Link] = 15;
Better Solution:
Create method that takes dimensions as parameters
Sets each instance variable appropriately
34 / 81
Provides controlled access to object data
Box Class with setDim() Method
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}}
class BoxDemo5 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
[Link](10, 20, 15);
[Link](3, 6, 9);
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}} 35 / 81
Understanding setDim() Method Operation
Method Call Analysis:
When [Link](10, 20, 15); is executed:
10 is copied into parameter w
20 is copied into parameter h
15 is copied into parameter d
Constructor’s Job:
Initialize object’s internal state
Ensure object is fully usable immediately after creation
Set object data to known, valid state
Perform necessary setup operations
Default Constructor:
Java provides one if no explicit constructor is defined
Initializes instance variables to default values:
Numeric: 0, Reference: null, Boolean: false
Defining your own constructor overrides default
38 / 81
Simple Constructor Example
// Box class with constructor
class Box {
double width, height, depth;
// Constructor
Box() {
[Link]("Constructing Box");
width = 10; height = 10; depth = 10;
}
// Compute volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Constructor Execution and Output
Program Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
What Happened:
Both mybox1 and mybox2 initialized by Box() constructor
Constructor called automatically when objects created
All boxes get same dimensions (10 × 10 × 10)
println() in constructor for illustration only
Understanding the new Operator:
new Box() is actually calling the Box() constructor
Parentheses after class name are constructor call
This explains why parentheses needed after class name
Box mybox1 = new Box(); creates and initializes object
Most constructors don’t display anything - they just initialize objects
40 / 81
Parameterized Constructors
Problem with Simple Constructor:
All boxes have same dimensions
Not flexible for real-world use
Need objects with different dimensions
Solution: Parameterized Constructor
// Box class with parameterized constructor
class Box {
double width, height, depth;
double volume() {
return width * height * depth;
}
}
Key Benefits:
Objects can have unique dimensions
Parameters provide initialization values
More flexible than fixed-dimension constructor
41 / 81
Using Parameterized Constructor
Program Output:
Volume is 3000.0
Volume is 162.0
What Happens:
Values passed to constructor: 10, 20, 15 → mybox1
Constructor copies them to width, height, depth
mybox1 dimensions become 10, 20, 15
Each object initialized as specified by constructor
42 / 81
Understanding the ’this’ Keyword
What is ’this’ ?
Keyword that refers to the object that invoked the current method
Always a reference to the current object
Can be used anywhere a reference to object of current class type is
permitted
Provides way for method to refer to invoking object
Context Sensitivity:
this always refers to the invoking object within a method
Different objects calling same method get different this references
Each method invocation has its own this context
43 / 81
Basic this Usage Example
Analysis:
Works same as version without this (redundant here)
Inside constructor, this always refers to invoking object
[Link] explicitly references object’s variable
When Redundant:
No naming conflicts
Context makes reference clear
Simple cases without ambiguity
When Useful:
Resolving parameter vs. instance variable conflicts
Making code explicit and self-documenting
Certain advanced programming scenarios
44 / 81
Instance Variable Hiding
The Problem:
Local variables (including parameters) can have same names as instance variables
Local variable ”hides” instance variable in its scope
Why Parameters Named Differently:
Earlier examples used different names (w, h, d) to avoid hiding
Using same names without this would refer to parameters
Two Solutions:
1 Use different parameter names
2 Use this to access instance variables explicitly
Programmer Preferences:
Some avoid hiding for clarity
Others use same names and resolve with this
Choice depends on style/team convention
45 / 81
Using ’this’ to Resolve Name Conflicts
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
[Link] = width;
[Link] = height;
[Link] = depth;
}
How This Works:
Parameters named width, height, depth
Same names as instance variables
[Link] refers to instance variable
width (without this) refers to parameter
Assignment copies parameter value to instance variable
Benefits of This Approach:
Parameter names clearly indicate their purpose
More intuitive - width parameter sets width instance variable
Self-documenting code
Common in professional Java code 46 / 81
Caution:
Can be confusing initially
Requires careful attention to this usage
Easy to accidentally omit this and reference wrong variable
Memory Management in Java
The Question:
Objects dynamically allocated using new operator
How are objects destroyed and memory released?
What happens to memory when objects no longer needed?
Programmer Benefits:
No need to worry about memory deallocation in most cases
Reduces programming errors
Eliminates memory leaks from forgotten deallocations
Simplifies program development 48 / 81
Reference Lifecycle:
Objects exist while at least one reference points to them
Last reference removed → object eligible for GC
GC runs automatically; programmer cannot force it
Memory Management Strategy:
Create objects via new as needed
Use objects through references
Optionally set references to null when done
Rely on GC for cleanup
49 / 81
Garbage Collection Best Practices
Key Points:
GC is automatic; focus on proper object usage
Large-scale or memory-intensive apps need awareness
Avoid unnecessary object creation in loops
Set large object references to null when done
JVM handles memory efficiently; trust GC
Advanced Considerations:
GC algorithms and tuning differ across JVMs
Usually not needed for basic programming
50 / 81
Complete Class Example: Stack
Real-World Class Benefits:
Encapsulation of data and manipulation code
Methods define consistent, controlled interface
Internal details can change without affecting external code
Class acts like a ”data engine”
Stack Characteristics:
Stores data using first-in, last-out ordering
Like stack of plates - first down, last used
Two primary operations: push and pop
Push: Put item on top of stack
Pop: Take item from top of stack
Encapsulation Benefits:
Stack implementation details hidden from users
Could change from array to linked list without affecting interface
push() and pop() methods remain the same
Internal storage mechanism irrelevant to stack users 51 / 81
Stack Class Implementation
int pop() {
if (tos < 0) { [Link]("Stack underflow"); return 0; }
else return stck[tos--];
}
}
52 / 81
Stack Class Analysis
Class Components:
Data: stck array (holds integers), tos variable (top of stack index)
Constructor: Stack() initializes tos to -1 (empty stack)
Methods: push() and pop() for stack operations
Method Details:
push(): Adds item if stack not full, otherwise shows error
pop(): Removes and returns top item if stack not empty
Error handling built into both methods
Encapsulation Success:
Stack held in array, but this detail hidden from users
Users only interact through push() and pop()
Internal representation could change without affecting interface
Could use linked list, different array size, etc.
Key Insight:
Interface (methods) remains constant
Implementation details can vary
This is power of object-oriented programming 53 / 81
Using the Stack Class
class TestStack {
public static void main(String[] args) {
Stack s1 = new Stack();
Stack s2 = new Stack();
for(int i=0;i<10;i++) [Link](i);
for(int i=10;i<20;i++) [Link](i);
[Link]("Stack in s1:");
for(int i=0;i<10;i++) [Link]([Link]());
[Link]("Stack in s2:");
for(int i=0;i<10;i++) [Link]([Link]());
}}
/* Output:
Stack in s1: Stack in s2:
9 19
8 18
7 17
6 16
5 15
4 14
3 13
2 12
1 11
0 10 54 / 81
*/