Computer Applications

Design a class to overload the method display(…..) as follows:

  1. void display(String str, char ch) — checks whether the word str contains the letter ch at the beginning as well as at the end or not. If present, print 'Special Word' otherwise print 'No special word'.
  2. void display(String str1, String str2) — checks and prints whether both the words are equal or not.
  3. void display(String str, int n) — prints the character present at nth position in the word str.

Write a suitable main() method.

Java

User Defined Methods

41 Likes

Answer

public class KboatWordCheck
{
    public void display(String str, char ch) {
        
        String temp = str.toUpperCase();
        ch = Character.toUpperCase(ch);
        int len = temp.length();
        
        if (temp.indexOf(ch) == 0 && 
            temp.lastIndexOf(ch) == (len - 1))
            System.out.println("Special Word");
        else
            System.out.println("No Special Word");
            
    }
    
    public void display(String str1, String str2) {
        
        if (str1.equals(str2))
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
            
    }
    
    public void display(String str, int n) {
        
        int len = str.length();
        
        if (n < 0 || n > len) {
            System.out.println("Invalid value for argument n");
            return;
        }
        
        char ch = str.charAt(n - 1);
        System.out.println(ch);
    }
    
    public static void main(String args[]) {
        KboatWordCheck obj = new KboatWordCheck();
        obj.display("Tweet", 't');
        obj.display("Tweet", "Massachusetts");
        obj.display("Massachusetts", 8);
    }
}

Variable Description Table

Program Explanation

Output

Answered By

12 Likes


Related Questions