Default Methods for String Manipulation in Java


Write a Java program to demonstrate the use of an interface with default methods for string manipulation

  • The StringUtil interface defines two default methods: reverse() and toUpperCase().
  • The reverse() method reverses the given input string using the StringBuilder class.
  • The toUpperCase() method converts the given input string to uppercase.
  • The Main class implements the StringUtil interface.
  • In the main() method of the Main class, an instance of Main class is created.
  • A string str is defined with the value "Tutor Joes".
  • The reverse() method is called on the main object to reverse the string str, and the result is printed.
  • The toUpperCase() method is called on the main object to convert the string str to uppercase, and the result is printed.

Source Code

interface StringUtil
{
	default String reverse(String input)
	{
		return new StringBuilder(input).reverse().toString();
	}
 
	default String toUpperCase(String input)
	{
		return input.toUpperCase();
	}
}
 
public class Main implements StringUtil
{
	public static void main(String[] args)
	{
		Main main = new Main();
		String str = "Tutor Joes";
 
		System.out.println("Reversed String : " + main.reverse(str));
		System.out.println("Uppercase String : " + main.toUpperCase(str));
	}
}

Output

Reversed String : seoJ rotuT
Uppercase String : TUTOR JOES

Example Programs