Program to throw a user-defined exception "String Mismatch Exception", if two strings are not equal (ignore the case)

This is a simple program in which we have two checked two strings for equality. If they are equal then print "String matched !!!" otherwise throw user-defined exception. The euqlasIgnoreCase( ) method of java.lang.String class is used to compare two strings by ignoring case considerations.

PROGRAM
import java.util.Scanner;

class StringMismatchException extends Exception {
 
 public StringMismatchException(String str) {
  
  System.out.println(str);
 }
}
public class StringExcDemo {

 public static void main(String[] args) {
  
  Scanner scan = new Scanner(System.in);
  System.out.print("Enter the string :: ");
  String input = scan.nextLine();
  
  try {
   if(input.equalsIgnoreCase("Hello"))
    System.out.println("String matched !!!");
   else
    throw new StringMismatchException("String not matched ???");
  }
  catch (StringMismatchException s) {
   System.out.println(s);
  }
 }

}
OUTPUT 1
C:\>javac StringExcDemo.java
C:\>java StringExcDemo
Enter the string :: Hello
Strings matched !!!
OUTPUT 2
C:\>javac StringExcDemo.java
C:\>java StringExcDemo
Enter the string :: HELLO
String matched !!!
OUTPUT 3
C:\>javac StringExcDemo.java
C:\>java StringExcDemo
Enter the string :: Hi
Strings mismatch ???
exception.StringMismatchException

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet