ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 21

Updated on October 16, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Lesson 21: How to search for a character or string in Java

When working with strings in Java programming language, in some cases you would like to search for a character or string to determine if it is appearing in a given string.

For example, a user is required to enter an email address in a user input box, the validation of the email address may involve checking if the symbol character “@” is appearing in the email address. An email address without the standard “@” symbol character may be passed as invalid.

Source

Java programming language provides several methods of checking if a character or string is found in another string. In this particular lesson, we shall discuss the Java indexOf() method.

To learn how to search for a character using the indexOf() method, we are going to write a simple program in Java to search if the symbol character “@” is appearing in a given email address.

Later, we shall modify the program to be more meaningful by displaying the appropriate messages if the email address is valid or not.

We shall also see how we can write a more better program to validate an email address by checking if the email address has the "@" symbol character or the ".com" part.

Create a new Java class, call it SearchString and type the following code.

A Java program to search for a given character in a string

In the above program, we have created a char variable to store the “@” symbol in the email address. The string with email address is in another variable named myEmail.

char atsymbol = '@';

String myEmail = "lessons@java.com"; //Type as a single line

Notice that to store a single character variable in Java as we learnt in Lesson 4, we use a variable of type char (lowercase "c") and then surround the character with single quotes and not double quotes as in string variables.

Using the indexOf() method, we are searching the string in myEmail variable to see if it contain the “@” symbol. The method indexOf() returns a digit number position representing the position where the character was found in the string.

int result;

result = myEmail.indexOf(atsymbol);

The counting starts from 0 and not 1. However, if the character is not found, indexOf() method returns -1 digit number. It is this returned digit number that we are capturing in the result variable and then outputing the appropriate message using IF .. ELSE conditional statement.

Now, run the above program and you’ll find that, counting from zero, indexOf() method will return a digit number 7 along with the joined message.

Delete the “@” symbol in the email address and run the program again, this time, as you would expect, the method indexOf() will return -1 as the "@" symbol is not found.

Let us write another program that will check the “@” symbol in the email address as we did in the above program and also check if the email address has the “.com” part. This time we shall let the user to enter the email address. For this purpose, you can modify the above program or create a new Java class. Type the following program and run.

A Java program to search for a string in a another string

package myfirstprogram;
import javax.swing.JOptionPane;
public class SearchString {
  public static void main(String[] args) {
   char atsymbol = '@'; //A char variable to store "@" symbol
   String dotcom = ".com"; // A string variable to store ".com" part
   String myEmail = JOptionPane.showInputDialog("Enter Email address:");
    
   int result1, result2;
   result1 = myEmail.indexOf(atsymbol); //Using indexOf(), we search for "@"
   result2 = myEmail.indexOf(dotcom); //Using indexOf(), we search for ".com"
    
   if(result1 >=0 && result2 >=0){  //Using nested IF .. ElSE for outputs
    JOptionPane.showMessageDialog(null,"Valid Email address");
     }
   else if(result1 < 0){
     JOptionPane.showMessageDialog(null,"'@' symbol missing in the Email address"); 
    }
   else if(result2 < 0){
     JOptionPane.showMessageDialog(null,".com part missing in the Email address"); 
    }
  }   
}

When you run the program, you’ll be able to input an email address of your choice. Run the program with an email address without the “@” symbol, without the “.com” part and finally with the correct email address. You should be able to get the following outputs.

Methods to search for a given string in Java programming language are many and it depends on how the programmer wants to search the string. In the above program, for example, we could have used another Java method called endsWith() to check if the email address ends with a “.com” part. To use endsWith() method, you have to set a Boolean variable to store the returned value because this method returns a true or false value.

Boolean ending = myEmail.endsWith(dotcom);

Another method that works like the endsWith() method in Java is the startsWith(). It checks if a string starts with a certain given string, here too you have to set a Boolean variable. Go ahead and try these methods on your own. In the next lesson, we shall look at how to use the substring() method in Java. See you then.

<< Lesson 20 | Lesson 22 >>

Comments

    0 of 8192 characters used
    Post Comment
    • profile image

      ankit 

      7 years ago

      good

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hello dinkan53,

      Thanks for the complement, i get extra strength when i know that an article i wrote did help someone. I do appreciate you stopping here and commenting.

    • dinkan53 profile image

      dinkan53 

      7 years ago from India

      Went through some of your lessons. I must admit that your works are very useful and it is nice to help others by your hard works. I will appreciate if you continue this in future. Voted.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)