Exercise - 2
a) Write a JAVA program using StringBuffer to delete, remove character.
import java.util.Scanner;
public class StringBufferExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input original string
System.out.println("Enter a string:");
String input = scanner.nextLine();
// Create a StringBuffer object
StringBuffer stringBuffer = new StringBuffer(input);
// Display original string
System.out.println("Original String: " + stringBuffer);
// Delete a portion of the string
System.out.println("Enter start and end index to delete (0-based index):");
int start = scanner.nextInt();
int end = scanner.nextInt();
// Deleting substring
if (start >= 0 && end <= stringBuffer.length() && start < end) {
stringBuffer.delete(start, end);
System.out.println("String after deletion: " + stringBuffer);
} else {
System.out.println("Invalid indices for deletion.");
}
// Remove a specific character
System.out.println("Enter the character to remove:");
char charToRemove = scanner.next().charAt(0);
for (int i = 0; i < stringBuffer.length(); i++) {
if (stringBuffer.charAt(i) == charToRemove) {
stringBuffer.deleteCharAt(i);
i--; // Adjust index after removal
}
}
// Display final string
System.out.println("String after removing character '" + charToRemove +
"': " + stringBuffer);
scanner.close();
}
}
Example Input/Output:
Input:
Enter a string:
hello world
Enter start and end index to delete (0-based index):
6 11
Enter the character to remove:
o
Output:
Original String: hello world
String after deletion: hello
String after removing character 'o': hell
b) Write a JAVA program to implement class mechanism. Create a class,
methods and invoke
them inside main method.
// Class to represent a Person
class Person {
// Fields (attributes)
private String name;
private int age;
// Constructor to initialize the Person object
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display the person's details
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
// Method to check if the person is an adult
public boolean isAdult() {
return age >= 18;
}
// Method to set a new age
public void setAge(int newAge) {
if (newAge > 0) {
age = newAge;
} else {
System.out.println("Invalid age. Age must be positive.");
}
}
}
public class ClassMechanismExample {
public static void main(String[] args) {
// Create an object of the Person class
Person person1 = new Person("Alice", 25);
// Invoke methods on the object
System.out.println("Person Details:");
person1.displayDetails();
// Check if the person is an adult
if (person1.isAdult()) {
System.out.println(person1.name + " is an adult.");
} else {
System.out.println(person1.name + " is not an adult.");
}
// Update the age of the person
System.out.println("\nUpdating age...");
person1.setAge(17);
// Display updated details
person1.displayDetails();
// Check again if the person is an adult
if (person1.isAdult()) {
System.out.println(person1.name + " is an adult.");
} else {
System.out.println(person1.name + " is not an adult.");
}
}
}
Example Output:
Initial Details:
Person Details:
Name: Alice
Age: 25
Alice is an adult.
After Updating Age:
Updating age...
Person Details:
Name: Alice
Age: 17
Alice is not an adult.
1. Class and Object
java
Copy code
// Define a class
class Car {
// Fields
String brand;
String model;
int year;
// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Method to display car details
public void displayDetails() {
System.out.println("Car Brand: " + brand);
System.out.println("Car Model: " + model);
System.out.println("Year: " + year);
}
}
public class ClassAndObjectExample {
public static void main(String[] args) {
// Create an object of the Car class
Car car1 = new Car("Toyota", "Corolla", 2022);
// Call method on the object
car1.displayDetails();
}
}
2. Abstraction
java
Copy code
// Abstract class
abstract class Animal {
// Abstract method
public abstract void sound();
// Concrete method
public void sleep() {
System.out.println("The animal is sleeping.");
}
}
// Concrete subclass
class Dog extends Animal {
@Override
public void sound() {
System.out.println("The dog barks: Woof Woof!");
}
}
public class AbstractionExample {
public static void main(String[] args) {
// Create an object of the Dog class
Animal dog = new Dog();
dog.sound();
dog.sleep();
}
}
3. Encapsulation
java
Copy code
class BankAccount {
// Private fields
private String accountHolder;
private double balance;
// Constructor
public BankAccount(String accountHolder, double balance) {
this.accountHolder = accountHolder;
this.balance = balance;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Setter to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Invalid deposit amount!");
}
}
// Setter to withdraw money
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient funds or invalid amount!");
}
}
}
public class EncapsulationExample {
public static void main(String[] args) {
BankAccount account = new BankAccount("Alice", 5000.0);
// Access the balance through getter
System.out.println("Initial Balance: " + account.getBalance());
// Deposit and withdraw using setters
account.deposit(2000);
account.withdraw(1500);
// Check updated balance
System.out.println("Final Balance: " + account.getBalance());
}
}
4. Inheritance
java
Copy code
// Base class
class Vehicle {
String brand = "Ford";
public void honk() {
System.out.println("Vehicle is honking: Beep Beep!");
}
}
// Derived class
class Car extends Vehicle {
String model = "Mustang";
public void displayDetails() {
System.out.println("Brand: " + brand + ", Model: " + model);
}
}
public class InheritanceExample {
public static void main(String[] args) {
Car car = new Car();
car.honk(); // Inherited method
car.displayDetails(); // Subclass-specific method
}
}
5. Polymorphism
java
Copy code
// Parent class
class Shape {
public void draw() {
System.out.println("Drawing a shape...");
}
}
// Child class 1
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle...");
}
}
// Child class 2
class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle...");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
// Polymorphism: Parent reference, child objects
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
// Call the overridden methods
shape1.draw();
shape2.draw();
}
}
Output Examples:
1. Class and Object:
yaml
Copy code
Car Brand: Toyota
Car Model: Corolla
Year: 2022
2. Abstraction:
csharp
Copy code
The dog barks: Woof Woof!
The animal is sleeping.
3. Encapsulation:
yaml
Copy code
Initial Balance: 5000.0
Deposited: 2000
Withdrawn: 1500
Final Balance: 5500.0
4. Inheritance:
yaml
Copy code
Vehicle is honking: Beep Beep!
Brand: Ford, Model: Mustang
5. Polymorphism:
css
Copy code
Drawing a circle...
Drawing a rectangle...