What are Strings?

In Java, a String is a sequence of characters. Strings are objects of the String class and are one of the most commonly used data types. Unlike primitive types, Strings are immutable, meaning once created, their values cannot be changed.

📝

Key Characteristics

  • Immutable: Cannot be changed after creation
  • Objects: Strings are objects, not primitives
  • Zero-indexed: First character is at index 0
  • Case-sensitive: "Hello" ≠ "hello"

Why Use Strings?

  • Store and manipulate text data
  • Process user input and output
  • Read and write files
  • Build dynamic messages and reports

Creating Strings

There are multiple ways to create strings in Java. Here are the most common methods.

String Creation Methods

Method 1: Using String Literals (Most Common)

String name = "Alice";
String greeting = "Hello World";
String empty = "";  // Empty string

Method 2: Using the new Keyword

String message = new String("Hello");
String text = new String("Java Programming");

Method 3: From Character Array

char[] chars = {'J', 'a', 'v', 'a'};
String word = new String(chars);
System.out.println(word);  // Output: Java

💡 Best Practice

Use string literals (Method 1) whenever possible. It's more efficient because Java reuses string literals from a special memory area called the "string pool."

Essential String Methods

Java provides many built-in methods to work with strings. Here are the most important ones for ISC Class 11.

1. length() - Get String Length

String text = "Hello World";
int len = text.length();
System.out.println(len);  // Output: 11

2. charAt() - Get Character at Index

String text = "Java";
char ch = text.charAt(0);
System.out.println(ch);  // Output: J

// Get last character
char last = text.charAt(text.length() - 1);
System.out.println(last);  // Output: a

3. equals() - Compare Strings (Case-Sensitive)

String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";

System.out.println(str1.equals(str2));  // Output: true
System.out.println(str1.equals(str3));  // Output: false

// IMPORTANT: Never use == to compare strings!
// == compares memory addresses, not content

⚠️ Warning: Always use .equals() to compare strings, never ==!

4. equalsIgnoreCase() - Compare Ignoring Case

String str1 = "Hello";
String str2 = "hello";
String str3 = "HELLO";

System.out.println(str1.equalsIgnoreCase(str2));  // Output: true
System.out.println(str1.equalsIgnoreCase(str3));  // Output: true

5. compareTo() - Lexicographic Comparison

String str1 = "Apple";
String str2 = "Banana";
String str3 = "Apple";

System.out.println(str1.compareTo(str2));  // Output: negative (Apple < Banana)
System.out.println(str2.compareTo(str1));  // Output: positive (Banana > Apple)
System.out.println(str1.compareTo(str3));  // Output: 0 (equal)

// Returns:
// 0 if strings are equal
// Negative if first string comes before second
// Positive if first string comes after second

6. toUpperCase() and toLowerCase() - Change Case

String text = "Hello World";

String upper = text.toUpperCase();
System.out.println(upper);  // Output: HELLO WORLD

String lower = text.toLowerCase();
System.out.println(lower);  // Output: hello world

// Original string remains unchanged (immutable)
System.out.println(text);  // Output: Hello World

7. substring() - Extract Part of String

String text = "Hello World";

// From index to end
String sub1 = text.substring(6);
System.out.println(sub1);  // Output: World

// From start index to end index (exclusive)
String sub2 = text.substring(0, 5);
System.out.println(sub2);  // Output: Hello

8. indexOf() - Find Position of Character/Substring

String text = "Hello World";

int pos1 = text.indexOf('o');
System.out.println(pos1);  // Output: 4 (first occurrence)

int pos2 = text.indexOf("World");
System.out.println(pos2);  // Output: 6

int pos3 = text.indexOf('z');
System.out.println(pos3);  // Output: -1 (not found)

9. replace() - Replace Characters/Substrings

String text = "Hello World";

String replaced1 = text.replace('o', 'a');
System.out.println(replaced1);  // Output: Hella Warld

String replaced2 = text.replace("World", "Java");
System.out.println(replaced2);  // Output: Hello Java

10. trim() - Remove Leading/Trailing Spaces

String text = "   Hello World   ";
String trimmed = text.trim();
System.out.println(trimmed);  // Output: Hello World
System.out.println(trimmed.length());  // Output: 11

11. split() - Split String into Array

String text = "Apple,Banana,Orange";

// Split by comma
String[] fruits = text.split(",");
for (String fruit : fruits) {
    System.out.println(fruit);
}
// Output:
// Apple
// Banana
// Orange

// Split by space
String sentence = "Java is fun";
String[] words = sentence.split(" ");
System.out.println(words[0]);  // Output: Java
System.out.println(words[1]);  // Output: is
System.out.println(words[2]);  // Output: fun

12. startsWith() and endsWith() - Check Prefix/Suffix

String filename = "document.pdf";

boolean isPdf = filename.endsWith(".pdf");
System.out.println(isPdf);  // Output: true

String url = "https://example.com";
boolean isSecure = url.startsWith("https");
System.out.println(isSecure);  // Output: true

13. concat() - Concatenate Strings

String first = "Hello";
String second = " World";

// Method 1: Using concat()
String result1 = first.concat(second);
System.out.println(result1);  // Output: Hello World

// Method 2: Using + operator (more common)
String result2 = first + second;
System.out.println(result2);  // Output: Hello World

14. contains() - Check if Substring Exists

String text = "Java Programming";

boolean hasJava = text.contains("Java");
System.out.println(hasJava);  // Output: true

boolean hasPython = text.contains("Python");
System.out.println(hasPython);  // Output: false

Practical String Examples

Let's apply what we've learned with some practical programming examples commonly asked in ISC exams.

Example 1: Count Vowels in a String

public class CountVowels {
    public static void main(String[] args) {
        String text = "Hello World";
        int count = 0;
        
        text = text.toLowerCase();
        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                count++;
            }
        }
        
        System.out.println("Number of vowels: " + count);  // Output: 3
    }
}

Example 2: Reverse a String

public class ReverseString {
    public static void main(String[] args) {
        String text = "Java";
        String reversed = "";
        
        for (int i = text.length() - 1; i >= 0; i--) {
            reversed += text.charAt(i);
        }
        
        System.out.println(reversed);  // Output: avaJ
    }
}

Example 3: Check if String is Palindrome

public class Palindrome {
    public static void main(String[] args) {
        String text = "madam";
        String reversed = "";
        
        for (int i = text.length() - 1; i >= 0; i--) {
            reversed += text.charAt(i);
        }
        
        if (text.equals(reversed)) {
            System.out.println(text + " is a palindrome");
        } else {
            System.out.println(text + " is not a palindrome");
        }
    }
}

Example 4: Count Words in a Sentence

public class CountWords {
    public static void main(String[] args) {
        String sentence = "Java is a programming language";
        
        String[] words = sentence.split(" ");
        System.out.println("Number of words: " + words.length);  // Output: 5
    }
}

Example 5: Replace Spaces with Underscores

public class ReplaceSpaces {
    public static void main(String[] args) {
        String text = "Hello World Java";
        String result = text.replace(' ', '_');
        System.out.println(result);  // Output: Hello_World_Java
    }
}

Example 6: Extract Initials from Name

public class ExtractInitials {
    public static void main(String[] args) {
        String name = "John Doe Smith";
        String[] parts = name.split(" ");
        String initials = "";
        
        for (String part : parts) {
            initials += part.charAt(0);
        }
        
        System.out.println(initials);  // Output: JDS
    }
}

Key Points to Remember

  • Strings are immutable - methods like toUpperCase() return a new String.
  • Always use .equals() to compare strings, never ==.
  • String indices start at 0, just like arrays.
  • Strings are case-sensitive unless you use equalsIgnoreCase().
  • Use split() to convert a string into an array of substrings.
  • substring(start, end) - end index is exclusive.
  • indexOf() returns -1 if the character/substring is not found.
  • Use trim() to remove leading and trailing whitespace.