Strings in Java

Strings are one of the most commonly used data types in Java. They represent sequences of characters and are immutable, meaning their values cannot be changed after creation.

String Basics

Creating Strings

StringBasics.java
public class StringBasics {
    public static void main(String[] args) {
        // Different ways to create strings
        String str1 = "Hello";           // String literal
        String str2 = new String("Hello"); // Using constructor
        String str3 = " World";          // Another literal
        
        // String concatenation
        String greeting = str1 + str3;
        System.out.println("Greeting: " + greeting);
        
        // Using String.format()
        String formatted = String.format("Name: %s, Age: %d", "John", 25);
        System.out.println("Formatted: " + formatted);
        
        // Comparing strings
        String s1 = "Java";
        String s2 = "Java";
        String s3 = new String("Java");
        
        System.out.println("s1 == s2: " + (s1 == s2));        // true (same literal)
        System.out.println("s1 == s3: " + (s1 == s3));        // false (different objects)
        System.out.println("s1.equals(s3): " + s1.equals(s3)); // true (same content)
    }
}

Common String Methods

StringMethods.java
public class StringMethods {
    public static void main(String[] args) {
        String text = "Hello World Programming";
        
        // Length
        System.out.println("Length: " + text.length());
        
        // Character at position
        System.out.println("Char at 0: " + text.charAt(0));
        
        // Substring
        System.out.println("Substring 0-5: " + text.substring(0, 5));
        System.out.println("Substring 6: " + text.substring(6));
        
        // Case conversion
        System.out.println("Uppercase: " + text.toUpperCase());
        System.out.println("Lowercase: " + text.toLowerCase());
        
        // Trim (removes leading and trailing whitespace)
        String spaced = "   Hello World   ";
        System.out.println("Original: '" + spaced + "'");
        System.out.println("Trimmed: '" + spaced.trim() + "'");
        
        // Contains, startsWith, endsWith
        System.out.println("Contains 'World': " + text.contains("World"));
        System.out.println("Starts with 'Hello': " + text.startsWith("Hello"));
        System.out.println("Ends with 'Programming': " + text.endsWith("Programming"));
        
        // Replace
        System.out.println("Replace 'World' with 'Java': " + text.replace("World", "Java"));
        
        // Split
        String[] words = text.split(" ");
        System.out.println("Words: " + java.util.Arrays.toString(words));
    }
}

String Manipulation Examples

StringManipulation.java
import java.util.Arrays;

public class StringManipulation {
    // Reverse a string
    public static String reverse(String str) {
        StringBuilder sb = new StringBuilder(str);
        return sb.reverse().toString();
    }
    
    // Count occurrences of a character
    public static int countChar(String str, char ch) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ch) {
                count++;
            }
        }
        return count;
    }
    
    // Check if string is palindrome
    public static boolean isPalindrome(String str) {
        // Remove non-alphanumeric characters and convert to lowercase
        String cleaned = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        return cleaned.equals(reverse(cleaned));
    }
    
    // Remove duplicate characters
    public static String removeDuplicates(String str) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (result.toString().indexOf(ch) == -1) {
                result.append(ch);
            }
        }
        return result.toString();
    }
    
    // Word count
    public static int wordCount(String str) {
        if (str == null || str.trim().isEmpty()) {
            return 0;
        }
        String[] words = str.trim().split("\\s+");
        return words.length;
    }
    
    public static void main(String[] args) {
        String text = "Programming is fun and programming is challenging";
        
        System.out.println("Original: " + text);
        System.out.println("Reversed: " + reverse(text));
        System.out.println("Count of 'o': " + countChar(text, 'o'));
        System.out.println("Is 'madam' palindrome: " + isPalindrome("madam"));
        System.out.println("Is 'hello' palindrome: " + isPalindrome("hello"));
        System.out.println("Remove duplicates from 'hello': " + removeDuplicates("hello"));
        System.out.println("Word count: " + wordCount(text));
    }
}

StringBuilder and StringBuffer

StringBuilderExample.java
public class StringBuilderExample {
    public static void main(String[] args) {
        // StringBuilder for single-threaded use (faster)
        StringBuilder sb = new StringBuilder();
        
        // Append operations
        sb.append("Hello");
        sb.append(" ");
        sb.append("World");
        sb.append("!");
        
        System.out.println("StringBuilder: " + sb.toString());
        
        // Insert at position
        sb.insert(5, " Beautiful");
        System.out.println("After insert: " + sb.toString());
        
        // Delete range
        sb.delete(5, 15);
        System.out.println("After delete: " + sb.toString());
        
        // Replace range
        sb.replace(6, 11, "Java");
        System.out.println("After replace: " + sb.toString());
        
        // Reverse
        sb.reverse();
        System.out.println("Reversed: " + sb.toString());
        
        // Performance comparison
        stringVsBuilder();
    }
    
    public static void stringVsBuilder() {
        long start, end;
        int iterations = 10000;
        
        // Using String concatenation
        start = System.currentTimeMillis();
        String strResult = "";
        for (int i = 0; i < iterations; i++) {
            strResult += "a";
        }
        end = System.currentTimeMillis();
        System.out.println("String concatenation time: " + (end - start) + "ms");
        
        // Using StringBuilder
        start = System.currentTimeMillis();
        StringBuilder sbResult = new StringBuilder();
        for (int i = 0; i < iterations; i++) {
            sbResult.append("a");
        }
        end = System.currentTimeMillis();
        System.out.println("StringBuilder time: " + (end - start) + "ms");
    }
}

String Formatting

StringFormatting.java
public class StringFormatting {
    public static void main(String[] args) {
        // printf style formatting
        String name = "John";
        int age = 25;
        double salary = 50000.50;
        
        System.out.printf("Name: %s, Age: %d, Salary: %.2f%n", name, age, salary);
        
        // String.format()
        String formatted = String.format("Name: %-10s | Age: %3d | Salary: %,10.2f", 
                                       name, age, salary);
        System.out.println("Formatted: " + formatted);
        
        // Padding with spaces
        String padded = String.format("%10s", "Hello");
        System.out.println("Padded right: '" + padded + "'");
        
        padded = String.format("%-10s", "Hello");
        System.out.println("Padded left: '" + padded + "'");
        
        // Leading zeros
        String number = String.format("%05d", 42);
        System.out.println("Padded with zeros: " + number);
        
        // Percentage
        double percentage = 0.75;
        String percent = String.format("%.1f%%", percentage * 100);
        System.out.println("Percentage: " + percent);
    }
}

String to Number Conversion

StringConversion.java
public class StringConversion {
    public static void main(String[] args) {
        // String to primitive types
        String strInt = "123";
        String strDouble = "45.67";
        String strBoolean = "true";
        
        int intValue = Integer.parseInt(strInt);
        double doubleValue = Double.parseDouble(strDouble);
        boolean boolValue = Boolean.parseBoolean(strBoolean);
        
        System.out.println("Int: " + intValue);
        System.out.println("Double: " + doubleValue);
        System.out.println("Boolean: " + boolValue);
        
        // Handling invalid conversions
        try {
            int invalid = Integer.parseInt("abc");
        } catch (NumberFormatException e) {
            System.out.println("Invalid number format: " + e.getMessage());
        }
        
        // Primitive to String
        int number = 42;
        double pi = 3.14159;
        
        String intString = String.valueOf(number);
        String doubleString = Double.toString(pi);
        String anotherIntString = Integer.toString(number);
        
        System.out.println("String from int: " + intString);
        System.out.println("String from double: " + doubleString);
        System.out.println("Another string from int: " + anotherIntString);
    }
}
ℹ️
Use StringBuilder when you need to modify strings frequently. Use String for immutable text that won’t change.

You’ve now completed the Java basics! These fundamentals will help you build more complex Java applications.

Last updated on