KnowledgeBoat Logo
OPEN IN APP

Chapter 15

String Handling

Class 10 - Logix Kips ICSE Computer Applications with BlueJ



Multiple Choice Questions

Question 1

The trim() method of the String class removes ............... .

  1. leading spaces only
  2. trailing spaces only
  3. spaces in between words
  4. leading and trailing spaces

Answer

leading and trailing spaces

Reason — The trim() method of the String class removes the leading and trailing spaces from a string. It does not remove the spaces present in between the string.

Question 2

While using the toLowerCase() method on a string containing special characters, ............... .

  1. the special characters remain unaffected.
  2. the special characters are converted to spaces.
  3. the special characters are converted to null character.
  4. the special characters are removed from the string.

Answer

the special characters remain unaffected

Reason — The toLowerCase() method converts each character in a string to lowercase. However, if the string contains any special character, it remains unchanged.

Question 3

The index of a string ............... .

  1. ranges from 0 to the length -1 of the string
  2. ranges from 0 to the length of the string
  3. ranges from 1 to the length of the string
  4. ranges from 1 to the length -1 of the string

Answer

ranges from 0 to the length -1 of the string

Reason — The index of a string ranges from 0 to the length -1 of the string as a string is similar to a character array whose index starts from 0 to size - 1.

Question 4

The indexOf() method returns the position of the ............... .

  1. first occurrence of the specified character
  2. last occurrence of the specified character
  3. null character
  4. '\n' character

Answer

first occurrence of the specified character

Reason — The indexOf() method returns the index (position) of the first occurrence of the specified character in a string.

Question 5

The return type of the equals() method is ............... .

  1. int
  2. char
  3. boolean
  4. void

Answer

boolean

Reason — The equals() method compares two strings to check whether they are equal or not. The result is a boolean value true if they are equal, otherwise the result is false.

Question 6

Which one of the given statements is true for the following statement? string1.compareTo(string2)

  1. if string1 > string2 the result will be a negative integer i.e. < 0.
  2. if string1 > string2 the result will be a positive integer i.e. > 0.
  3. if string1 > string2 the result will be 0.
  4. None of the above

Answer

if string1 > string2 the result will be a positive integer i.e. > 0.

Reason — The compareTo() method compares two strings lexicographically, and returns a value based on the following logic:

  1. if string1 > string2 the result will be a positive integer, i.e., result > 0
  2. if string1 < string2 the result will be a negative integer, i.e., result < 0
  3. if string1 = string2 the result will be 0, i.e., result = 0

Question 7

Which one of the given statements is true for the following statement? string1.compareTo(string2)

  1. if string1 > string2 the result will be a positive integer i.e. > 0.
  2. if string1 < string2 the result will be a negative integer i.e. < 0.
  3. if string1 = string2 the result will be 0 i.e. = 0.
  4. all of these

Answer

all of these

Reason — The compareTo() method compares two strings lexicographically, and returns a value based on the following logic:

  1. if string1 > string2 the result will be a positive integer, i.e., result > 0
  2. if string1 < string2 the result will be a negative integer, i.e., result < 0
  3. if string1 = string2 the result will be 0, i.e., result = 0

Question 8

The valueOf() method returns the ............... .

  1. string representation of the argument
  2. int representation of the argument
  3. boolean representation of the argument
  4. character representation of the argument

Answer

string representation of the argument

Reason — The valueOf() method returns the string representation of the argument.

Question 9

Output of the following statement is ............... .

System.out.println("SUNDAY".substring(3));

  1. NDA
  2. DAY
  3. SUN
  4. N

Answer

DAY

Reason — The substring() method returns a substring of the given string, which begins with the character at the specified start index and extends to the end of the string.

Here, the start index is 3 so the substring starts from 'D' and continues till the end of the string. So, the substring returned is "DAY".

Question 10

Output of the following statement is ............... .

System.out.println("WONDERFUL".substring(3,4));

  1. DERF
  2. NDER
  3. D
  4. N

Answer

D

Reason — The function substring(start_index, end_index) returns a substring which begins from start_index and ends at end_index - 1.

Here, "WONDERFUL".substring(3,4) returns a substring which begins at start_index 3 and ends at end_index - 1, i.e., 4 - 1 = 3. The character at index 3 is D.

Assignment Questions

Question 1

How do you create strings implicitly and explicitly?

Answer

To create a string implicitly, we write a series of characters enclosed in double quotes. After doing so, the Java compiler implicitly creates an object of the String class and assigns it the value written in double quotes.
For example,
String day = "MONDAY";

To create a string explicitly, we use the keyword — new. There is a constructor in the String class that accepts a string as a parameter and creates a unique string.
For example,
String day = new String("MONDAY");

Question 2(i)

Mention the purpose and syntax of trim() method.

Answer

The trim() method of the String class removes the leading and trailing spaces from a string. It does not remove the spaces present in between the string.
Syntax:
stringObject.trim()

Question 2(ii)

Mention the purpose and syntax of length() method.

Answer

The length() method returns the length of a string. The length is equal to the number of characters present in the string including the white spaces.
Syntax:
stringObject.length()

Question 2(iii)

Mention the purpose and syntax of charAt() method.

Answer

The charAt() method accepts an index number as its argument and returns the character present at that particular index. The index of the string ranges from 0 to length() - 1.
Syntax:
stringObject.charAt(index)

Question 2(iv)

Mention the purpose and syntax of indexOf() method.

Answer

The indexOf() method returns the index of the first occurrence of the specified character (passed as an argument) in a string. If the character is present in the string, the method will return the index number; otherwise, it will return -1.
Syntax:
stringObject.indexOf(char)

Question 2(v)

Mention the purpose and syntax of lastIndexOf() method.

Answer

The lastIndexOf() method returns the index of the last occurrence of the specified character in a string. If the character does not occur in the string, it returns -1.
Syntax:
stringObject.lastIndexOf(char)

Question 2(vi)

Mention the purpose and syntax of equals() method.

Answer

The equals() method compares two strings to check whether they are equal or not. It checks the case of the character as well. The result is a boolean value true if they are equal, otherwise the result is false.
Syntax:
string1.equals(string2)

Question 2(vii)

Mention the purpose and syntax of compareTo() method.

Answer

The compareTo() method compares two strings lexicographically, and returns a value based on the following logic:

  1. if string1 > string2 the result will be a positive integer, i.e., result > 0
  2. if string1 < string2 the result will be a negative integer, i.e., result < 0
  3. if string1 = string2 the result will be 0, i.e., result = 0

Syntax:
string1.compareTo(string2)

Question 2(viii)

Mention the purpose and syntax of compareToIgnore() method.

Answer

The compareToIgnore() method compares two strings lexicographically, ignoring case differences in the strings. It returns a value based on the following logic:

  1. if string1 > string2 the result will be a positive integer, i.e., result > 0
  2. if string1 < string2 the result will be a negative integer, i.e., result < 0
  3. if string1 = string2 the result will be 0, i.e., result = 0

Syntax:
string1.compareToIgnore(string2)

Question 2(ix)

Mention the purpose and syntax of substring() method.

Answer

The substring() method returns a new string that is a substring of the given string. It has two variations:

Syntax:
stringObject.substring(int startindex)

The above method returns a substring beginning from the startindex and extending to the end of the string.

Syntax:
stringObject.substring(int startIndex, int endIndex)

The above method returns a substring beginning from the startindex and extending to the character at index endIndex - 1.

Question 2(x)

Mention the purpose and syntax of valueOf() method.

Answer

The valueOf() method returns the string representation of the argument.
Syntax:
String.valueOf(data)

Here, data can be of various types like char, boolean, int, long, float, double or char array.

Question 3(i)

Differentiate between equals() and compareTo().

Answer

equals()compareTo()
equals() checks if contents of two strings are same or not.compareTo() compares two strings lexicographically.
The result is true if the contents are same otherwise it is false.The result is a negative, positive or zero integer value depending on whether the String object precedes, follows or is equal to the String argument.

Question 3(ii)

Differentiate between equals() and == .

Answer

equals()==
It is a method.It is a relational operator.
It is used to check if the contents of two strings are same or not.It is used to check if two variables refer to the same object in memory.
Example:
String s1 = new String("hello");
String s2 = new String("hello");
boolean res = s1.equals(s2);
System.out.println(res);

The output of this code snippet is true as contents of s1 and s2 are the same.
Example:
String s1 = new String("hello");
String s2 = new String("hello");
boolean res = s1 == s2;
System.out.println(res);

The output of this code snippet is false as s1 and s2 point to different String objects.

Question 3(iii)

Differentiate between startsWith() and endsWith().

Answer

startsWith()endsWith()
startsWith() tests if the string object starts with the string specified as its argument.endsWith() tests if the string object ends with the string specified as its argument.
Example:
String str = "ICSE Computer Applications";
boolean res = str.startsWith("ICSE");
System.out.println(res);

The output of this code is true as str begins with "ICSE".
Example:
String str = "ICSE Computer Applications";
boolean res = str.endsWith("tions");
System.out.println(res);

The output of this code is true as str ends with "tions".

Question 3(iv)

Differentiate between indexOf() and lastIndexOf().

Answer

indexOf()lastIndexOf()
The indexOf() method returns the index of the first occurrence of the specified character in a string.The lastIndexOf() method returns the index of the last occurrence of the specified character in a string.
Example:
String str = "How are you?";
int index = str.indexOf('o');
System.out.println("Index = " + index);

The output is
Index = 1
Example:
String str = "How are you?";
int index = str.lastIndexOf('o');
System.out.println("Index = " + index);

The output is
Index = 9

Question 3(v)

Differentiate between compareTo() and compareToIgnore().

Answer

compareTo()compareToIgnore()
It compares two strings lexicographically.It compares two strings lexicographically, ignoring the case of the characters in a string.
Example:
String str1 = "computer";
String str2 = "COMPUTER";
int res = str1.compareTo(str2);
System.out.println(res);

The output is 32 as 'c' and 'C' are treated differently.
Example:
String str1 = "computer";
String str2 = "COMPUTER";
int res = str1.compareToIgnore(str2);
System.out.println(res);

The output is 0 as case difference is ignored.

Question 4

Write a program to input a sentence and print each word of the string along with its length in tabular form.

import java.util.Scanner;

public class KboatWordsLengthTable
{
   public static void main(String args[]) {
       Scanner in = new Scanner(System.in);
       System.out.println("Enter a sentence:");
       String str = in.nextLine();
             
       str += " ";
       int len = str.length();
       
       String word = "";
       int wLen = 0; 
       System.out.println("Word Length");
       for (int i = 0; i < len; i++) {
           char ch = str.charAt(i);
           if (ch != ' ')   {
               word = word + ch;
               wLen++;
           }
           else {
               System.out.println(word + "\t" + wLen);
               word = "";
               wLen = 0;
               
           }
       }
    }
}
Output
BlueJ output of KboatWordsLengthTable.java

Question 5

Write a program to input a sentence and arrange each word of the string in alphabetical order.

import java.util.Scanner;

public class KboatWordsSort
{
   public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
             
        str += " ";
        int len = str.length();
    
        String word = "";
        int wordCount = 0;
        char ch;
        // calculating no. of words
        for (int i = 0; i < len; i++) 
            if (str.charAt(i) == ' ')   
                wordCount++;
                
        String wordArr[] = new String[wordCount];
        int index = 0;
        // storing words in array
        for (int i = 0; i < len; i++) {
            ch = str.charAt(i);
            if (ch != ' ')   {
                word = word + ch;    
            }
            else {
                wordArr[index++] = word;
                word = "";
            }
        }
        //bubble sort
         for (int i = 0; i < wordCount - 1; i++) {
            for (int j = 0; j < wordCount - i - 1; j++) {
                if (wordArr[j].compareTo(wordArr[j + 1]) > 1) {
                    String t = wordArr[j];
                    wordArr[j] = wordArr[j+1];
                    wordArr[j+1] = t;
                }
            } 
        }
        // printing
        for(int i = 0; i < wordCount; i++)
            System.out.print(wordArr[i] + " ");
    }
}
Output
BlueJ output of KboatWordsSort.java

Question 6

Write a program to input a sentence and arrange words of the string in order of their lengths from shortest to longest.

import java.util.Scanner;

public class KboatWordsSortbyLength
{
   public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
             
        str += " ";
        int len = str.length();
    
        String word = "";
        int wordCount = 0;
        char ch;
        // calculating no. of words
        for (int i = 0; i < len; i++) { 
            if (str.charAt(i) == ' ') {  
                wordCount++;
            }
        }
                
        String wordArr[] = new String[wordCount];
        int index = 0;
        // storing words in array
        for (int i = 0; i < len; i++) {
            ch = str.charAt(i);
            if (ch != ' ')   {
                word = word + ch;
                
            }
            else {
                wordArr[index++] = word;
                word = "";
            }
        }
        //bubble sort
         for (int i = 0; i < wordCount - 1; i++) {
            for (int j = 0; j < wordCount - i - 1; j++) {
                if (wordArr[j].length() > wordArr[j + 1].length()) {
                    String t = wordArr[j];
                    wordArr[j] = wordArr[j+1];
                    wordArr[j+1] = t;
                }
            } 
        }
        // printing
        for(int i = 0; i < wordCount; i++) {
            System.out.print(wordArr[i] + " ");
        }
    }
}
Output
BlueJ output of KboatWordsSortbyLength.java

Question 7

Write a program to input a string in uppercase and print the frequency of each character.
Sample Input : COMPUTER HARDWARE
Sample Output

Character	Frequency
A	            2
C	            1
D	            1
E	            2
H	            1
M	            1   
0	            1
p	            1
R	            1
import java.util.Scanner;

public class KboatLetterFreq
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
        str = str.toUpperCase();
        int freqMap[] = new int[26];
        int len = str.length();
        
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if (Character.isLetter(ch)) {
                int chIdx = ch - 65;
                freqMap[chIdx]++;
            }
        }
        
        System.out.println("Character\tFrequency");
        for (int i = 0; i < freqMap.length; i++) {
            if (freqMap[i] > 0) {
                System.out.println((char)(i + 65) 
                            + "\t\t" + freqMap[i]);
            }
        }
    }
}
Output
BlueJ output of KboatLetterFreq.java

Question 8

Write a program to input a string and print each word of the string in the reverse order.
Sample Input:
Enter a string: My name is Raman
Sample Output
yM eman si namaR

import java.util.Scanner;

public class KboatWordsReverse
{
   public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
             
        str += " ";
        int len = str.length();
    
        String word = "";
        int wLen = 0;
        char ch;

        for (int i = 0; i < len; i++) {
            ch = str.charAt(i);
            if (ch != ' ')   {
                word = word + ch;  
            }
            else {
                wLen = word.length();
                for(int j = wLen - 1; j >= 0; j--) {
                    System.out.print(word.charAt(j));
                }
                System.out.print(' ');
                word = "";
            }
        } 
    }
}
Output
BlueJ output of KboatWordsReverse.java

Question 9

Write a program in Java to accept a string and display the number of uppercase, number of lowercase, number of special characters and number of digits present in the string.

import java.util.Scanner;

public class KboatCount
{
   public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
             
        int len = str.length();
    
        int uc = 0;
        int lc = 0;
        int sc = 0;
        int dc = 0;
        char ch;

        for (int i = 0; i < len; i++) {
            ch = str.charAt(i);
            if (Character.isUpperCase(ch))  
                uc++;    
            else if (Character.isLowerCase(ch))
                lc++;
            else if (Character.isDigit(ch))
                dc++;
            else if (!Character.isWhitespace(ch))
                sc++;
        }
        
        System.out.println("UpperCase Count = " + uc);
        System.out.println("LowerCase Count = " + lc);
        System.out.println("Digit count = " + dc);
        System.out.println("Special Character Count = " + sc);
        
    }
}
Output
BlueJ output of KboatCount.java

Question 10

Write a program to enter a sentence from the keyboard and count the number of times a particular word occurs in it. Display the frequency of the search word.

Sample Input:
Enter a sentence: The quick brown fox jumps over the lazy dog.
Enter a word to search: the

Sample Output:
Search word occurs 2 times

import java.util.Scanner;

public class KboatWordFrequency
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String str = in.nextLine();
        System.out.print("Enter a word to search: ");
        String ipWord = in.nextLine();
        str += " ";
        String word = "";
        int count = 0;
        int len = str.length();

        for (int i = 0; i < len; i++) {
            if (str.charAt(i) == ' ') {

                if (word.equalsIgnoreCase(ipWord))
                    count++ ;

                word = "";
            }
            else {
                word += str.charAt(i);
            }
        }
        
        if (count > 0) {
            System.out.println("Search word occurs " + count + " times.");
        }
        else {
            System.out.println("Search word is not present in sentence.");
        }
        
    }
}
Output
BlueJ output of KboatWordFrequency.java

Question 11

Write a program in Java to enter a string/sentence and display the longest word and the length of the longest word present in the string.

Sample Input:
"Tata football academy will play against Mohan Bagan"

Sample Output:
The longest word: Football
The length of the word: 8

import java.util.Scanner;

public class KboatLongestWord
{
    public static void main(String args[]) {
       Scanner in = new Scanner(System.in);
       System.out.println("Enter a word or sentence:");
       String str = in.nextLine();
       
       str += " "; //Add space at end of string
       String word = "", lWord = "";
       int len = str.length();
       
       for (int i = 0; i < len; i++) {
           char ch = str.charAt(i);
           if (ch == ' ') {
               
                if (word.length() > lWord.length())
                    lWord = word;
                    
                word = "";
           }
           else {
               word += ch;
           }
       }
       
       System.out.println("The longest word: " + lWord +
        ": The length of the word: " + lWord.length());
    }
    
}
Output
BlueJ output of KboatLongestWord.java

Question 12

Write a program to accept a string. Convert the string to uppercase. Count and output the number of double letter sequences that exist in the string.

Sample Input:
"SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE"

Sample Output:
4

import java.util.Scanner;

public class KboatLetterSeq
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter string: ");
        String s = in.nextLine();
        String str = s.toUpperCase();
        int count = 0;
        int len = str.length();
        
        for (int i = 0; i < len - 1; i++) {
            if (str.charAt(i) == str.charAt(i + 1))
                count++;
        }
        
        System.out.println("Double Letter Sequence Count = " + count);
        
    }
}
Output
BlueJ output of KboatLetterSeq.java

Question 13

Write a program to input twenty names in an array. Arrange these names in descending order of alphabets, using the bubble sort technique.

import java.util.Scanner;

public class KboatArrangeNames
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String names[] = new String[20];
        System.out.println("Enter 20 names:");
        for (int i = 0;  i < names.length; i++) {
            names[i] = in.nextLine();
        }

        //Bubble Sort
        for (int i = 0; i < names.length - 1; i++) {
            for (int j = 0; j < names.length - 1 - i; j++) {
                if (names[j].compareToIgnoreCase(names[j + 1]) < 0) {
                    String temp = names[j + 1];
                    names[j + 1] = names[j];
                    names[j] = temp;
                }
            }
        }
        
        System.out.println("\nSorted Names");
        for (int i = 0;  i < names.length; i++) {
            System.out.println(names[i]);
        }
    }
}
Output
BlueJ output of KboatArrangeNames.java

Question 14

Given below is a hypothetical table showing rates of Income Tax for male citizens below the age of 65 years:

Taxable Income (TI)Income Tax Calculation
Does not exceed 1,60,000Nil
Is greater than 1,60,000 and less than or equal to 5,00,000( TI - 1,60,000 ) * 10%
Is greater than 5,00,000 and less than or equal to 8,00,000( (TI - 5,00,000 ) * 20% ) + 34,000
Is greater than 8,00,000( (TI - 8,00,000) * 30%) + 94,000

Write a program to input the age, gender (male or female) and Taxable Income of a person. If the age is more than 65 years or the gender is female, display "wrong category".

If the age is less than or equal to 65 years and the gender is male, compute and display the Income Tax payable as per the table given above.

import java.util.Scanner;

public class KboatIncomeTax
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Gender(male/female): ");
        String gender = in.nextLine();
        System.out.print("Enter Age: ");
        int age = in.nextInt();
        System.out.print("Enter Taxable Income: ");
        double ti = in.nextDouble();
        double tax = 0.0;

        if (age > 65 || gender.equalsIgnoreCase("female")) {
            System.out.print("Wrong Category");
        }
        else {
            if (ti <= 160000)
                tax = 0;
            else if (ti <= 500000)
                tax = (ti - 160000) * 10 / 100;
            else if (ti <= 800000)
                tax = 34000 + ((ti - 500000) * 20 / 100);
            else
                tax = 94000 + ((ti - 800000) * 30 / 100);
                
            System.out.println("Tax Payable: " + tax);
        }      
    }
}
Output
BlueJ output of KboatIncomeTax.java
BlueJ output of KboatIncomeTax.java

Question 15

Write a program to accept the names of 10 cities in a single dimensional string array and their STD (Subscribers Trunk Dialling) codes in another single dimensional integer array. Search for a name of a city input by the user in the list. If found, display "Search Successful" and print the name of the city along with its STD code, or else display the message "Search Unsuccessful, No such city in the list".

import java.util.Scanner;

public class KboatStdCodes
{
    public static void main(String args[]) {
        final int SIZE = 10;
        Scanner in = new Scanner(System.in);
        String cities[] = new String[SIZE];
        String stdCodes[] = new String[SIZE];
        System.out.println("Enter " + SIZE + 
                 " cities and their STD codes:");
        
        for (int i = 0;  i < SIZE; i++) {
            System.out.print("Enter City Name: ");
            cities[i] = in.nextLine();
            System.out.print("Enter its STD Code: ");
            stdCodes[i] = in.nextLine();
        }
        
        System.out.print("Enter name of city to search: ");
        String city = in.nextLine();
        
        int idx;
        for (idx = 0;  idx < SIZE; idx++) {
            if (city.compareToIgnoreCase(cities[idx]) == 0) {
                break;
            }
        }
        
        if (idx < SIZE) {
            System.out.println("Search Successful");
            System.out.println("City: " + cities[idx]);
            System.out.println("STD Code: " + stdCodes[idx]);
        }
        else {
            System.out.println("Search Unsuccessful");
        }
    }
}
Output
BlueJ output of KboatStdCodes.java

Question 16

Write a program to input forty words in an array. Arrange these words in descending order of alphabets, using selection sort technique. Print the sorted array.

import java.util.Scanner;

public class KboatSelectionSort
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String a[] = new String[40];
        int n = a.length;
        
        System.out.println("Enter 40 Names: ");
        for (int i = 0; i < n; i++) {
            a[i] = in.nextLine();
        }
        
        for (int i = 0; i < n - 1; i++) {
            int idx = i;
            for (int j = i + 1; j < n; j++) {
                if (a[j].compareToIgnoreCase(a[idx]) < 0) {
                    idx = j;
                }
            }
            String t = a[idx];
            a[idx] = a[i];
            a[i] = t;
        }
        
        System.out.println("Sorted Names");
        for (int i = 0; i < n; i++) {
            System.out.println(a[i]);
        }
    }
}
Output
BlueJ output of KboatSelectionSort.java

Question 17

Define a class named movieMagic with the following description:

Instance Variables/Data Members:
int year - to store the year of release of a movie
String title - to store the title of the movie.
float rating - to store the popularity rating of the movie.
(minimum rating = 0.0 and maximum rating = 5.0)

Member Methods:
i. movieMagic() - Default constructor to initialise numeric data members to 0 and String data member to "".
ii. void accept() - To input and store year, title and rating.
iii. void display() - To display the title of a movie and a message based on the rating as per the table given below.

RatingMessage to be displayed
0.0 to 2.0Flop
2.1 to 3.4Semi-hit
3.5 to 4.5Hit
4.6 to 5.0Super hit

Write a main method to create an object of the class and call the above member methods.

import java.util.Scanner;

public class movieMagic
{
    private int year;
    private String title;
    private float rating;
    
    public movieMagic() {
        year = 0;
        title = "";
        rating = 0.0f;
    }
    
    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Title of Movie: ");
        title = in.nextLine();
        System.out.print("Enter Year of Movie: ");
        year = in.nextInt();
        System.out.print("Enter Rating of Movie: ");
        rating = in.nextFloat();
    }
    
    public void display() {
        String message = "Invalid Rating";
        if (rating <= 2.0f)
            message = "Flop";
        else if (rating <= 3.4f)
            message = "Semi-Hit";
        else if (rating <= 4.4f)
            message = "Hit";
        else if (rating <= 5.0f)
            message = "Super-Hit";
            
        System.out.println(title);
        System.out.println(message);
    }
    
    public static void main(String args[]) {
        movieMagic obj = new movieMagic();
        obj.accept();
        obj.display();
    }
}
Output
BlueJ output of movieMagic.java

Question 18

Write a program to accept name and total marks of N number of students in two single subscripts array name[] and totalmarks[].

Calculate and print:
i. The average of the total marks obtained by N number of students. [average = (sum of total marks of all the students) / N]

ii. Deviation of each student's total marks with the average. [deviation = total marks of a student - average]

import java.util.Scanner;

public class KboatSDAMarks
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number of students: ");
        int n = in.nextInt();
        
        String name[] = new String[n];
        int totalmarks[] = new int[n];
        int grandTotal = 0;
        
        for (int i = 0; i < n; i++) {
            in.nextLine();
            System.out.print("Enter name of student " + (i+1) + ": ");
            name[i] = in.nextLine();
            System.out.print("Enter total marks of student " + (i+1) + ": ");
            totalmarks[i] = in.nextInt();
            grandTotal += totalmarks[i];
        }
        
        double avg = grandTotal / (double)n;
        System.out.println("Average = " + avg);
        
        for (int i = 0; i < n; i++) {
            System.out.println("Deviation for " + name[i] + " = " 
            + (totalmarks[i] - avg));
        }
    }
}
Output
BlueJ output of KboatSDAMarks.java

Question 19

Design a class RailwayTicket with the following description:

Instance Variables/Data Members:

String name: to store the name of the customer.
String coach: to store the type of coach customer wants to travel in.
long mobno: to store customer's mobile number.
int amt: to store basic amount of ticket.
int totalamt: to store the amount to be paid after updating the original amount.

Methods:

void accept(): to take input for name, coach, mobile number and amount.
void update(): to update the amount as per the coach selected.

Extra amount to be added in the amount as follows:

Type of coachesAmount
First_AC700
Second_AC500
Third_AC250
SleeperNone

void display(): To display all details of a customer such as name, coach, total amount and mobile number.

Write a main() method to create an object of the class and call the above methods.

import java.util.Scanner;

public class RailwayTicket
{
    private String name;
    private String coach;
    private long mobno;
    private int amt;
    private int totalamt;
    
    private void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter name: ");
        name = in.nextLine();
        System.out.print("Enter coach: ");
        coach = in.nextLine();
        System.out.print("Enter mobile no: ");
        mobno = in.nextLong();
        System.out.print("Enter amount: ");
        amt = in.nextInt();
    }
    
    private void update() {
        if(coach.equalsIgnoreCase("First_AC"))
            totalamt = amt + 700;
        else if(coach.equalsIgnoreCase("Second_AC"))
            totalamt = amt + 500;
        else if(coach.equalsIgnoreCase("Third_AC"))
            totalamt = amt + 250;
        else if(coach.equalsIgnoreCase("Sleeper"))
            totalamt = amt;
    }
    
    private void display() {
        System.out.println("Name: " + name);
        System.out.println("Coach: " + coach);
        System.out.println("Total Amount: " + totalamt);
        System.out.println("Mobile number: " + mobno);
    }
    
    public static void main(String args[]) {
        RailwayTicket obj = new RailwayTicket();
        obj.accept();
        obj.update();
        obj.display();
    }
}
Output
BlueJ output of RailwayTicket.java

Question 20

Design a class to overload a function check() as follows:

  1. void check(String str, char ch) - to find and print the frequency of a character in a string.
    Example:
    Input:
    Str = "success"
    ch= 's'
    Output:
    Number of s present is = 3
  2. void check (String s1) - to display only vowels from string s1, after converting it to lowercase.
    Example:
    Input:
    S1= "computer"
    Output: o u e
public class KboatOverload
{
    void check (String str , char ch ) {
        int count = 0;
        int len = str.length();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (ch == c) {
                count++;
            }
        }
        System.out.println("Frequency of " + ch + " = " + count);
    }
    
    void check(String s1) {
        String s2 = s1.toLowerCase();
        int len = s2.length();
        System.out.println("Vowels:");
        for (int i = 0; i < len; i++) {
            char ch = s2.charAt(i);
            if (ch == 'a' ||
                ch == 'e' ||
                ch == 'i' ||
                ch == 'o' ||
                ch == 'u')
                System.out.print(ch + " ");
        }
    }
}
Output
BlueJ output of KboatOverload.java
BlueJ output of KboatOverload.java

Question 21

Design a class to overload a function Joystring() as follows:

  1. void Joystring(String s, char ch1, char ch2) with one string argument and two character arguments that replaces the character argument ch1 with the character argument ch2 in the given string s and prints the new string.
    Example:
    Input value of s = "TECHNALAGY"
    ch1 = 'A',
    ch2='O'
    Output: "TECHNOLOGY"
  2. void Joystring(String s) with one string argument that prints the position of the first space and the last space in the given string s.
    Example:
    Input value of s = "Cloud computing means Internet based computing"
    Output:
    First index : 5
    Last index : 36
  3. void Joystring (String s1, String s2) with two string arguments that combines the two strings with a space between them and prints the resultant string.
    Example:
    Input value of s1 ="COMMON WEALTH"
    Input value of s2 = "GAMES"
    Output: COMMON WEALTH GAMES

(use library functions)

public class KboatStringOverload
{
    public void joystring(String s, char ch1, char ch2) {
        String newStr = s.replace(ch1, ch2);
        System.out.println(newStr);
    }
    
    public void joystring(String s) {
        int f = s.indexOf(' ');
        int l = s.lastIndexOf(' ');
        System.out.println("First index:  " + f);
        System.out.println("Last index:  " + l);
    }
    
    public void joystring(String s1, String s2) {
        String newStr = s1.concat(" ").concat(s2);
        System.out.println(newStr);
    }
    
    public static void main(String args[]) {
        KboatStringOverload obj = new KboatStringOverload();
        obj.joystring("TECHNALAGY", 'A', 'O');
        obj.joystring("Cloud computing means Internet based computing");
        obj.joystring("COMMON WEALTH", "GAMES");
    }
}
Output
BlueJ output of KboatStringOverload.java

Question 22

Design a class to overload a function num_calc() as follows:

  1. void num_calc(int mini, char ch) with one integer argument and one character argument, computes the square of integer argument if choice ch is 's' otherwise finds its cube.
  2. void num_calc (int a, int b, char ch) with two integer arguments and one character argument. It computes the product of integer arguments if ch is 'p' else adds the integers.
  3. void num_calc (String s1, String s2) with two string arguments, which prints whether the strings are equal or not.
import java.util.Scanner;

public class KboatChoiceOverload
{
    void num_calc(int mini, char ch) {
        if (ch == 's') {
            long sq = mini * mini;
            System.out.println("Square = " + sq );
        }
        else {
            long cube = mini * mini * mini;
            System.out.println("Cube = " + cube);
        }
    }
    
    void num_calc(int a, int b, char ch) {
        if (ch == 'p') {
            long prod = a * b;
            System.out.println("Product = " + prod );
        }
        else {
            long sum = a + b;
            System.out.println("Sum = " + sum);
        }
    }
    
    void num_calc(String s1, String s2)    {
        if(s1.equals(s2))   
            System.out.println("Strings are equal");
        else
            System.out.println("Strings are not equal");
    }
    
}
Output
BlueJ output of KboatChoiceOverload.java
BlueJ output of KboatChoiceOverload.java
BlueJ output of KboatChoiceOverload.java
BlueJ output of KboatChoiceOverload.java
BlueJ output of KboatChoiceOverload.java
BlueJ output of KboatChoiceOverload.java

Question 23

Design a class to overload a function compare( ) as follows:

  1. void compare(int, int) - to compare two integer values and print the greater of the two integers.
  2. void compare(char, char) - to compare the numeric value of two characters with higher numeric value.
  3. void compare(String, String) - to compare the length of the two strings and print the longer of the two.
import java.util.Scanner;

public class KboatCompare
{
    public void compare(int a, int b) {
        
        if (a > b) {
            System.out.println(a);
        }
        else {
            System.out.println(b);
        }
        
    }
    
    public void compare(char a, char b) {
        int x = (int)a;
        int y = (int)b;
        
        if (x > y) {
            System.out.println(a);
        }
        else {
            System.out.println(b);
        }
        
    }
    
    public void compare(String a, String b) {
        
        int l1 = a.length();
        int l2 = b.length();
        
        if (l1 > l2) {
            System.out.println(a);
        }
        else {
            System.out.println(b);
        }

    }
    
}
Output
BlueJ output of KboatCompare.java
BlueJ output of KboatCompare.java
BlueJ output of KboatCompare.java
BlueJ output of KboatCompare.java
BlueJ output of KboatCompare.java
BlueJ output of KboatCompare.java
PrevNext