ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Java Examples 001 - Strings

Updated on December 26, 2017
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. 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