Heterogram Word in Java | ISC Computer Science 2025 Theory

A class Flipgram has been defined to flip the letters of the left and right halves of a non-heterogram word. If the word has odd number of characters, then the middle letter remains at its own position.

A heterogram is a word where no letter appears more than once.

Example 1:
INPUT: BETTER
OUTPUT: TERBET

Example 2:
INPUT: NEVER
OUTPUT: ERVNE

Example 3:
INPUT: THAN
OUTPUT: HETEROGRAM

The details of the members of the class are given below:

Class name: Flipgram
Data member/instance variable:
word: to store a word
Methods/Member functions:
Flipgram(String s): parameterized constructor to assign word = s
boolean ishetero(): to return true if word is a heterogram else return false
String flip(): to interchange the left and right sides of a non-heterogram word and return the resultant word
void display(): to print the flipped word for a non-heterogram word by invoking the method flip(). An appropriate message should be printed for a heterogram word.

Specify the class Flipgram giving the details of the constructor, boolean ishetero(), String flip() and void display(). Define a main() function to create an object and call the functions accordingly to enable the task.

import java.util.Scanner;
class Flipgram{
    String word;
    public Flipgram(String s){
        word = s;
    }
    public boolean ishetero(){
        for(int i = 0; i < word.length() - 1; i++){
            char ch = word.charAt(i);
            String s = word.substring(i + 1);
            if(s.indexOf(ch) >= 0)
                return false;
        }
        return true;
    }
    public String flip(){
        int len = word.length();
        if(len % 2 == 0){
            String a = word.substring(0, len / 2);
            String b = word.substring(len / 2);
            return b + a;
        }
        else{
            String a = word.substring(0, len / 2);
            String b = word.substring(len / 2 + 1);
            return b + word.charAt(len / 2) + a;
        }
    }
    public void display(){
        if(ishetero())
            System.out.println("HETEROGRAM");
        else
            System.out.println(flip().toUpperCase());
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the word: ");
        String w = in.next();
        Flipgram obj = new Flipgram(w);
        obj.display();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *