Object Oriented Programming
JAVA
Arrays
• An array is a data structure that stores a fixed-size
sequence of elements of the same type.
Declaration & Initialization
int[ ] numbers = new int[5];
numbers[0] = 10;
Alternative initialization
int[] numbers = {10, 20, 30, 40, 50};
Looping through an array
for(int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
Console Input
• Console input is used to take data from the
user at runtime. In Java, we use the Scanner
class.
import [Link];
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link](); // Reads an integer from the
console
Console Output
• Console output is typically done using the
[Link]() or [Link]()
methods.
[Link]("Hello"); // Prints on the same
line
[Link](" World!"); // Prints and moves
to a new line
Constructors
• A constructor is a special method that is called
when an object is created. It is used to
initialize objects.
Features:
• Same name as the class
• No return type (not even void)
• Can be default, parameterized, or copy
constructor
Methods
• A method is a block of code that performs a
specific task. It helps in reusability and
modular programming.
Syntax:
returnType methodName(parameters) {
// method body
}
Parameter Passing
• In Java, parameter passing is done by value,
meaning a copy of the variable is passed.
Types of Parameters:
• Primitive types: Copy is passed, original is
unchanged
• Objects: Reference copy is passed, object data
can be changed
• Primitive Example:
void increment(int a) {
a = a + 1; // Changes local copy only
}
• Object Example:
void changeName(Student s) {
[Link] = "Updated Name"; // Changes actual object
}
Constructors
• Special method used to initialize objects
• No return type
• Same name as the class
Types:
• Default Constructor
• Parameterized Constructor
Student(String name) {
[Link] = name;
}
Methods
• Block of code that performs a task
• Improves reusability and readability
Syntax:
returnType methodName(parameters) {
// method body
}
Example:
int add(int a, int b) {
return a + b;
}
Parameter Passing
Pass by Value:
• Copies of values are passed
• For primitive types, changes don’t affect
original
Example
void update(int a) {
a = a + 1;
}
Static Fields and Methods
• Static Field: Shared among all instances
• Static Method: Belongs to class, not object
Example:
class Counter {
static int count = 0;
Counter() { count++; }
}
Access Control
Access Modifiers
this Reference
• Refers to current object
• Resolves variable shadowing
• Can return current object
Example:
[Link] = name;
Method Overloading
Same method name, different parameter list
void show(int a)
void show(String b)
Constructor Overloading
Multiple constructors with different parameters
Book() {}
Book(String title) {}
Recursion
• Method calls itself
• Must have a base condition
Example:
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}