str.
length(); // Get length
str.charAt(0); // Get character at index
str.substring(0, 5); // Substring
str.contains("World"); // Check if contains
str.equals("Hello World"); // Exact match
str.equalsIgnoreCase("hello world"); // Match ignoring case
str.isEmpty(); // Check if empty
str.toUpperCase(); // Uppercase
str.toLowerCase(); // Lowercase
str.trim(); // Remove spaces
str.startsWith("He"); // Starts with
str.endsWith("ld"); // Ends with
str.indexOf("o"); // First index of char
str.lastIndexOf("o"); // Last index of char
str.replace("o", "0"); // Replace chars
str.split(" "); // Split string
String.valueOf(123); // Convert int to String
String.join("-", "A", "B"); // Join strings
str.repeat(3); // Repeat string (Java 11+)
// Main class to run the program
public class OOPExample {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
Animal a3 = new Cow();
a1.makeSound(); // Polymorphism
a2.makeSound();
a3.makeSound();
Zoo zoo = new Zoo();
zoo.addAnimal(a1);
zoo.addAnimal(a2);
zoo.addAnimal(a3);
zoo.showAllSounds();
// Base class
abstract class Animal {
String name;
Animal() {
this.name = this.getClass().getSimpleName();
abstract void makeSound();
// Subclasses
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks: Woof!");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Cat meows: Meow!");
class Cow extends Animal {
void makeSound() {
System.out.println("Cow moos: Moo!");
// Zoo class using encapsulation & composition
import java.util.ArrayList;
class Zoo {
private ArrayList<Animal> animals = new ArrayList<>();
void addAnimal(Animal a) {
animals.add(a);
void showAllSounds() {
for (Animal a : animals) {
a.makeSound();