Write a Java method to display the middle character of a string


This Java program prompts the user to enter a string and then finds and prints the middle character(s) of the string. Here's a step-by-step explanation of how the program works:

  • The program begins by importing the Scanner class, which is used to read user input from the command line.
  • The main method is defined, which is the entry point of the program.
  • A new Scanner object is created and assigned to the variable input.
  • The program prompts the user to enter a string by calling System.out.print() method with the message "Enter the String: ".
  • The user enters a string, which is read by calling the nextLine() method on the Scanner object input, and is assigned to the variable str.
  • Two integer variables pos and len are declared but not initialized.
  • The program checks if the length of the input string is even by using the modulo operator (%) to determine if the remainder of str.length() / 2 is zero. If the length is even, the middle characters will be the two characters at positions str.length() / 2 - 1 and str.length() / 2. If the length is odd, the middle character will be the single character at position str.length() / 2.
  • The program assigns the value of pos and len based on whether the length of the input string is even or odd, as described in step 7.
  • The program uses the substring() method on the string str to extract the middle character(s) by passing in the pos and len variables as arguments. This method returns a new string that contains the characters of the original string starting at position pos and continuing for len characters.
  • The program prints the middle character(s) of the input string by calling System.out.print() method with the message "Middle character in the String : " concatenated with the result of the substring() method.
  • The program terminates.

Overall, this program is a simple example of how to manipulate strings in Java to find the middle character(s) of a string.

Source Code

import java.util.Scanner;
public class Middle_Character
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the String: ");
		String str = input.nextLine();
		int pos;
		int len;
		if (str.length() % 2 == 0)
		{
			pos = str.length() / 2 - 1;
			len = 2;
		}
		else
		{
			pos = str.length() / 2;
			len = 1;
		}
		System.out.print("Middle character in the String : " + str.substring(pos, pos + len));
	}
}
 

Output

Enter the String: Computer
Middle character in the String : pu

Example Programs