ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on October 16, 2019
dwachira profile image

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

Source

Lesson 22: How to use substring() method in Java

In Lesson 21, we learnt about the Java indexOf() method and how to use this method to search for a character or string in a given string in Java programming language. In this particular lesson, we shall discuss another useful string method called subtring() method.

The Java substring() method is used to extract a given part of string from another string. Let us say you run a business and you would like to greet your clients with the last name when emailing them. If you have a client with a name like “Paul Smith”, then you can use substring() to extract the last name “Smith” from the full name.

To use the Java substring() method, you have to specify the starting position from where the method should start extracting the characters in a given string. After the extraction position you put a comma and then you specify number of characters to extract. The syntax of using substring() method is as follow:

String_to_extract_from.substring(Starting_Position, Number_of_characters_to_extract);

e.g. lastname.substring(0, 5);

From the above example, the statement when used substring() method, will extract 5 characters from a string variable called lastname starting at position 0.

One thing about substring() method is that if you want to extract some characters from a string at a given starting position all the way to the end of that string, then you can omit to specify the number of characters to extract. The method will grab all the characters after the starting position to the end of string.

Now, let us write a program to greet clients with their last name as stated above. We’ll let the user to enter first name and last name in an input box and then grab the last name and use it in greetings.

For us to be able to grab the last name, we should be able to specify where the last name starts. The last name will start just after the space, so we should be able to tell at what position is space in the full name.

The Java indexOf() method we discussed in Lesson 21 will work perfectly here i.e. we can use it to tell at what position is space in the full name. Create a new Java class, call it greetings, type and run the following code

Java program using substring() method

package myfirstprogram;
import javax.swing.JOptionPane;

public class Greetings {
  public static void main(String[] args) {
     String Lastname = ""; //A variable to store last name
     String NameSpace = " "; //A variable to store space
     int spacePosition;
     
     String Fullname = JOptionPane.showInputDialog("Enter your name:");
     
     spacePosition = Fullname.indexOf(NameSpace); //Determine space position
     Lastname = Fullname.substring(spacePosition); //Extract last name just after space position
     JOptionPane.showMessageDialog(null,"Hello "+Lastname+", This is just "
        + "a test of the Java substring() method. Thank you.");
  }   
}

In the above program, we want to capture the last name after space and store it in a variable named “Lastname”.

String Lastname = "";

We also need to know the position of the space in the full name and we are doing so by use of indexOf() method.

spacePosition = Fullname.indexOf(NameSpace);

Finally, having known the space position in the full name, we grab the last name, store it in the lastname variable and output the message.

Lastname = Fullname.substring(spacePosition);

Notice that in the above program we have not specified the number of characters to extract from the full name simply because we want everything from the space position to the end.

Exercise:

What will happen if the user enter “Paul Smith Willis”? How do we extract “Willis” only and not “Smith Willis”?

The following program also make use of Java substring() and indexOf() methods to determine whether an email address ends with a “.com”, “co.uk”, or any other email domain. Create another Java class and try it out.

Java program using substring() method

package myfirstprogram;
import javax.swing.JOptionPane;

public class UsingSubstring {
  public static void main(String[] args) {
     String EmailEnding = ""; //A variable to store email domain
     String Emaildot = "."; //A variable to store dot character
     int dotPosition;
     
     String myEmail = JOptionPane.showInputDialog("Enter Email address:");
     
     dotPosition = myEmail.indexOf(Emaildot); //Determine dot position
     EmailEnding = myEmail.substring(dotPosition); //Extract domain after the dot
     JOptionPane.showMessageDialog(null,"Your Email address ends with "+EmailEnding);
  }   
}

I would recommend that you try many varied examples of programs that deals with substring() method. In that way, you shall learn many techniques of using the method or combining the method with other methods such as indexOf() or equals() that we shall look into in our next lesson.

<< Lesson 21 | Lesson 23 >>

Comments

    0 of 8192 characters used
    Post Comment
    • profile image

      Doogie 

      5 years ago

      thanks man, I had an issue with a program, but your way for programming let me get out of my own bug and find a solution (y),

    • Jakov Andric profile image

      Jakov 

      6 years ago from Varazdin

      Exercise solution:

      Easiest way to solve it is to use lastIndexOf method

      String space = " ";

      String lastname = "";

      int index_of_space;

      String fullname = JOptionPane.showInputDialog("Full name: ");

      index_of_space=fullname.lastIndexOf(space);

      lastname =fullname.substring(index_of_space);

      JOptionPane.showMessageDialog(null,"lastname: "+lastname);

      ...and output should be the last string

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Thanks teaches12345 for the support, reading and commenting. Enjoy your day.

    • teaches12345 profile image

      Dianna Mendez 

      7 years ago

      Another great technological lesson to learn from a great teacher! Thanks for sharing.

    • tammyswallow profile image

      Tammy 

      7 years ago from North Carolina

      You have some serious technical abilities! This is impressive.

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi Lord De Cross,

      I feel humbled receiving these kind words from you, i find a lot of young programmers always seeking information about coding. I hope those seeking information will come from the places you've mentioned and beyond. Thanks for finding time to stop here, reading and commenting. From here, it is Lala salama!

    • Lord De Cross profile image

      Joseph De Cross 

      7 years ago from New York

      Gee! Danson, this lesson was like adding 3+3. I know you don't get comments, but you are read by young college students from UK, West Africa and even India. What I remember is that semicolons (;) are crucial in these java arrays. Keep it up buddy! You are doing an awesome job!

    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://hubpages.com/privacy-policy#gdpr

    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)