You are on page 1of 51

Chapter on : String Handling for class 10

Question 1
concat() method is used to join two strings.
Question 2
The output of the following statement, when executed:
System.out.println("COMPUTER".charAt(4)); is U
Question 3
The output of the statement, when executed:
System.out.println("Object Oriented".length()); is 15
Question 4
+ operator is used to concatenate two strings.
Question 5
String declaration is terminated by the symbol ;(semicolon).
Question 6
Character literal is enclosed within single quotes (').
Question 7
The return type of the statement equals( ) is boolean.
Question 8
The output of "VIDYALAYA."substring(2,5) will result in DYA
Write down the syntax to perform the following tasks
Question 1
To check whether a character(chr) is in upper case or not.
boolean res = Character.isUpperCase(chr);
Question 2
To compare two Strings(str1, str2) are same or not.
boolean res = str1.equals(str2);
Question 3
To extract the last character of a word(wd) stored in the variable chr.
char chr = wd.charAt(wd.length() - 1);
Question 4
To return the first occurrence of 'a' in the word "applications".
int res = "applications".indexOf('a');
Question 5
To replace the word "old" with the word "new" in a given String st = "old is always old"
String str = st.replace("old", "new");
Question 6
To check if the second character of a String(str) is in upper case.
boolean res = Character.isUpperCase(str.charAt(1));
Predict the output of the following
Question 1
String str = "Computer Applications" + 1 + 0;
System.out.println("Understanding" + str);
Output
UnderstandingComputer Applications10
Explanation
In the first line, + operator concatenates 1 and 0 to the end of "Computer Applications" so str becomes
"Computer Applications10". Next line prints "UnderstandingComputer Applications10" to the console.
Question 2
String n1 = "46", n2 = "64";
int total = Integer.parseInt(n1) + Integer.parseInt(n2);
System.out.println("The sum of " + "46 " + "and" + " 64" + " is " + total);
Output
The sum of 46 and 64 is 110
Explanation
Integer.parseInt() method will convert the strings n1 and n2 to their corresponding numerical integers. So,
46 and 64 are added as numerical values and the result 110 is stored in int variable total.
Question 3
boolean p;
p = ("BLUEJ".length() > "bluej".length()) ? true: false;
Output
False
Explanation
Both "BLUEJ" and "bluej" have the same length 5. So, condition of ternary operator is false and false is
assigned to boolean variable p.
Question 4
String str = "Information Technology";
int p;
p = str.indexOf('n');
System.out.println(p);
Output
1
Explanation
str.indexOf('n') will return the first index of n in str which is 1. So, the output of this program is 1.
Question 5
String str1 = "Information Technology";
String str2 = "information technology";
boolean p = str1.equalsIgnoreCase(str2);
System.out.println("The result is " + p);
Output
The result is true
Explanation
str1.equalsIgnoreCase(str2) will do a case insensitive comparison of str1 and str2. As both strings contain
the same characters if we ignore the case so it returns true which is stored in boolean variable p.
Question 6
What do the following functions return?
String x = "Vision";
String y = "2020";
(a)
System.out.println(x + y);
Output
Vision2020
Explanation
x and y are concatenated and printed.
(b)
System.out.println(x.length());
Output
6
Explanation
x.length() will give the number of characters in string x which is 6.
(c)
System.out.println(x.charAt(3));
Output
I
Explanation
x.charAt(3) will return the character at index 3 of string x which is i.
(d)
System.out.println(x.equals(y));

Output
False
Explanation
x.equals(y) will return false as x and y contains different characters.
Question 7
String S1 = "Computer World";
String S2 = "COMPUTER WORLD";
String S3 = "Computer world";
String S4 = "computer world";
System.out.println(S1 + " equals "+ S2 + " " + S1.equals(S2));
System.out.println(S1 + " equals "+ S3 + " " + S1.equals(S3));
System.out.println(S1 + " equals "+ S4 + " " + S1.equals(S4));
System.out.println(S1 + " equalsIgnoreCase "+ S4 + " " + S1.equalsIgnoreCase(S4));
Output
Computer World equals COMPUTER WORLD false
Computer World equals Computer world false
Computer World equals computer world false
Computer World equalsIgnoreCase computer world true
Explanation
As the strings S1, S2, S3 and S4 differ in the case of the characters so equals() method will return false
but equalsIgnoreCase() method will return true.
Question 8
If:
String x = "Computer";
String y = "Applications";
What do the following functions return?
(i) System.out.println(x.substring(1,5));
Output
Ompu
Explanation
x.substring(1,5) will return a substring of x starting at index 1 till index 4 (i.e. 5 - 1 = 4).
(ii) System.out.println(x.indexOf(x.charAt(4)));
Output
4
Explanation
x.charAt(4) returns the character at index 4 of string x which is 'u'. First index of 'u' in x is 4 so output is 4.
(iii) System.out.println(y + x.substring(5));
Output
Applicationster
Explanation
x.substring(5) will return the substring of x starting at index 5 till the end of the string. It is "ter". This is
added to the end of string y and printed to the console as output.
(iv) System.out.println(x.equals(y));
Output
False
Explanation
As strings x and y are not equal so x.equals(y) returns false.
Question 9
Give the output of the following:
String n = "Computer Knowledge";
String m = "Computer Applications";
System.out.println(n.substring(0,8).concat(m.substring(9)));
System.out.println(n.endsWith("e"));
Output
ComputerApplications
True
Explanation
n.substring(0,8) returns the substring of n starting at index 0 till 7 (i.e. 8 - 1 = 7) which is
"Computer". m.substring(9)returns the substring of m starting at index 9 till the end of the string which is
"Applications". concat() method joins "Computer" and "Applications" together to give the output as
ComputerApplications.
Question 10
Give the output of the following statements:
String x[] = {"SAMSUNG", "NOKIA", "SONY", "MICROMAX", "BLACKBERRY"};
(i) System.out.println(x[1]);
Output
NOKIA
Explanation
x[1] gives the second element of the array x which is "NOKIA"
(ii) System.out.println(x[3].length());
Output
8
Explanation
x[3].length() gives the number of characters in the fourth element of the array x.
Question 11
Give the output of the following string functions:
(i) "ACHIEVEMENT".replace('E', 'A')
Output
ACHIAVAMANT
Explanation
All 'E' are replaced with 'A'.
(ii) "DEDICATE".compareTo("DEVOTE")
Output
-18
Explanation
"DEDICATE" and "DEVOTE" differ at the third character with 'D' and 'V', respectively. So, output
of compareTo() method will be ASCII Code of 'D' - ASCII Code of 'V' ⇒ 68 - 86 ⇒ -18.
Question 12
Consider the following String array and give the output
String arr[]= {"DELHI", "CHENNAI", "MUMBAI", "LUCKNOW", "JAIPUR"};
System.out.println(arr[0].length() > arr[3].length());
System.out.print(arr[4].substring(0,3));
Output
false
JAI
Explanation
As length of the string "DELHI" is less than that of "LUCKNOW" so first output is false.
arr[4].substring(0,3) will return the substring of "JAIPUR" starting at index 0 till index 2 (i.e. 3 - 1 = 2).
Differentiate between the following
Question 1
equals() and ==
equals() ==
It is a method It is a relational operator
It is used to check if the contents of two strings It is used to check if two variables refer to the same
are same or not object in memory
Example: Example:
String s1 = new String("hello"); String s1 = new String("hello");
String s2 = new String("hello"); String s2 = new String("hello");
boolean res = s1.equals(s2); boolean res = s1 == s2;
equals() ==
System.out.println(res); System.out.println(res);

The output of this code snippet is true as contents The output of this code snippet is false as s1 and s2
of s1 and s2 are the same. point to different String objects.

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

Question 3
toLowerCase() and toUpperCase()
toLowerCase() toUpperCase()
Converts all characters of the String object to lower Converts all characters of the String object to upper
case case
Example: Example:
String str = "HELLO"; String str = "hello";
System.out.println(str.toLowerCase()); System.out.println(str.toUpperCase());

Output of this code snippet will be hello. Output of this code snippet will be HELLO.

Question 4
charAt() and substring()
charAt() substring()
It returns a character from the string at the It extracts a part of the string as specified by its arguments
index specified as its argument and returns the extracted part as a new string.

Its return type is char Its return type is String

Example: Example:
String str = "Hello"; String str = "Hello";
char ch = str.charAt(1); String subStr = str.substring(1);
System.out.println(ch); System.out.println(subStr);

Output of this code snippet is e. Output of this code snippet is ello.

Write short answers


Question 1
What is exception? Name two exception handling blocks.
An exception is an event, which occurs during the execution of a program, that disrupts the normal
flow of the program's instructions. Two exception handling blocks are try and catch.
Question 2
State the purpose and return data type of the following String functions:
(a) indexOf()
It returns the index within the string of the first occurrence of the specified character or -1 if the
character is not present. Its return type is int.
(b) compareTo()
It compares two strings lexicographically. Its return type is int.
Question 3
Write a statement for each to perform the following task on a string:
(i) Extract the second last character of a word stored in the variable wd.
char ch = wd.charAt(wd.length() - 2);
(ii) Check if the second character of a string str is in upper case.
boolean res = Character.isUpperCase(str.charAt(1));
Question 4
Write a statement each to perform the following task on a string:
(i) Find and display the position of the last space in a string s.
System.out.println(s.lastIndexOf(' '));
(ii) Convert a number stored in a string variable x to double data type.
double a = Double.parseDouble(x);
Question 5
How does endsWith() and startsWith() differ? Explain with an example.
endsWith() tests if the string object ends with the string specified as its argument. startsWith() tests if
the string object starts with the string specified as its argument. Consider the below example:
public class Example {
public static void main(String args[]) {
String str = "ICSE Computer Applications";
System.out.println("Does " + str + " starts with ICSE? " + str.startsWith("ICSE"));
System.out.println("Does " + str + " ends with tions? " + str.endsWith("tions"));
}
}
Here, both str.startsWith("ICSE") and str.endsWith("tions") returns true as str starts with "ICSE" and
ends with "tions".
Describe the purpose of the following functions with their syntax
Question 1
toUpperCase()
It converts a string into upper case characters. If any character is already in uppercase or is a special
character then it will remain same.
Syntax:
String <variable-name> = <string-variable>.toUpperCase();
Question 2
trim()
It removes all leading and trailing space from the string.
Syntax:
String <variable-name> = <string-variable>.trim();
Question 3
toLowerCase()
It converts a string into lowercase characters. If any character is already in lowercase or is a special
character then it will remain same.
Syntax:
String <variable-name> = <string-variable>.toLowerCase();
Question 4
length()
It returns the length of the string i.e. the number of characters present in the string.
Syntax:
int <variable-name> = <string-variable>.length();
Question 5
replace()
It replaces a character with another character or a substring with another substring at all its
occurrences in the given string.
Syntax:
String <variable-name> = <string-variable>.replace(<character or substring to replace>, <new character or
substring>);
Question 6
compareTo()
It compares two strings lexicographically.
Syntax:
int <variable-name> = <string-variable>.compareTo(<string-variable2>);
Question 7
reverse()
It is a method of StringBuffer class used to reverse the sequence of characters.
Syntax:
<StringBuffer-Variable>.reverse();
Question 8
indexOf()
It returns the index within the string of the first occurrence of the specified character or -1 if the
character is not present.
Syntax:
int <variable-name> = <string-variable>.indexOf(<character>);
Question 9
startWith()
It tests if the string object starts with the string specified as its argument.
Syntax:
boolean <variable-name> = <string-variable>.startWith(<string>);
Question 10
equalsIgnoreCase()
It ignores the case of the characters and checks if the contents of two strings are same or not.
Syntax:
boolean <variable-name> = <string-variable>.equalsIgnoreCase(<string>);
Solutions to Unsolved Java Programs
Question 1
Write a program to input a sentence. Find and display the following:
(i) Number of words present in the sentence
(ii) Number of letters present in the sentence
Assume that the sentence has neither include any digit nor a special character.
import java.util.*;
public class stringWordsNLetters
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
int wCount = 0, lCount = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ')
wCount++;
else
lCount++;
}

/*
* Number of words in a sentence are one more than
* the number of spaces so incrementing wCount by 1
*/
wCount++;
System.out.println("No. of words = " + wCount);
System.out.println("No. of letters = " + lCount);
}
}
Output

Question 2
Write a program in Java to accept a word/a String and display the new string after removing all the vowels
present in it.
Sample Input: COMPUTER APPLICATIONS
Sample Output: CMPTR PPLCTNS
import java.util.*;
public class stringVowelRemoval
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or sentence:");
String str = in.nextLine();
char newStrArr[] = new char[str.length()];
String t = str.toUpperCase();
int idx = 0;
for (int i = 0; i < t.length(); i++) {
if (t.charAt(i) == 'A' || t.charAt(i) == 'E' || t.charAt(i) == 'I' || t.charAt(i) == 'O' || t.charAt(i) == 'U')
continue;
newStrArr[idx++] = str.charAt(i);
}
String newStr = new String(newStrArr);
System.out.println("String with vowels removed");
System.out.println(newStr);
}
}
Output
Question 3
Write a program in Java to accept a name(Containing three words) and Display only the initials (i.e., first
letter of each word).
Sample Input: LAL KRISHNA ADVANI
Sample Output: L K A
import java.util.*;
public class stringNameInitials
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a name of 3 or more words:");
String str = in.nextLine();
System.out.print(str.charAt(0) + " ");
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == ' ')
System.out.print(str.charAt(i + 1) + " ");
}
}
}
Output
Question 4
Write a program in Java to accept a name containing three words and display the surname first, followed by
the first and middle names.
Sample Input: MOHANDAS KARAMCHAND GANDHI
Sample Output: GANDHI MOHANDAS KARAMCHAND
import java.util.*;
public class stringSurnameFirst
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a name of 3 words:");
String name = in.nextLine();
int lastSpaceIdx = name.lastIndexOf(' ');
System.out.println(name.substring(lastSpaceIdx + 1) + " " +
name.substring(0, lastSpaceIdx));
}
}
Output

Question 5
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.*;
public class stringLongestWord
{
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 += " ";
String word = "", lWord = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
if (word.length() > lWord.length())
lWord = word;
word = "";
}
else {
word += str.charAt(i);
}
}
System.out.println("The longest word: " + lWord +
": The length of the word: " + lWord.length());
}
}
Output

Question 6
Write a program in Java to accept a word and display the ASCII code of each character of the word.
Sample Input: BLUEJ
Sample Output:
ASCII of B = 66
ASCII of L = 76
ASCII of U = 85
ASCII of E = 69
ASCII of J = 74
import java.util.*;
public class stringASCIICode
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
for (int i = 0; i < word.length(); i++) {
System.out.println("ASCII of " + word.charAt(i)
+ " = " + (int)word.charAt(i));
}
}
}
Output

Question 7
Write a program in Java to accept a String in upper case and replace all the vowels present in the String with
Asterisk (*) sign.
Sample Input: "TATA STEEL IS IN JAMSHEDPUR"
Sample output: T*T* ST**L *S *N J*MSH*DP*R
import java.util.*;
public class stringVowelReplace
{
Public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string in uppercase:");
String str = in.nextLine();
char newStrArr[] = new char[str.length()];
String t = str.toUpperCase();
int idx = 0;
for (int i = 0; i < t.length(); i++) {
if (t.charAt(i) == 'A' ||
t.charAt(i) == 'E' ||
t.charAt(i) == 'I' ||
t.charAt(i) == 'O' ||
t.charAt(i) == 'U') {
newStrArr[idx++] = '*';
}
else {
newStrArr[idx++] = str.charAt(i);
}
}
String newStr = new String(newStrArr);
System.out.println(newStr);
}
}
Output
Question 8
Write a program in Java to enter a sentence. Frame a word by joining all the first characters of each word of
the sentence. Display the word.
Sample Input: Vital Information Resource Under Seize
Sample Output: VIRUS
import java.util.*;
public class stringFrameWord
{
public void frameWord() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
String word = "" + str.charAt(0);
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ')
word += str.charAt(i + 1);
}
System.out.println(word);
}
}
Output

Question 9
Write a program in Java to enter a sentence. Display the words which are only palindrome.
Sample Input: MOM AND DAD ARE NOT AT HOME
Sample Output: MOM
                          DAD
import java.util.*;
public class stringPalinWords
{
Public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
str = str + " ";
String word = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
int len = word.length();
boolean isPalin = true;
for (int j = 0; j < len / 2; j++) {
if (word.charAt(j) != word.charAt(len - 1 - j)) {
isPalin = false;
break;
}
}
if (isPalin)
System.out.println(word);
word = "";
}
else {
word += str.charAt(i);
}
}
}
}
Output

Question 10
Write a program to accept a sentence. Display the sentence in reversing order of its word.
Sample Input: Computer is Fun
Sample Output: Fun is Computer
import java.util.Scanner;
public class stringReverseWords
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
str = " " + str;
String word = "";
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) == ' ') {
System.out.print(word + " ");
word = "";
}
else {
word = str.charAt(i) + word;
}
}
}
}
Output

Question 11
Write a program to input a sentence and display the word of the sentence that contains maximum number of
vowels.
Sample Input: HAPPY NEW YEAR
Sample Output: The word with maximum number of vowels: YEAR
import java.util.Scanner;
public class stringVowelWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String input = in.nextLine();
String str = (input + " ").toUpperCase();
String word = "", mWord = "";
int count = 0, maxCount = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'A' || str.charAt(i) == 'E' || str.charAt(i) == 'I' || str.charAt(i) == 'O' ||
str.charAt(i) == 'U') {
count++;
}
if (str.charAt(i) == ' ') {
if (count > maxCount) {
maxCount = count;
mWord = word;
}
word = "";
count = 0;
}
else {
word += str.charAt(i);
}
}
System.out.println("The word with maximum number of vowels: "
+ mWord);
}
}
Output

Question 12
Consider the sentence as given below:
Blue bottle is in Blue bag lying on Blue carpet
Write a program to assign the given sentence to a string variable. Replace the word Blue with Red at all its
occurrence. Display the new string as shown below:
Red bottle is in Red bag lying on Red carpet
public class KboatStringReplace
{
public static void main(String args[]) {
String str = "Blue bottle is in Blue bag lying on Blue carpet";
str += " ";
String newStr = "";
String word = "";
String target = "Blue";
String newWord = "Red";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
if (target.equals(word)) {
newStr = newStr + newWord + " ";
}
else {
newStr = newStr + word + " ";
}
word = "";
}
else {
word += str.charAt(i);
}
}
System.out.println(newStr);
}
}
Output

Question 13
Write a program to accept a word and convert it into lower case, if it is in upper case. Display the new word
by replacing only the vowels with the letter following it.
Sample Input: computer
Sample Output: cpmpvtfr
import java.util.Scanner;
public class replaceVowelReplace
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = in.nextLine().toLowerCase();
char newStr[] = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' ||
str.charAt(i) == 'u') {
newStr[i] = (char)(str.charAt(i) + 1);
}
else {
newStr[i] = str.charAt(i);
}
}
String replacedStr = new String(newStr);
System.out.println(replacedStr);
}
}
Output
Question 14
A string is said to be ‘Unique’ if none of the letters present in the string are repeated. Write a program to
accept a string and check whether the string is Unique or not. The program displays a message accordingly.
Sample Input: COMPUTER
Sample Output: Unique String
import java.util.Scanner;
public class UniqueString
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = in.nextLine();
String str = input.toUpperCase();
boolean isUnique = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = i + 1; j < str.length(); j++) {
if (ch == str.charAt(j)) {
isUnique = false;
break;
}
}
if (!isUnique)
break;
}
if (isUnique)
System.out.println("Unique String");
else
System.out.println("Not Unique String");
}
}
Output
Question 15
A 'Happy Word' is defined as:
Take a word and calculate the word’s value based on position of the letters in English alphabet. On
the basis of word’s value, find the sum of the squares of its digits. Repeat the process with the
resultant number until the number equals 1 (one). If the number ends with 1 then the word is called a
'Happy Word'.
Write a program to input a word and check whether it a ‘Happy Word’ or not. The program displays a
message accordingly.
Sample Input: VAT
Place value of V = 22, A= 1, T = 20
[Hint: A = 1, B = 2, ----------, Z = 26]
Solution:
22120 ⇒ 22 + 22 + 12 + 22 + 02 = 13
           ⇒ 12 + 32 = 10
           ⇒ 12 + 02 = 1
Sample Output: A Happy Word
import java.util.Scanner;
public class HappyWord
{
private boolean isHappyNumber(long num) {
long sum = 0;
long n = num;
do {
sum = 0;
while (n != 0) {
int d = (int)(n % 10);
sum += d * d;
n /= 10;
}
n = sum;
} while (sum > 6);

return (sum == 1);


}
public void checkHappyWord() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.nextLine();
word = word.toUpperCase();
String wordValueStr = "";
for (int i = 0; i < word.length(); i++) {
wordValueStr += String.valueOf(word.charAt(i) - 64);
}
long wordValue = Long.parseLong(wordValueStr);
boolean isHappy = isHappyNumber(wordValue);
if (isHappy)
System.out.println("A Happy Word");
else
System.out.println("Not a Happy Word");
}
}
Output

Question 16
Write a program to input a sentence. Count and display the frequency of each letter of the sentence in
alphabetical order.
Sample Input: COMPUTER APPLICATIONS
Sample Output:
Character Frequency Character Frequency
A 2 O 2
C 2 P 3
I 1 R 1
L 2 S 1
M 1 T 2
Character Frequency Character Frequency
N 1 U 1
import java.util.Scanner;
public class LetterFreq
{
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];
for (int i = 0; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i))) {
int chIdx = str.charAt(i) - 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

Question 17
Write a program to accept a string. Convert the string into upper case letters. 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 doubleLetterSeq
{
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;
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) == str.charAt(i + 1))
count++;
}
System.out.println("Double Letter Sequence Count = " + count);
}
}
Output

Question 18
Special words are those words which start and end with the same letter.
Example: EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same from left to right and vice-versa.
Example: MALYALAM, MADAM, LEVEL, ROTATOR, CIVIC
All palindromes are special words but all special words are not palindromes.
Write a program to accept a word. Check and display whether the word is a palindrome or only a special
word or none of them.
import java.util.Scanner;
public class SpecialPalindrome
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = in.nextLine();
str = str.toUpperCase();
int len = str.length();
if (str.charAt(0) == str.charAt(len - 1)) {
boolean isPalin = true;
for (int i = 1; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - 1 - i)) {
isPalin = false;
break;
}
}
if (isPalin) {
System.out.println("Palindrome");
}
else {
System.out.println("Special");
}
}
else {
System.out.println("Neither Special nor Palindrome");
}

}
}
Output
Question 19
Write a program to input a sentence. Convert the sentence into upper case letters. Display the words along
with frequency of the words which have at least a pair of consecutive letters.
Sample Input: MODEM IS AN ELECTRONIC DEVICE
Sample Output:
MODEM
DEVICE
Number of words containing consecutive letters: 2
import java.util.Scanner;
public class StringConsecutive
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = in.nextLine();
str = str.toUpperCase();
str += " ";
String word = "";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
for (int j = 0; j < word.length() - 1; j++) {
if (word.charAt(j) + 1 == word.charAt(j + 1)) {
count++;
System.out.println(word);
break;
}
}
word = "";
}
else {
word += str.charAt(i);
}
}
System.out.println("Number of words containing consecutive letters: " + count);
}
}
Output
Question 20
Write a program to accept a word (say, BLUEJ) and display the pattern:
(a)
BLUEJ
BLUE
BLU
BL
B
import java.util.Scanner;
public class StringPattern
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();

for (int i = len - 1; i >= 0; i--) {


for (int j = 0; j <= i; j++) {
System.out.print(word.charAt(j));
}
System.out.println();
}
}
}
Output
(b)
J
EE
UUU
LLLL
BBBBB
import java.util.Scanner;
public class StringPattern2
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();
for (int i = len - 1; i >= 0; i--) {
for (int j = len - 1; j >= i; j--) {
System.out.print(word.charAt(i));
}
System.out.println();
}
}
}
Output
(c)
BLUEJ
LUEJ
UEJ
EJ
J
import java.util.Scanner;
public class StringPattern3
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
System.out.print(word.charAt(j));
}
System.out.println();
}
}
}
Output
Question 21
Write a program to display the pattern:
(a)
ABCDE
BCDE
CDE
DE
E
public class StringPattern4
{
public static void main(String args[]) {
String word = "ABCDE";
int len = word.length();
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
System.out.print(word.charAt(j));
}
System.out.println();
}
}
}
Output
(b)
A
BC
DEF
GHIJ
KLMNO
public class StringPattern5
{
public static void main(String args[]) {
char ch = 'A';
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(ch++);
}
System.out.println();
}
}
}
Output
(c)
ABCDE
ABCDA
ABCAB
ABABC
AABCD
public class StringPattern6
{
Public static void main(String args[]) {
String word = "ABCDE";
int len = word.length();
for (int i = 0; i < len; i++) {
for (int j = 0; j < len - i; j++) {
System.out.print(word.charAt(j));
}
for (int k = 0; k < i; k++) {
System.out.print(word.charAt(k));
}
System.out.println();
}
}
}
Output
Question 22
Write a program to generate a triangle or an inverted triangle till n terms based upon the User’s choice of the
triangle to be displayed.
Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter the number of terms 5
Sample Output:
*****
****
***
**
*
Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter the number of terms 5
Sample Output:
ABCDE
ABCD
ABC
AB
A
import java.util.Scanner;
public class TriangleChoice
{
Public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for a triangle and");
System.out.println("Type 2 for an inverted triangle of alphabets");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
System.out.print("Enter the number of terms: ");
int n = in.nextInt();
switch (choice) {
case 1:
for (int i = 0; i <= n; i++) {
for (int j = 0; j < i; j++) {
System.out.print(' ');
}
for (int k = i; k <= n; k++) {
System.out.print('*');
}
System.out.println();
}
break;
case 2:
n += 64;
for (int i = n; i >= 65; i--) {
for (int j = 65; j <= i; j++) {
System.out.print((char)j);
}
System.out.println();
}
break;

default:
System.out.println("Incorrect choice");
break;
}
}
}
Output
Question 23
Write a program to generate a triangle or an inverted triangle based upon User’s choice.
Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter a word : BLUEJ
Sample Output:
B
LL
UUU
EEEE
JJJJJ
Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter a word : BLUEJ
Sample Output:
BLUEJ
BLUE
BLU
BL
B
import java.util.Scanner;
public class TriangleMenu
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for a triangle and");
System.out.println("Type 2 for an inverted triangle");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
System.out.print("Enter a word: ");
String word = in.nextLine();
int len = word.length();
switch (choice) {
case 1:
for(int i = 0; i < len; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(word.charAt(i));
}
System.out.println();
}
break;
case 2:
for(int i = len - 1; i >= 0; i--) {
for(int j = 0; j <= i; j++) {
System.out.print(word.charAt(j));
}
System.out.println();
}
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Output
Question 24
Using the switch statement, write a menu driven program for the following:
(a) To print the Floyd’s triangle:
1
2   3
4   5   6
7   8   9   10
11 12 13 14 15
(b) To display the following pattern:
I
IC
ICS
ICSE
For an incorrect option, an appropriate error message should be displayed.
import java.util.Scanner;
public class Pattern
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Floyd's triangle");
System.out.println("Type 2 for an ICSE pattern");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
break;
case 2:
String s = "ICSE";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j <= i; j++) {
System.out.print(s.charAt(j) + " ");
}
System.out.println();
}
break;
default:
System.out.println("Incorrect Choice");
}
}
}
Output
Question 25
Write a program in Java to store 10 different country names and their capitals in two different Single
Dimensional Arrays (SDA). Display the country names (that starts with a vowel) along with their capitals in
the given format.
Country Names          Capital
        xxxx                       xxxx
        xxxx                       xxxx
import java.util.Scanner;
public class CountryCapital
{
public static void main(String args[]) {
final int SIZE = 10;
Scanner in = new Scanner(System.in);
String countries[] = new String[SIZE];
String capitals[] = new String[SIZE];
System.out.println("Enter " + SIZE + " countries and their capitals");
for (int i = 0; i < SIZE; i++) {
System.out.print("Enter country name: ");
countries[i] = in.nextLine();
System.out.print("Enter its capital: ");
capitals[i] = in.nextLine();
}
System.out.println("Country Names\t\tCapital");
for (int i = 0; i < SIZE; i++) {
char ch = Character.toUpperCase(countries[i].charAt(0));
if (ch == 'A' ||
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
System.out.println(countries[i] + "\t\t" + capitals[i]);
}
}
}
}
Output
Question 26
(a) Write a program in Java to store 20 different names and telephone numbers of your friends in two
different Single Dimensional Arrays (SDA). Now arrange all the names in alphabetical order and display all
the names along with their respective telephone numbers using selection sort technique.
import java.util.Scanner;
public class TelephoneBook
{
public static void main(String args[]) {
final int SIZE = 20;
Scanner in = new Scanner(System.in);
String names[] = new String[SIZE];
long telNos[] = new long[SIZE];
System.out.println("Enter " + SIZE + " names and telephone numbers");
for (int i = 0; i < SIZE; i++) {
System.out.print("Enter Name: ");
names[i] = in.nextLine();
System.out.print("Enter telephone number: ");
telNos[i] = in.nextLong();
in.nextLine();
}
//Selection Sort
for (int i = 0; i < SIZE - 1; i++) {
int min = i;
for (int j = i + 1; j < SIZE; j++) {
if (names[j].compareToIgnoreCase(names[min]) < 0) {
min = j;
}
}
String temp = names[min];
names[min] = names[i];
names[i] = temp;
long t = telNos[min];
telNos[min] = telNos[i];
telNos[i] = t;
}
System.out.println("Name\tTelephone Number");
for (int i = 0; i < SIZE; i++) {
System.out.println(names[i] + "\t" + telNos[i]);
}
}
}
Output
(b) Write a program to accept 10 names in a Single Dimensional Array (SDA). Display the names whose
first letter matches with the letter entered by the user.
Sample Input:
Aman Shahi
Akash Gupta
Suman Mishra
and so on ..........
Sample Output:
Enter the alphabet: A
Aman Shahi
Akash Gupta
.....
.....
import java.util.Scanner;
public class SDANames
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String names[] = new String[10];
System.out.println("Enter 10 names");
for (int i = 0; i < names.length; i++) {
names[i] = in.nextLine();
}
System.out.print("Enter a letter: ");
char ch = in.next().charAt(0);
ch = Character.toUpperCase(ch);
for (int i = 0; i < names.length; i++) {
if (Character.toUpperCase(names[i].charAt(0)) == ch) {
System.out.println(names[i]);
}
}
}
}
Output

Question 27
Write a program to input twenty names in an array. Arrange these names in ascending order of letters, using
the bubble sort technique.
Sample Input:
Rohit, Devesh, Indrani, Shivangi, Himanshu, Rishi, Piyush, Deepak, Abhishek, Kunal, .....
Sample Output:
Abhishek, Deepak, Devesh, Himanshu, Indrani, Kunal, Piyush, Rishi, Rohit, Shivangi, .....
import java.util.Scanner;
public class ArrangeNames
{
public static void main(String arg[]) {
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
Question 28
Write a program in Java to input the names of 10 cities in a Single Dimensional Array. Display only those
names which begin with a consonant but end with a vowel.
Sample Input: Kolkata, Delhi, Bengaluru, Jamshedpur, Bokaro, .......
Sample Output: Kolkata
Delhi
Bengaluru
Bokaro
....
....
import java.util.Scanner;
public class KboatCityName
{
public boolean isVowel(char ch) {
char letter = Character.toUpperCase(ch);
if (letter == 'A' || letter == 'E' || letter == 'I' || letter == 'O' || etter == 'U')
return true;
else
return false;
}

public void cityNames() {


String cities[] = new String[10];
Scanner in = new Scanner(System.in);
System.out.println("Enter 10 city names");

for (int i = 0; i < cities.length; i++) {


cities[i] = in.nextLine();
}

System.out.println("\nCities starting with consonant & ending with vowel:");


for (int i = 0; i < cities.length; i++) {
if (!isVowel(cities[i].charAt(0)) &&
isVowel(cities[i].charAt(cities[i].length() - 1)))
System.out.println(cities[i]);
}
}

}
Output

Question 29
Write a program in Java to store 10 words in a Single Dimensional Array. Display only those words which
are Palindrome.
Sample Input: MADAM, TEACHER, SCHOOL, ABBA, .........
Sample Output: MADAM
ABBA
..........
..........
import java.util.Scanner;

public class SDAPalindrome


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String words[] = new String[10];
System.out.println("Enter 10 words:");
for (int i = 0; i < words.length; i++) {
words[i] = in.nextLine();
}
System.out.println("\nPalindrome Words:");
for (int i = 0; i < words.length; i++) {
String str = words[i].toUpperCase();
int strLen = str.length();
boolean isPalin = true;
for (int j = 0; j < strLen / 2; j++) {
if (str.charAt(j) != str.charAt(strLen - 1 - j)) {
isPalin = false;
break;
}
}
if (isPalin)
System.out.println(words[i]);
}
}
}
Output

Question 30
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 dimension integer array. Search for the 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 StdCodes
{
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

You might also like