Java Method to Display the Middle Character of a String

Program to find middle character in string in java. This program will print the center element in this input. Write a Java program that reads a string from the user and retrieves the middle characters in the string’s center from the input string and returns it as a string output.

import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string");
String str = sc.nextLine();
char ch[] = str.toLowerCase().toCharArray();
int c=0;
int v=0;
String sp="";
if(str.length()<3)
{
System.out.println("The string should not have "+str+" is too short");
}
else{

for (int i=0;i<ch.length;i++) {

if (ch[i] >= 'a' && ch[i] <= 'z') {
c++;
} else {
sp += ch[i];
v++;
}

}
if(ch.length!=c)
{
System.out.println("this string shouldnt have");
System.out.println(sp);
}
else if(ch.length==c){
System.out.println("middle charecters");
if(ch.length%2==0){
String out = ""+ch[(ch.length/2)-1]+ch[(ch.length/2)];
System.out.println(out);
}
else{
String out = ""+ch[ch.length/2];
System.out.println(out);
}
}

}
}
}

 

Output:

Enter the string
thilagar
middle charecters
la

toCharArray() function in Java

The toCharArray() function in Java turns a string into a series of characters. The length of the returned array is the same as the length of the string. This string is converted to a character array using the java string toCharArray() function. It produces a newly generated character array with a length identical to this string and contents populated with this string’s characters.

string.length in Java

length is a final variable that applies to arrays. We can find out how big the array is by using the length variable. string. length(): The length() function applies to string objects as a final variable. The length() function calculates the total number of characters in a string.

str.lowercase() in Java

The lowercase letter is returned by the java string toLowerCase() function. In other words, it changes all of the string’s characters to lower case letters. The toLowerCase() function is identical to toLowerCase(Locale. getDefault()). Using this program we can execute program to find middle character in string in java.