DEV Community

Preethi Nandhagopal
Preethi Nandhagopal

Posted on

String Predefined Method

String Method:
The String class provides many predefined methods that help you perform operations like comparison, searching, modification, conversion, etc., on string objects.

startsWith() / endsWith()-> Checks if the string starts or ends with a specified sequence.
toLowerCase() / toUpperCase()-> Converts string to lowercase or uppercase.
trim()-> Removes leading and trailing whitespace.
toCharArray()-> Converts a string into a character array.
substring()-> Extracts a part of the string.
split()-> Splits a string based on a regex.
isEmpty()-> Checks if the string is empty.
length()-> Returns the length of the string.
charAt()-> method is a predefined method in the String class that returns the character at a specified index in the string.
isBlank()-> method is a predefined method in the String class that checks whether a string is empty or contains only whitespace characters.
replace()-> method replaces all occurrences of a character or substring with another character or substring.
replaceAll()-> method replaces all substrings matching a regular expression with the given replacement.
join()-> method combines multiple strings using a delimiter.
contains()-> Checks if a sequence of characters is present in the string.

Program using above methods:
package String_Project;

public class StringLearning {
public static void main(String[] args) {
String s=new String("welcome java");
System.out.println(s);

    char charAt= s.charAt(0);
    System.out.println(charAt);

    boolean st = s.startsWith("we");
    System.out.println(st);

    boolean ed = s.endsWith("me");
    System.out.println(ed);

    String tr = s.trim();
    System.out.println(tr);

    int length =s.length();
    System.out.println(length);

    boolean contains=s.contains("come");
    System.out.println(contains);

    String upper = s.toUpperCase();
    System.out.println(upper);

    String lower=s.toLowerCase();
    System.out.println(lower);

    char[] arr=s.toCharArray();
    System.out.println(arr);

            boolean empty = s.isEmpty();
    System.out.println(empty);

    boolean blank=s.isBlank();
    System.out.println(blank);

    String substring = s.substring(2);
    System.out.println(substring);

    String substring1 = s.substring(0,2);
    System.out.println(substring1);

    String replace=s.replace('w','i');
    System.out.println(replace);

    String replace1=s.replace("java","world");
    System.out.println(replace1);

    String replaceAll=s.replaceAll("[aeiou]", "*");
    System.out.println(replaceAll);

    String[] parts=s.split(" ");
    System.out.println(parts[0]);
    System.out.println(parts[1]);

    }
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)