This article presents some Examples of Java String Methods.

The following code shows a Java program that defines a class called StringDemo and demonstrates the use of the length, charAt, and equals functions on three strings.

public class StringDemo {
    public static void main(String[] args) {
        // Declare three strings
        String str1 = "Hello, World!";
        String str2 = "Java Programming";
        String str3 = "Hello, World!";

        // Using the length() function to get the length of a string
        int length1 = str1.length();
        int length2 = str2.length();

        System.out.println("Length of str1: " + length1);
        System.out.println("Length of str2: " + length2);

        // Using the charAt() function to access characters in a string
        char char1 = str1.charAt(0); // Get the first character
        char char2 = str2.charAt(5); // Get the character at index 5

        System.out.println("First character of str1: " + char1);
        System.out.println("Character at index 5 of str2: " + char2);

        // Using the equals() function to compare strings
        boolean isEqual1to2 = str1.equals(str2);
        boolean isEqual1to3 = str1.equals(str3);

        System.out.println("str1 equals str2: " + isEqual1to2);
        System.out.println("str1 equals str3: " + isEqual1to3);

In this program:

  1. At first, we declare three strings: str1, str2, and str3.
  2. Then, we use the length() function to determine the length of str1 and str2 and print the results.
  3. After that, we use the charAt() function to access specific characters in str1 and str2 and print the characters.
  4. Finally, we use the equals() function to compare str1 with str2 and str1 with str3 and print the results.

Compile and run this Java program, and it will demonstrate the usage of these string functions.

Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise