Dremendo Tag Line

String in Java Programming

String in Java

In this lesson, we will understand what is String in Java Programming along with some examples.

What is String in Java

A String is a class in java which is used to store a sequence of characters in the form of a character array. A String is immutable means that it can't be altered directly once it is created. To alter its value, we have to replace it with the newly created string.

A string in java can be created in three ways using.

  • String Class
  • StringBuffer Class
  • StringBuilder Class

In this lesson we will discuss about the String Class and its various methods. StringBuffer and StringBuilder class will be discussed in the subsequent lessons.

video-poster

String Literal and String Object

A String class be used in two ways to store a string, either by creating a Literal or by creating an Object.

Syntax of Creating a String Literal

String literal_name="string value";

Example

String s1="Dremendo";

Here we have declared a string literal s1 and initialize it with the string value Dremendo.

Syntax of Creating a String Object

String object_name=new String("string value");

Example

String s2=new String("Dremendo");

Here we have declared a string object s2 and initialize it with the string value Dremendo.

Difference Between String Literal and String Object

The difference between string literal and string object is that.

  • When we create two string literals, having the same string in it. They will not create two separate space in the heap memory to store the same string. Both the literals will point to a common space in the heap memory where the string is stored.
  • When we create two string object, having the same string in it. They will create two separate space in the heap memory to store the same string. Both the objects will point to a different space in the heap memory where the strings are stored.

Let's see the example given below.

Example

String x1="Dremendo", x2="Dremendo";
String y1=new String("Dremendo");
String y2=new String("Dremendo");
string literal and string object example

Note: A String Literals is also an object of String class, but it does not create separate space if the string value is already available in the heap memory. It points to space already created before by some other literal with the same string value, as shown in the above image.

Methods of String Class

String methods are useful functions used to perform a specific task on the string. Below we have discussed all the important string methods available in the String class.

length() Method

The length() method returns the total number of characters (including space) present in the string.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s;
        int l;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a string");
        s=sc.nextLine();
        l=s.length();
        System.out.println("Length="+l);
    }
}

Output

Enter a string
Hello World
Length=11

charAt() Method

The charAt() method returns the character at the specified index. In a string, the first character starts from index 0.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a string");
        s=sc.nextLine();
        System.out.println("Character at index 3="+s.charAt(3));
    }
}

Output

Enter a string
Dremendo
Character at index 3=m

indexOf() Method

The indexOf() method returns the index of the first occurrence of the specified character or string within the current string. The indexOf() method accepts two arguments. The first argument is the string or character and the second optional argument is the index from where we want to check the occurrence. If the index is not given, it will start checking the occurrence from index 0.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        System.out.println("The 2nd string first occur at index " + s1.indexOf(s2) + " in the first string.");
        System.out.println("After index 5, the 2nd string first occur at index " + s1.indexOf(s2,5) + " in the first string.");
    }
}

Output

Enter 2 strings
I am a boy and I love java programming.
I
The 2nd string first occur at index 0 in the first string.
After index 5, the 2nd string first occur at index 15 in the first string.

lastIndexOf() Method

The lastIndexOf() method returns the index of the last occurrence of the specified character or string within the current string.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        System.out.println("The 2nd string last occur at index " + s1.lastIndexOf(s2) + " in the first string.");
    }
}

Output

Enter 2 strings
I am a boy and I love playing football.
I
The 2nd string last occur at index 15 in the first string.

compareTo() Method

The compareTo() method compares two strings lexicographically including case sensitive comparison. It returns a negative value if the first string is less then the second string. A positive value if the first string is greater than the second string. It returns zero if both are same.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        if(s1.compareTo(s2)==0)
        {
            System.out.println("Both are same string");
        }
        else
        {
            System.out.println("They are not same");
        }
    }
}

Output

Enter 2 strings
Apple
apple
They are not same

compareToIgnoreCase() Method

The compareToIgnoreCase() method compares two strings lexicographically ignoring case sensitive comparison. It returns a negative value if the first string is less then the second string. A positive value if the first string is greater than the second string. It returns zero if both are same.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        if(s1.compareToIgnoreCase(s2)==0)
        {
            System.out.println("Both are same string");
        }
        else
        {
            System.out.println("They are not same");
        }
    }
}

Output

Enter 2 strings
Apple
ApPlE
Both are same string

equals() Method

The equals() method compares two strings, including case sensitive comparison. It returns true if both the string contents are same otherwise it returns false.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        if(s1.equals(s2)==true)
        {
            System.out.println("Both are same string");
        }
        else
        {
            System.out.println("They are not same");
        }
    }
}

Output

Enter 2 strings
Orange
Orange
Both are same string

equalsIgnoreCase() Method

The equalsIgnoreCase() method compares two strings, ignoring case sensitive comparison. It returns true if both the string contents are same otherwise it returns false.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        if(s1.equalsIgnoreCase(s2)==true)
        {
            System.out.println("Both are same string");
        }
        else
        {
            System.out.println("They are not same");
        }
    }
}

Output

Enter 2 strings
BanaNA
baNaNa
Both are same string

startsWith() Method

The startsWith() method returns true if the first string starts with the specified second string, otherwise, it returns false. The startsWith() method accepts two arguments. The first argument is the string and the second optional argument is the index from where we want to check. If the index is not given, it will start checking from index 0.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        if(s1.startsWith(s2)==true)
        {
            System.out.println("Yes, 1st string starts with the 2nd string from index 0.");
        }
        else
        {
            System.out.println("No, 1st string does not starts with the 2nd string from index 0");
        }

        // We are checking if the string s1 starts with the string s2 from index 15.
        if(s1.startsWith(s2,15)==true)
        {
            System.out.println("Yes, 1st string starts with the 2nd string from index 15.");
        }
        else
        {
            System.out.println("No, 1st string does not starts with the 2nd string from index 15");
        }
    }
}

Output

Enter 2 strings
I am a boy and I love gaming.
I
Yes, 1st string starts with the 2nd string from index 0.
Yes, 1st string starts with the 2nd string from index 15.

endsWith() Method

The endsWith() method returns true if the first string ends with the specified second string, otherwise, it returns false.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        if(s1.endsWith(s2)==true)
        {
            System.out.println("Yes, 1st string ends with the 2nd string.");
        }
        else
        {
            System.out.println("No, 1st string does not ends with the 2nd string.");
        }
    }
}

Output

Enter 2 strings
I am learning Java
Java
Yes, 1st string ends with the 2nd string.

contains() Method

The contains() method returns true if the string contains the specified sequence of char values in it. Otherwise, it returns false.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        if(s1.contains(s2)==true)
        {
            System.out.println("Yes, 1st string contains the 2nd string in it.");
        }
        else
        {
            System.out.println("No, 1st string does not contains the 2nd string in it.");
        }
    }
}

Output

Enter 2 strings
Hello how are you?
are
Yes, 1st string contains the 2nd string in it.

concat() Method

The concat() method concatenates the specified string to the end of the current string, but it does not originally update the current string. To update the current string we have to replace it with the concatenated string as shown in the example below.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1,s2;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 2 strings");
        s1=sc.nextLine();
        s2=sc.nextLine();

        // Concatenated string
        System.out.println("Concatenated string");
        System.out.println(s1.concat(s2));

        // Original string
        System.out.println("Original string");
        System.out.println(s1);

        // Update the original string with the concatenated string
        s1=s1.concat(s2);

        // Original string after replacing it with the concatenated string
        System.out.println("Original string after replacing it with the concatenated string");
        System.out.println(s1);
    }
}

Output

Enter 2 strings
good
bye
Concatenated string
goodbye
Original string
good
Original string after replacing it with the concatenated string
goodbye

replace() Method

The replace() method returns a new string after replacing all the occurrences of a specified character or string with the other specified character or string.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a string");
        s1=sc.nextLine();

        System.out.println(s1.replace('a','p'));
        System.out.println(s1.replace("dog","cat"));
    }
}

Output

My dog name is max. My dog loves to eat meat every day.
My dog npme is mpx. My dog loves to ept mept every dpy.
My cat name is max. My cat loves to eat meat every day.

substring() Method

The substring() method returns a new string which is a substring of the current string.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a string");
        s1=sc.nextLine();

        System.out.println("Print the 1st 3 characters of the current string");
        System.out.println(s1.substring(0,3));
        System.out.println("Print the 1st 3 characters starting from index 2 and stopping at index 5");
        System.out.println("The stopping index is not included in the substring");
        System.out.println(s1.substring(2,5));
        System.out.println("Print all the characters starting from index 3 till end");
        System.out.println(s1.substring(3));
    }
}

Output

Enter a string
Dremendo
Print the 1st 3 characters of the current string
Dre
Print the 1st 3 characters starting from index 2 and stopping at index 5
The stopping index is not included in the substring
eme
Print all the characters starting from index 3 till end
mendo

toLowerCase() Method

The toLowerCase() method returns a new string after converting all the characters of the string in lowercase.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a string");
        s1=sc.nextLine();
        System.out.println(s1.toLowerCase());
    }
}

Output

Enter a string
Hello World
hello world

toUpperCase() Method

The toUpperCase() method returns a new string after converting all the characters of the string in uppercase.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a string");
        s1=sc.nextLine();
        System.out.println(s1.toUpperCase());
    }
}

Output

Enter a string
Hello World
HELLO WORLD

trim() Method

The trim() method returns a new string after removing all the whitespaces from beginning and end of the string.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a string");
        s1=sc.nextLine();
        System.out.println(s1.trim());
    }
}

Output

Enter a string
    Hello World
Hello World

toCharArray() Method

The toCharArray() method converts the string to a new character array for easy manipulation.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        String s1;
        char a[];
        int i;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a string");
        s1=sc.nextLine();
        a=s1.toCharArray();

        // Printing the character array on the screen
        for(i=0; i<a.length; i++)
        {
            System.out.println(a[i]);
        }
    }
}

Output

Enter a string
Computer
C
o
m
p
u
t
e
r

Note: You can convert a string into a character array if you want to apply a sorting algorithm on it to arrange the characters in either ascending or descending order.

Methods of Character Class

Character methods are useful functions used to perform a specific task on a character. Below we have discussed all the important character methods available in the Character class.

isAlphabetic() Method

The isAlphabetic() method returns true if the character is an alphabet. Otherwise, it returns false.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        char c;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a character");
        c=sc.nextLine().charAt(0);
        System.out.println(Character.isAlphabetic(c));
    }
}

Output

Enter a character
a
true

isDigit() Method

The isDigit() method returns true if the character is a digit. Otherwise, it returns false.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        char c;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a character");
        c=sc.nextLine().charAt(0);
        System.out.println(Character.isDigit(c));
    }
}

Output

Enter a character
8
true

isUpperCase() Method

The isUpperCase() method returns true if the character is an uppercase character. Otherwise, it returns false.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        char c;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a character");
        c=sc.nextLine().charAt(0);
        System.out.println(Character.isUpperCase(c));
    }
}

Output

Enter a character
D
true

isLowerCase() Method

The isLowerCase() method returns true if the character is a lowercase character. Otherwise, it returns false.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        char c;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a character");
        c=sc.nextLine().charAt(0);
        System.out.println(Character.isLowerCase(c));
    }
}

Output

Enter a character
d
true

toUpperCase() Method

The toUpperCase() method returns the uppercase version of the given character.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        char c;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a character");
        c=sc.nextLine().charAt(0);
        System.out.println(Character.toUpperCase(c));
    }
}

Output

Enter a character
d
D

toLowerCase() Method

The toLowerCase() method returns the lowercase version of the given character.

Example

import java.util.Scanner;

public class StringMethod
{
    public static void main(String args[])
    {
        char c;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a character");
        c=sc.nextLine().charAt(0);
        System.out.println(Character.toLowerCase(c));
    }
}

Output

Enter a character
D
d

Test Your Knowledge

Loading