3. Write a Java method to display the middle character of a string. Note: a) If the length of the string is odd there will be two middle characters. b) If the length of the string is even there will be one middle character.
class MiddleCharacter
{
static String getMiddleCharacter(String str)
{
if(str.length() %2==0)
{
return String.valueOf(str.charAt(str.length()/2));
}
else
{
return str.substring(str.length()/ 2 - 1, str.length() / 2 + 1);
}
}
public static void main(String st[])
{
String str1="Hello";
String str2="Tree";
System.out.println("Middle character of :" + str1 +" \n" + getMiddleCharacter(str1));
System.out.println("Middle character of :" + str2 +" \n" + getMiddleCharacter(str2));
}
}
OUTPUT
Middle character of :Hello
el
Middle character of :Tree
e