Ad Code

Write a Java program to perform following string operations 1.Length2.Copy3.Contatenation 4.Compare5.Reverse

import java.util.Scanner;

public class StringOperations {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input two strings
        System.out.print("Enter the first string: ");
        String str1 = scanner.nextLine();

        System.out.print("Enter the second string: ");
        String str2 = scanner.nextLine();

        // 1. Length
        int length1 = str1.length();
        int length2 = str2.length();
        System.out.println("Length of String 1: " + length1);
        System.out.println("Length of String 2: " + length2);

        // 2. Copy
        String copyStr1 = str1;
        System.out.println("Copy of String 1: " + copyStr1);

        // 3. Concatenation
        String concatStr = str1.concat(str2);
        System.out.println("Concatenation of String 1 and String 2: " + concatStr);

        // 4. Compare
        int compareResult = str1.compareTo(str2);
        if (compareResult == 0) {
            System.out.println("String 1 and String 2 are equal.");
        } else if (compareResult < 0) {
            System.out.println("String 1 comes before String 2.");
        } else {
            System.out.println("String 1 comes after String 2.");
        }

        // 5. Reverse
        StringBuilder reverseStr1 = new StringBuilder(str1).reverse();
        System.out.println("Reverse of String 1: " + reverseStr1);

        scanner.close();
    }
}

Reactions

Post a Comment

0 Comments