231ALC302T - Object Oriented Programming Using Java
UNIT II :METHODS AND STRING HANDLING 9
Defining Classes and Creating Objects- Methods - this keyword - Method
Overloading - Constructors and Constructor Overloading - Static Members - Final
keyword - Garbage Collection & finalize() - Strings, StringBuffer and StringBuilder
- Arrays and ArrayList
1. Defining Classes and Creating Objects
● Class: A class in Java is a blueprint for creating objects (instances). It
defines the properties (fields) and behaviors (methods) that the objects will
have.
class Car {
// Fields
String model;
int year;
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
// Method
void displayDetails() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
● Object: An object is an instance of a class. You create an object using the
new keyword.
public class Main {
public static void main(String[] args) {
// Creating an object of Car
Car myCar = new Car("Tesla", 2022);
myCar.displayDetails();
}
}
1
2. Methods
● Method: A method in Java is a block of code that performs a specific task.
class Calculator {
// Method that adds two numbers
int add(int a, int b) {
return a + b;
}
}
● Methods can have parameters, return types, and can be called on objects
or directly via class (if static).
3. The this Keyword
● this keyword is used to refer to the current object. It helps distinguish
between instance variables and local variables when they have the same
name.
class Person {
String name;
Person(String name) {
this.name = name; // 'this.name' refers to the instance variable
}
}
● this() can also be used to call another constructor in the same class
(constructor chaining).
4. Method Overloading
● Method Overloading occurs when a class has multiple methods with the
same name but different parameter lists (number, type, or both).
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
2
5. Constructors and Constructor Overloading
● Constructor: A constructor is a special method used to initialize objects. It
has the same name as the class and no return type.
java
CopyEdit
class Car {
String model;
int year;
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
}
● Constructor Overloading: Like method overloading, constructor
overloading allows multiple constructors with different parameters.
class Car {
String model;
int year;
Car(String model) {
this.model = model;
this.year = 2022; // Default year
}
Car(String model, int year) {
this.model = model;
this.year = year;
}
}
6. Static Members
● Static Fields and Methods: Static members belong to the class, not
instances of the class. They are shared by all objects of the class.
class Counter {
static int count = 0; // Static variable
// Static method
static void increment() {
count++;
}
}
3
public class Main {
public static void main(String[] args) {
Counter.increment();
System.out.println(Counter.count); // Output: 1
}
}
7. Final Keyword
● final can be used with:
o Variables: When applied to variables, the value cannot be changed
(constant).
final int MAX_SPEED = 120;
o Methods: Prevents method overriding.
final void display() {
System.out.println("This is a final method.");
}
o Classes: Prevents inheritance of the class.
java
CopyEdit
final class Car {
// This class cannot be inherited
}
8. Garbage Collection & finalize()
● Garbage Collection: In Java, the JVM automatically manages memory and
frees up memory that is no longer in use (i.e., unreachable objects).
o Objects are garbage collected when they are no longer referenced.
o finalize() method: The finalize() method is called before the garbage
collector deletes an object. It allows cleanup of resources (e.g., closing
files or database connections).
protected void finalize() throws Throwable {
// Cleanup code
super.finalize();
}
● Note: The use of finalize() is not recommended because the timing of
garbage collection is unpredictable.
4
9. Strings, StringBuffer, and StringBuilder
● String: In Java, strings are immutable. Once a String object is created, its
content cannot be changed.
String str = "Hello";
str = str + " World"; // Creates a new string object
● StringBuffer: StringBuffer is mutable and provides methods to modify its
content without creating new objects.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
● StringBuilder: Like StringBuffer, but it is not synchronized (faster in single-
threaded environments).
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
10. Arrays and ArrayList
● Arrays: Arrays in Java are used to store multiple values in a single variable.
Arrays have fixed sizes.
int[] arr = new int[5]; // Array of 5 integers
arr[0] = 10;
arr[1] = 20;
● ArrayList: ArrayList is a part of the java.util package and provides a
dynamic array that can grow as needed.
import java.util.ArrayList;
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
o Advantages of ArrayList over Arrays:
▪ Dynamic size.
▪ Provides built-in methods (e.g., add(), remove(), size()).
▪ Can store objects of any type (via generics).
5
Summary
● Classes & Objects: Classes define objects' properties and behaviors.
● Methods & Overloading: Methods perform tasks; overloading allows
multiple methods with the same name.
● Constructors: Initialize objects.
● Static Members: Shared by all instances of the class.
● Final Keyword: Prevents modification of variables, methods, and classes.
● Garbage Collection: Automatic memory management.
● String Handling: Use String for immutability, StringBuffer/StringBuilder for
mutable strings.
● Arrays & ArrayList: Arrays are fixed size, while ArrayList provides a
dynamic size with useful methods.
1. Introduction to Strings in Java
What is a String?
● A String is a sequence of characters.
● In Java, String is a class in the java.lang package.
● Strings are immutable, meaning their values cannot be changed after they
are created.
🔤 Declaring and Initializing Strings
String s1 = "Hello"; // using string literal
String s2 = new String("World"); // using 'new' keyword
🔧 Common String Methods
Method Description
length() Returns length of string
charAt(int index) Returns char at given index
substring(int, int) Extracts substring
toLowerCase() Converts to lower case
toUpperCase() Converts to upper case
6
Method Description
Compares content (case-
equals()
sensitive)
equalsIgnoreCase
Case-insensitive comparison
()
compareTo() Lexicographical comparison
contains() Checks for sequence
Replaces characters or
replace()
substrings
🔒 String Immutability
String s = "Java";
s.concat(" Programming"); // No change to original string
System.out.println(s); // Output: Java
Explanation: A new String is created, but not assigned.
🔹 2. StringBuffer in Java
🔁 What is StringBuffer?
● A StringBuffer is a mutable sequence of characters.
● Used when you need to make modifications to strings.
● It is synchronized (thread-safe).
🧱 StringBuffer Constructors
java
CopyEdit
StringBuffer sb = new StringBuffer(); // default capacity 16
StringBuffer sb2 = new StringBuffer("Welcome"); // initialized with value
⚙️Common Methods in StringBuffer
Method Description
append(String str) Appends the specified string
insert(int offset, str) Inserts a string at specified index
replace(start, end,
Replaces content between indexes
str)
Deletes characters between
delete(start, end)
indexes
7
Method Description
reverse() Reverses the string
capacity() Current capacity of the buffer
charAt(int index) Character at a specific index
setCharAt(index,
Sets character at given index
char)
🧪 Example:
java
CopyEdit
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb); // Output: Java Programming
🔹 3. StringBuilder in Java
What is StringBuilder?
● Like StringBuffer, but not synchronized.
● Faster than StringBuffer in single-threaded environments.
● Introduced in Java 1.5.
🔧 Methods (Same as StringBuffer)
● append(), insert(), replace(), delete(), reverse(), capacity(), etc.
💡 Example:
java
CopyEdit
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
🔄 4. Differences Table
StringBuff StringBuild
Feature String
er er
Immutabl
Mutability Mutable Mutable
e
Thread-Safe Yes Yes No
Performanc
Low Medium High
e
8
StringBuff StringBuild
Feature String
er er
Package java.lang java.lang java.lang
Introduced
Java 1.0 Java 1.0 Java 1.5
In
📚 5. When to Use What?
Class to
Use Case
Use
Fixed text, no modification String
StringBuffe
Frequent modifications, thread-safe required
r
Frequent modifications, no thread-safety StringBuild
required er
🧪 Sample Exercise for Practice
java
CopyEdit
public class StringTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" is fun");
sb.insert(4, " Programming");
System.out.println(sb.reverse());
}}
Output: nuf si gnimmargorP avaJ