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.


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.


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”, “”, 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 >>


This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, 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:

Show Details
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 or domains, for performance and efficiency reasons. (Privacy Policy)
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)
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.
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)