Java program to print the middle character of a string

Given the string str, the task is to print the middle characters of the string. If the length of the string is even, then there will be two intermediate characters, and we need to print the second intermediate character.

Examples:

Input: str = “Java”
Output: v
Explanation: 
The length of the given string is even. 
Therefore, there would be two middle characters ‘a’ and ‘v’, we print the second middle character.

Input: str = “GeeksForGeeks”
Output: o
Explanation: 
The length of the given string is odd. 
Therefore, there would be only one middle character, we print that middle character.

Approach: 

  1. Get the string to find the middle character.
  2. Calculate the length of a given string.
  3. Find the middle index of the string.
  4. Now, use the function charAt() in Java to print the middle character of the string in the middle of the index.
The following is the execution of the above approach:
 
// Java program for the above approach
class GFG {

	// Function that prints the middle
	// character of a string
	public static void
	printMiddleCharacter(String str)
	{
		// Finding string length
		int len = str.length();

		// Finding middle index of string
		int middle = len / 2;

		// Print the middle character
		// of the string
		System.out.println(str.charAt(middle));
	}

	// Driver Code
	public static void
	main(String args[])
	{
		// Given string str
		String str = "GeeksForGeeks";

		// Function Call
		printMiddleCharacter(str);
	}
}

Output: 

o

Time Complexity: O(1) 
Auxiliary Space: O(1)

Submit Your Programming Assignment Details