0
0
Javaprogramming~15 mins

Common string methods in Java

Choose your learning style8 modes available
menu_bookIntroduction

String methods help you work with text easily. They let you check, change, or find parts of words or sentences.

When you want to check if a word contains a certain letter or part.
When you need to change all letters to uppercase or lowercase.
When you want to find where a word or letter appears in a sentence.
When you want to cut out a piece of a sentence.
When you want to replace some words with others.
regular_expressionSyntax
Java
string.methodName(arguments);
Replace string with your text variable or text in quotes.
Replace methodName with the name of the string method you want to use.
emoji_objectsExamples
line_end_arrow_notchCheck if the text contains the word "Hello".
Java
String text = "Hello World";
boolean hasHello = text.contains("Hello");
line_end_arrow_notchChange all letters in the text to uppercase.
Java
String text = "Hello World";
String upper = text.toUpperCase();
line_end_arrow_notchFind the position of the letter 'W' in the text.
Java
String text = "Hello World";
int pos = text.indexOf('W');
line_end_arrow_notchGet the part of the text starting from position 6 to the end.
Java
String text = "Hello World";
String part = text.substring(6);
code_blocksSample Program

This program shows common string methods: checking if text contains a word, changing to uppercase, finding a letter's position, getting a part of the text, and replacing words.

Java
public class Main {
    public static void main(String[] args) {
        String message = "Java is fun!";

        // Check if message contains "fun"
        boolean containsFun = message.contains("fun");
        System.out.println("Contains 'fun': " + containsFun);

        // Convert message to uppercase
        String upperMessage = message.toUpperCase();
        System.out.println("Uppercase: " + upperMessage);

        // Find position of 'i'
        int indexI = message.indexOf('i');
        System.out.println("Position of 'i': " + indexI);

        // Get substring from position 5
        String sub = message.substring(5);
        System.out.println("Substring from 5: " + sub);

        // Replace 'fun' with 'awesome'
        String replaced = message.replace("fun", "awesome");
        System.out.println("Replaced text: " + replaced);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

String positions start at 0, so the first letter is at position 0.

line_end_arrow_notch

Methods like substring do not change the original string but return a new one.

line_end_arrow_notch

Strings in Java are case sensitive, so "Fun" and "fun" are different.

list_alt_checkSummary

Use string methods to easily check, change, or find parts of text.

Common methods include contains, toUpperCase, indexOf, substring, and replace.

Remember that strings do not change themselves; methods return new strings.