w3resource
Java Programming Exercies

Java String Exercises: Read a string and return true if "good" appears starting at index 0 or 1 in the given string

Java String: Exercise-62 with Solution

Write a Java program to read a string and return true if "good" appears starting at index 0 or 1 in the given string.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public boolean hasGood(String str) 
{
  if(str.length() < 4)
    return false;
  else if ((str.substring(0,4)).equals("good"))
    return true;
  else if (str.length() > 4)
  {
    if ((str.substring(1,5)).equals("good"))
      return true;
  }
    return false;
}
public static void main (String[] args)
    {
      Main m= new Main();
      String str1 =  "goodboy";
	  
      System.out.println("The given strings is: "+str1);
      System.out.println("The 'good' appear in the string is: "+m.hasGood(str1));
	  }
}

Sample Output:

The given strings is: goodboy
The 'good' appear in the string is: true

Flowchart:

Flowchart: Java String Exercises - Read a string and return true if "good" appears starting at index 0 or 1 in the given string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to read a string and an int n, return a string made of the first and last n characters from the string.
Next: Write a Java program to return true from a given string if the first two characters in the string also appear at the end.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming