First Repeated Character Example in Java
Introduction
First Repeated Character is a classic Java console program that demonstrates the concept with complete source code and sample output. Strings are immutable objects in Java; the examples show comparison, searching and transformation.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
First Repeated Character Example Program
import java.util.Scanner;
public class FirstRepeatedCharacter {
Scanner in = new Scanner( System.in);
public static void main(String[] args) {
FirstRepeatedCharacter frc = new FirstRepeatedCharacter();
frc.mainLoop();
}
void mainLoop() {
String str = " ";
System.out.println("Please enter a string: ");
str = in.next();
str = str.toLowerCase();
for(int i = 0; i < str.length(); i++) {
char character = str.charAt(i);
int firstIndex = str.indexOf(character);
int lastIndex = str.lastIndexOf(character);
if(firstIndex != lastIndex) {
System.out.println("The character '"+character+"' is repeated");
break;
}
}
}
}Sample Output
Please enter a string:
java
The character 'a' is repeatedWhen to use
Use string manipulation when cleaning user input, parsing text files or formatting messages.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
Scannerreads typed input from the keyboard (System.in). -
FirstRepeatedCharacter frc = new FirstRepeatedCharacter();updates a variable used in the calculation or output. -
String str = " ";updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
str = in.next();updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.