Repetitions in String Example in Java
On this page (8sections)
Introduction
Repetitions In String 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.
Repetitions In String Example Program
import java.util.Scanner;
public class RepetitionsInString{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter the String");
String str=in.nextLine();
int count=0;
String temp="";
for(int i=0;i < str.length();i++){
char c1=str.charAt(i);
for(int j=i;j < str.length();j++){
char c2=str.charAt(j);
if(c1==c2 && temp.indexOf(c1)==-1){
count=count+1;
}
}
if(temp.indexOf(c1)==-1){
temp=temp+c1;
System.out.println("The Character " + c1 + " has occurred " + count + " times");
}
count=0;
}
}
}
Sample Output
Enter the String
impossible
The Character i has occurred 2 times
The Character m has occurred 1 times
The Character p has occurred 1 times
The Character o has occurred 1 times
The Character s has occurred 2 times
The Character b has occurred 1 times
The Character l has occurred 1 times
The Character e has occurred 1 times
When 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). -
A
println/printcall writes text to the console — part of the sample output below. -
String str=in.nextLine();updates a variable used in the calculation or output. -
int count=0;updates a variable used in the calculation or output. -
String temp="";updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.