String in Java

String In Java

A String is a sequence of characters. It is used to store textual data. E.g., to store your name, you can use String. You must use double quotes to represent a string in Java.

Example

public class Main {
    public static void main(String[] args) {
        // String Literal
            String str = "Hello World";
            // Printing String
            System.out.println(str);
    }
}
Show Output

Methods Of String

Java provides various String methods to perform multiple operations in String. Here are some essential & commonly used methods.

  • charAt(): It is used to get a character at the specified index.
  • concat(): It is used to join two string.
  • equals(): It is used to check if two string are equal or not.
  • length(): It is used to get the length of a String.
  • replace(): It is used to replace a string with another string.
  • substring(): It is used to get a substring from a string.
  • toUpperCase(): It is used to make text uppercase.
  • toLowerCase(): It is used to make text lowercase.
  • isEmpty(): It checks whether a string is empty for not.

String Methods Example In Java

This example shows how we can use different string methods in java. All are powerful and commonly used methods.

public class Main {
    public static void main(String[] args) {
         // String Literal
                String str = "Hello World";
                String str1 = "Hello World";
    
                // charAt()
                System.out.println(str.charAt(0));
    
                // concat()
                System.out.println(str.concat(" ").concat("Java"));
    
                // equals()
                System.out.println(str.equals(str1));
    
                // length()
                System.out.println(str.length());
    
                // replace()
                System.out.println(str.replace("World", "Java"));
    
                // substring()
                System.out.println(str.substring(0, 5));
    }
}
Show Output