In Java, How Can I Determine If A Specific Character Is Present Within A String?

In Java, you can check if a single character appears in a string using the contains method or by iterating through each character of the string. Here are two approaches:

  1. Using the contains method:
String str = "Hello World";
char ch = 'o';

if (str.contains(String.valueOf(ch))) {
    System.out.println("Character '" + ch + "' is present in the string");
} else {
    System.out.println("Character '" + ch + "' is not present in the string");
}
  1. Iterating through each character of the string:
String str = "Hello World";
char ch = 'o';
boolean found = false;

for (int i = 0; i < str.length(); i++) {
    if (str.charAt(i) == ch) {
        found = true;
        break;
    }
}

if (found) {
    System.out.println("Character '" + ch + "' is present in the string");
} else {
    System.out.println("Character '" + ch + "' is not present in the string");
}

Both approaches will give you the same result.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!