Write a Java program to find the first uppercase letter in a string using recursion


This program checks if a given string contains an uppercase letter and returns the first uppercase letter found. Here's how it works:

  • The program takes a string "str" as input and initializes a variable "i" to 0.
  • The method "firstUppercaseLetter" takes two parameters, "str" and "i". It first checks if the character at index i is null, which means we have reached the end of the string. If this is the case, it returns 0 to indicate that there are no uppercase letters in the string.
  • If the character at index i is uppercase, the method returns that character.
  • If the character at index i is not uppercase, the method calls itself recursively with i+1 as the new value for i.
  • If an exception occurs during the recursion, the program prints "Exception Occurs" and returns 0.

Source Code

import java.io.*;
class UpperCase_Letter
{
	public static void main(String args[])
	{
		String str = "tutor Joes";
		char res = firstUppercaseLetter(str,0);
		if (res == 0)
		{
			System.out.println("No Uppercase Letter in a String");
		}
		else
		{
			System.out.println (res);
		}
	}
	static char firstUppercaseLetter(String str, int i)
	{
		if(str.charAt(i)=='\0')
		{
			return 0;
		}
		if(Character.isUpperCase(str.charAt(i)))
		{
			return str.charAt(i);
		}
		try
		{
			return firstUppercaseLetter(str, i + 1);
		}
		catch(Exception e)
		{
			System.out.println("Exception Occurs");
		}
		return 0;
	}
}

Output

J