EX 2 Java
EX 2 Java
import java.util.Scanner;
// 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.");
}
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:
Example Output:
Initial Details:
Person Details:
Name: Alice
Age: 25
Alice is an adult.
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;
}
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!");
}
}
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;
}
4. Inheritance
java
Copy code
// Base class
class Vehicle {
String brand = "Ford";
// Derived class
class Car extends Vehicle {
String model = "Mustang";
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...");
}
}
Output Examples:
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...