Back to the 2020 paper

Module III: Basics of Web Programming

20207m

Explain different string handling functions and their syntax in Java language.

Worked SolutionAI Assisted

Answer: String Handling Functions in Java

1. Introduction

In Java, a String is an object of the java.lang.String class that represents a sequence of characters.

  • Immutability: Once created, a String object’s content cannot be modified. Any modification creates a new String object in memory (utilizing the String Constant Pool).
  • For mutable strings, Java provides StringBuffer (thread-safe, synchronized) and StringBuilder (faster, non-synchronized).

2. Core String Handling Methods

Method & Syntax Description Example
int length() Returns the number of characters in the string. "Hello".length() \to 5
char charAt(int index) Returns the character at the specified 0-based index. "Java".charAt(1) \to 'a'
String substring(int begin, int end) Returns substring from begin (inclusive) to end (exclusive). "Technology".substring(0, 4) \to "Tech"
boolean equals(Object obj) Compares character contents for exact equality (case-sensitive). "Cat".equals("cat") \to false
boolean equalsIgnoreCase(String s) Compares strings ignoring uppercase/lowercase differences. "Cat".equalsIgnoreCase("cat") \to true
int compareTo(String s) Compares strings lexicographically (00 if equal, negative if smaller, positive if greater). "A".compareTo("B") \to -1
String concat(String str) Appends the specified string to the end. "Web".concat("Tech") \to "WebTech"
int indexOf(String str) Returns index of first occurrence of the substring (or -1). "banana".indexOf("na") \to 2
int lastIndexOf(String str) Returns index of last occurrence of the substring. "banana".lastIndexOf("na") \to 4
String toUpperCase() Converts all characters to uppercase. "java".toUpperCase() \to "JAVA"
String toLowerCase() Converts all characters to lowercase. "HTML".toLowerCase() \to "html"
String trim() Eliminates leading and trailing whitespace. " test ".trim() \to "test"
String replace(char old, char new) Replaces all occurrences of old with new. "Java".replace('a', 'o') \to "Jovo"
boolean contains(CharSequence s) Checks if string contains the specified sequence. "PYQDeck".contains("Deck") \to true
boolean startsWith(String prefix) Checks if string begins with specified prefix. "http://".startsWith("http") \to true
String[] split(String regex) Splits the string into an array around matches of regex. "a,b,c".split(",") \to ["a", "b", "c"]
char[] toCharArray() Converts string into a new character array. "Hi".toCharArray() \to ['H', 'i']

3. Java Code Demonstration

public class StringHandlingDemo {
    public static void main(String[] args) {
        String s1 = " Bihar Engineering University ";
        
        System.out.println("Original String: '" + s1 + "'");
        System.out.println("Length: " + s1.length());
        System.out.println("Trimmed: '" + s1.trim() + "'");
        System.out.println("Uppercase: " + s1.toUpperCase());
        System.out.println("Character at index 7: " + s1.charAt(7));
        System.out.println("Substring (1-6): " + s1.substring(1, 6));
        System.out.println("Replaced: " + s1.replace("Bihar", "State"));
        System.out.println("Contains 'Engineering': " + s1.contains("Engineering"));

        // Splitting string
        String languages = "HTML,CSS,JavaScript,Java,PHP";
        String[] langArray = languages.split(",");
        System.out.println("
Split Elements:");
        for (String lang : langArray) {
            System.out.println(" - " + lang);
        }
    }
}

4. String vs StringBuffer vs StringBuilder

Parameter String StringBuffer StringBuilder
Storage String Constant Pool / Heap Heap Heap
Mutability Immutable Mutable Mutable
Thread Safety Thread-safe (due to immutability) Thread-safe (Synchronized) Not Thread-safe
Performance Slow on frequent concatenation Medium Fastest
Introduced Java 1.0 Java 1.0 Java 1.5

Similar questions