java


String Handling and String Methods in Java


In Java, strings are one of the most commonly used data types. Whether you’re creating messages, reading user input, or working with file data, you’ll find yourself working with strings often.

Unlike primitive types (like int, char, double), strings in Java are objects of the String class, making them immutable — once created, they cannot be changed.

 

Creating Strings in Java

// Using string literal
String str1 = "Hello";

// Using the 'new' keyword
String str2 = new String("World"); 

Using String Methods

public class StringExample {
    public static void main(String[] args) {
        String text = "  Java Programming  ";

        System.out.println("Original: '" + text + "'");
        System.out.println("Length: " + text.length());
        System.out.println("Trimmed: '" + text.trim() + "'");
        System.out.println("Uppercase: " + text.toUpperCase());
        System.out.println("Lowercase: " + text.toLowerCase());
        System.out.println("Substring (0-4): " + text.substring(0, 4));
        System.out.println("Contains 'Java'? " + text.contains("Java"));
        System.out.println("Replace 'Java' with 'Python': " + text.replace("Java", "Python"));
    }
}