Tuesday, 4 March 2025

Write Java program which accepts string from user, if its length is less than five, then throw user defined exception “Invalid String” otherwise display string in uppercase.


import java.io.*;

// User-defined exception class

class InvalidStringException extends Exception {

    public InvalidStringException(String message) {

        super(message);

    }

}

public class StringValidation {

    public static void main(String[] args) {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        try {

            System.out.println("Enter a string:");

            String input = br.readLine();

            // Check if the length is less than 5

            if (input.length() < 5) {

throw new InvalidStringException("Invalid String - Length must be at least 5 characters.");

            }

            // Display the string in uppercase

     System.out.println("Valid String in Uppercase: " + input.toUpperCase());

          } catch (InvalidStringException e) {

            System.out.println("Error: " + e.getMessage());

        } catch (IOException e) {

            System.out.println("Error in input!");

        }

    } }