ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java String Examples

Updated on May 19, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like playing video games & reading books.

1. Creating Java String

The first thing one know should know is that Java Strings are not primitive type. They are objects in Java. The String objects once constructed can not be changed. The java Strings like other programming languages are used to store texts. In this hub we are going to see basic Java String Examples.

A Java String can be created in many ways.

The below example shows creating a Java String and printing it in the console output window:

public class Main
{
    public static void main(String[] args)
    {
        //Declaring and Initializing
        String Str1 = "First String";

        //Constructing the string
        String Str2 = new String();
        Str2 = "Second String";

        //Constructing string from Char Array
        char Chr1[] = {'T','h','i','r','d',' ', 
                'S','t','r','i','n','g'};
        String Str3 = new String(Chr1);

        System.out.println(Str1);
        System.out.println(Str2);
        System.out.println(Str3);
    }
}

Explanation

Line 6: Here, we created a string and got reference to it in the variable Str1.

Line 9-10: Here, First a Java String Str2 constructed as empty string and the a string literal "Second String" and assigned to it.

Line 12-15: First an Array of Characters is created and for the memory is stored in Chr1. Then, the String Str3 is constructed from this Char Array Chr1 (Line 15).

The output of this First Example is given below:

Java String Example 1: Output
Java String Example 1: Output | Source

2. String Length

The length() method of the String object will return the length of the string. Have a look at the below Example:

public class Main
{
    public static void main(String[] args)
    {
        //001.1 Declaring and Initializing
        String Str1 = "First String";

        //001.2 Length of the String
        System.out.println("Length:" + Str1.length());
    }
}

This will print "Length:12" in the console output window.

3. Concatenating Strings

3.1 Using concat() method

A String in java can be concatenated using the + operator or using "concat()" method String. Let us see an example for both. Have a look at the example below:

public class Main
{
    public static void main(String[] args)
    {
        //Sample 1.0: Join String by Concat method
        String S1 = "Java ";
        String S2, S3;
        S2 = S1.concat("String ");
        S3 = S2.concat("Example");
        System.out.println(S3);
    }
}

Note that in the above code We created a string called "Java" and have reference S1. Then we created one more string S2 by appending the "String " with S1 by calling concat() method. The same way string S3 is created. The string S3 when printed gives - Java String Example as output.

Concatenating string means joining them together

3.2 Using '+' operator

Note that a string once constructed can not be changed. That is why; here we created three strings and finally printed S3. The more easy we to join string is shown in the below example:

public class Main
{
    public static void main(String[] args)
    {
        //Sample 1.0: Join String by Concat method
        String S1 = "Java ";
        String S2 = "String ";
        System.out.println(S1 + S2 + "Example");
    }
}

Here, the + operator is used to join the strings S1 and S2 with the string literal "Example".

4. Getting String Characters

4.1 Getting single character

The string is a combination of characters packed together. The "charAt()" method will help getting a particular character from the string. Have a look at the example below:

public class Main
{
    public static void main(String[] args)
    {
        //Sample 01: Take single char @ position
        String S1 = "Example String";
        char c1 = S1.charAt(2);
        char c2 = S1.charAt(10);

        //Sample 02: Print Char
        System.out.println("Character at position 2:" + c1);
        System.out.println("Character at position 10:" + c2);
    }
}

In the above code, at line 7 the character position at 2 is retrieved and stored in c1. The c1 will have letter “a” and the same way c2 will have “r”. The output of this example is shown below:

Java String charAt() Example - Output
Java String charAt() Example - Output | Source

4.2 Getting Range of character from String

The getChars() method of java string is useful to grab range of characters from the string. Now have a look at the below example:


public class Main
{
    public static void main(String[] args)
    {
        //Sample 01: Take single char @ position
        String S1 = "This is an example String";
        char[] chrarr = new char[7];
        S1.getChars(11, 18, chrarr, 0);

        System.out.println(chrarr);
    }
}

Explanation

Line 6: A String S1 is created.

Line 7: A New character array which can hold 7 elements is created.

Line 8: The "getChars()" method of String is called to fill the chrarr array. The first two parameters tell position start and end in the "Source String" and third parameter is the destination array that needs to be filled. In our case, it is chrarr. The fourth parameter says start location of the destination.

The program will output: example


5. Getting SubString of a given String

The “substring()” method is used to get portion of string from a given string. The example for this is given below:

public class Main
{
    public static void main(String[] args)
    {
        //Sample 01: Take Sub-String
        String S1 = "This is an example String";

        //Sample 02: Sub-String 1
        String S2 = S1.substring(8, 18);

        //Sample 03: Sub-String 2
        String S3 = S1.substring(11);

        System.out.println("Main String " +
                S1);
        System.out.println("Sub-String 1: " +
                S2);
        System.out.println("Sub-String 2: " +
                S3);

    }
}

Explanation

In this example, at line 9, we are making call to the "substring()" function. We are passing two parameters which denote the character position of the string. The first parameter is starting location of the sub-string and second parameter specifies the stop location. With these two parameters, the retrieved sub-string is stored in String S2.

At Line 12, we just pass the start location of the string and sub-string function knows that it should stop at end-of the string. Output of this example is shown below:

Java substring() Example - output
Java substring() Example - output | Source

6. Searching for String

There are two methods which is used in java to search for a string in the given string. The method "indexOf()" is used to find the first occurrence of a string. The method "lastIndexOf()" is used to find the last occurrence of the string. Both these methods will give position based index which tells found location of the string. Now, look at the example below:


public class Main
{
    public static void main(String[] args)
    {
        //Sample 01: Take Sub-String
        String S1 = "He Draws nice Drawings" +
                "Through DrawPad Application";

        //Sample 02: Find First and Last Occurence of draw
        int pos1 = S1.indexOf("Draw");
        int pos2 = S1.lastIndexOf("Draw");

        //Sample 03: Output the positions
        System.out.println("First occurance" +
                " of Draw: " + pos1);
        System.out.println("Last occurance" +
                "of Draw: " + pos2);
    }
}

Below is the output of the Example:

First occurance of Draw: 3
Last occuranceof Draw: 30

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    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)