Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Piglatin (OOP)

Updated 21 Oct 2026

This program converts a sentence into Pig Latin using a class whose parameterised constructor receives the sentence. Each method does one job: checking the sentence, cutting out the words, testing a vowel, converting a word and building the final sentence. Words are extracted with charAt() and substring() only, with no split() or StringTokenizer.

Definition

In Pig Latin a word that begins with a vowel (A, E, I, O, U) gets AY added at the end. Any other word has its leading consonants, up to the first vowel, moved to the end and then AY is added.

  • OPEN becomes OPENAY.
  • THE becomes ETHAY (TH moves to the end).
  • RHYTHM has no vowel, so it becomes RHYTHMAY.

Decisions made in this program:

  • The sentence is converted to upper case and printed in upper case.
  • Y is not a vowel.
  • A word with no vowel just gets AY added.
  • At most 50 words are stored; extra words are ignored.
  • Anything that is not a space, including commas and digits, stays inside the word and counts as a consonant.

Algorithm

  1. main reads the sentence into s and creates the object with new PigLatin(s). The constructor stores the trimmed, upper-case sentence in sent, creates words with 50 elements and sets count to 0.
  2. isValid() returns true if sent has at least 2 characters and ends with ., ? or !. If not, main prints INVALID INPUT.
  3. extractWords() scans sent up to the terminator. It adds each non-space character to w; at a space it stores w in words[count] (when w is not empty) and clears w. The last word is stored after the loop.
  4. convertWord(w) finds the index p of the first vowel using isVowel().
    • If p is 0 it returns w + "AY".
    • Otherwise it returns w.substring(p) + w.substring(0, p) + "AY". With no vowel, p equals the length and the word comes back unchanged before AY.
  5. convertSentence() converts every stored word, separates them by single spaces, adds the terminator and returns the new sentence, which main prints.

Program

The constructor takes the sentence. isValid() and isVowel() return boolean, convertWord() and convertSentence() return the converted text, and main does all the input and output.

import java.util.*;

/**
 * Class PigLatin (OOP version): the sentence is passed to the parameterised
 * constructor; each method does one job. A vowel word gets "AY" at the end;
 * otherwise the leading consonants (up to the first vowel) move to the end
 * and "AY" is added.
 */
public class PigLatin
{
    String sent;      // the sentence (upper case, trimmed)
    String words[];   // the words of the sentence, one per element
    int count;        // number of words stored in words[]

    /**
     * Parameterised constructor.
     * @param s the sentence typed by the user
     */
    PigLatin(String s)
    {
        sent = s.trim().toUpperCase();   // ISC input is usually upper case
        words = new String[50];          // room for at most 50 words
        count = 0;
    }

    /**
     * Checks the sentence.
     * @return true if it has a character before the terminator and ends
     *         with '.', '?' or '!'; otherwise false
     */
    boolean isValid()
    {
        int len = sent.length();
        if (len < 2)
            return false;
        char last = sent.charAt(len - 1);   // terminator
        return last == '.' || last == '?' || last == '!';
    }

    /**
     * Extracts the words without split/StringTokenizer and stores them in
     * words[]. Extra spaces between words are skipped.
     */
    void extractWords()
    {
        String w = "";                  // word being built
        int len = sent.length() - 1;    // stop before the terminator
        for (int i = 0; i < len; i++)
        {
            char ch = sent.charAt(i);
            if (ch != ' ')
                w = w + ch;             // letter: add to current word
            else if (!w.equals(""))     // space ends a word: store it
            {
                if (count < words.length)
                    words[count++] = w;
                w = "";
            }
        }
        if (!w.equals("") && count < words.length)   // last word
            words[count++] = w;
    }

    /**
     * Checks for a vowel (Y is not a vowel here).
     * @param c the character to test
     * @return true if c is A, E, I, O or U
     */
    boolean isVowel(char c)
    {
        return "AEIOU".indexOf(c) >= 0;
    }

    /**
     * Converts one word to Pig Latin.
     * @param w the word (upper case)
     * @return the Pig Latin word; a word with no vowel just gets AY added
     */
    String convertWord(String w)
    {
        int p = 0;                                  // index of the first vowel
        while (p < w.length() && !isVowel(w.charAt(p)))
            p++;                                    // skip leading consonants
        if (p == 0)
            return w + "AY";                        // begins with a vowel
        return w.substring(p) + w.substring(0, p) + "AY";   // p == length: whole word moves, so w + "AY"
    }

    /**
     * Converts all the stored words.
     * @return the Pig Latin sentence with single spaces and the terminator
     */
    String convertSentence()
    {
        String res = "";                            // converted sentence
        for (int i = 0; i < count; i++)
        {
            res = res + convertWord(words[i]);
            if (i < count - 1)
                res = res + " ";                    // single space between words
        }
        return res + sent.charAt(sent.length() - 1);   // add the terminator
    }

    /** main: reads the sentence, creates the object and calls the methods. */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String s = sc.nextLine();               // sentence typed by the user
        PigLatin ob = new PigLatin(s);
        if (ob.isValid())
        {
            ob.extractWords();
            System.out.println(ob.convertSentence());
        }
        else
            System.out.println("INVALID INPUT");
    }
}

Variable description table

VariableData TypePurpose
sentStringData member: the sentence, trimmed and in upper case
wordsString[]Data member: array holding the words of the sentence (50 elements)
countintData member: number of words stored in words[]
sStringIn the constructor: parameter holding the sentence typed by the user. In main: the line read from the keyboard
lenintIn isValid(): length of sent. In extractWords(): index of the terminator, where the loop stops
lastcharIn isValid(): the last character of sent, tested as the terminator
wStringIn extractWords(): the word being built. In convertWord(): parameter, the word to convert
iintLoop counter in extractWords() (index in sent) and convertSentence() (index in words[])
chcharCurrent character of sent in extractWords()
ccharParameter of isVowel(): the character being tested
pintIn convertWord(): index of the first vowel
resStringIn convertSentence(): the converted sentence built so far
scScannerReads the sentence from the keyboard in main
argsString[]Command line arguments of main (not used)
obPigLatinObject created in main to call the methods

Sample input and output

Sample 1

Enter a sentence:
Open the door.
OPENAY ETHAY OORDAY.

Sample 2

Enter a sentence:
The   quick brown fox is here!
ETHAY UICKQAY OWNBRAY OXFAY ISAY EREHAY!

Sample 3

Enter a sentence:
Why try rhythm?
WHYAY TRYAY RHYTHMAY?

Sample 4

Enter a sentence:
Hello world
INVALID INPUT

One value per line

Dry run

Input Why try rhythm? The constructor makes sent = WHY TRY RHYTHM? (15 characters) and isValid() returns true. In extractWords() len = 14, so the loop runs for i = 0 to 13.

ichw after the stepcount
0 to 2W, H, YWHY0
3spacestored in words[0], w = empty1
4 to 6T, R, YTRY1
7spacestored in words[1], w = empty2
8 to 13R, H, Y, T, H, MRHYTHM2
after loopRHYTHM stored in words[2]3

convertSentence() calls convertWord() for each word. None of them has a vowel, because Y is not a vowel, so p runs to the length of the word.

WordpResult
WHY3empty + WHY + AY = WHYAY
TRY3empty + TRY + AY = TRYAY
RHYTHM6empty + RHYTHM + AY = RHYTHMAY

With single spaces and the terminator ? the returned sentence is WHYAY TRYAY RHYTHMAY?, the same as the real run above.

Variations

  1. Reverse each word "Write a program to accept a sentence and reverse every word of it, keeping the order of the words."
  2. Longest word "Write a program to accept a sentence and display the number of words and the longest word."
  3. Capitalise words "Write a program to accept a sentence and change the first letter of every word to upper case."