Your Page Title
🔍

    Strings and Enums

    In the previous chapter, you learned how to define arrays of various sizes and dimensions, initialize them, and pass them to functions. With this knowledge, you’re now ready to tackle strings—a special kind of array. This chapter will focus on strings and their manipulation.

    What are Strings?

    Just as a group of integers can be stored in an integer array, a group of characters can be stored in a character array. Character arrays are used to manipulate text, such as words and sentences. The operations performed on character arrays differ from those on numeric arrays. For example, you can convert characters in an array to upper or lower case, but no such operations exist for numeric arrays.

    Java provides a special class called String to handle character arrays. Interestingly, even though String is a reference type, it can be created without the new operator. Here’s how to define strings:

    String s1 = "Lionel";
    String s2 = "Messi";

    In the above code, s1 and s2 are references to two String objects. You can display these strings using:

    System.out.println(s1);
    System.out.println(s2);

    String Concatenation

    The String class has an overloaded + operator that allows you to append one string to another:

    s1 = s1 + s2;
    System.out.println(s1); // Output: LionelMessi

    This may seem as if s2 was appended to s1, but strings in Java are immutable. This means that a new string object is created, and s1 is made to reference this new object instead of the original.

    String Comparison

    Consider the following code snippet:

    String s1 = "Hoopster";
    String s2 = "Hoopster";
    if (s1 == s2)
    System.out.println("Equal");
    else
    System.out.println("Unequal");

    In this case, s1 and s2 reference the same string object, so the condition is true.

    However, if we use:

    tring s3 = new String("Hoopster");
    String s4 = new String("Shuttler");
    if (s3 == s4)
    System.out.println("Equal");
    else
    System.out.println("Unequal");

    Here, s3 and s4 are different objects, so the condition is false. To check if their contents are the same, use:

    if (s3.equals(s4))
    System.out.println("Equal");
    else
    System.out.println("Unequal");

    Common String Methods

    We can perform various operations on strings using methods defined in the String class. Here’s a program demonstrating some common string methods:

    // Different string operations
    package usingstringsproject;

    public class Main {
    public static void main(String[] args) {
    String s1 = "kicit";
    String s2 = "Nagpur";
    System.out.println("Char at 3rd pos: " + s1.charAt(2)); // Output: c
    String s3 = s1.concat(s2);
    System.out.println(s3); // Output: kicitNagpur
    System.out.println("Length of s3: " + s3.length()); // Output: 11
    s3 = s3.replace("p", "P");
    System.out.println(s3); // Output: kicitNagPur
    s3 = String.copyValueOf(s2.toCharArray());
    System.out.println(s3); // Output: Nagpur

    int c = s2.compareTo(s3);
    if (c < 0)
    System.out.println("s2 is less than s3");
    else if (c == 0)
    System.out.println("s2 is equal to s3");
    else
    System.out.println("s2 is greater than s3");

    if (s1 == s3)
    System.out.println("s1 is equal to s3");
    else
    System.out.println("s1 is not equal to s3");

    s3 = s1.toUpperCase();
    System.out.println(s3); // Output: KICIT
    s3 = s2.concat("Mumbai");
    System.out.println(s3); // Output: NagpurMumbai
    s3 = s2.replace(s2.charAt(0), ' ');
    System.out.println(s3); // Output: agpur

    int fin = s1.indexOf("i");
    System.out.println("First index of i in s1: " + fin); // Output: 1
    int lin = s1.lastIndexOf("i");
    System.out.println("Last index of i in s1: " + lin); // Output: 3

    String s = s1.substring(fin, lin + 1);
    System.out.println("Substring: " + s); // Output: ici

    int i = 10;
    float f = 9.8f;
    s3 = String.format("Value of i = %d Value of f = %f", i, f);
    System.out.println(s3); // Output: Value of i = 10 Value of f = 9.800000
    }
    }

    Output of the Program

    Char at 3rd pos: c
    kicitNagpur
    Length of s3: 11
    kicitNagPur
    Nagpur
    s2 is equal to s3
    s1 is not equal to s3
    KICIT
    NagpurMumbai
    agpur
    First index of i in s1: 1
    Last index of i in s1: 3
    Substring: ici
    Value of i = 10 Value of f = 9.800000

    Explanation of String Operations

    • Character Access: Use charAt(index) to get individual characters.
    • Concatenation: The concat() method combines two strings into a new string.
    • Length: Use length() to find the number of characters in a string.
    • Replacement: replace(oldChar, newChar) replaces all occurrences of a character.
    • Copying: copyValueOf(charArray) creates a new string from a character array.
    • Comparison: compareTo(otherString) compares two strings lexicographically.
    • Substring: substring(startIndex, endIndex) returns a portion of the string.
    • Formatting: String.format(format, args) creates a formatted string.

    Splitting Strings

    To split a string into parts based on a separator, you can use the split() method:

    // Split string operations
    package splitandjoinproject;
    import java.io.*;

    public class SplitAndJoinProject {
    public static void main(String[] args) throws Exception {
    File f = new File(".");
    String d = f.getCanonicalPath();
    String[] parts = d.split("\\\\");
    System.out.println("Complete path: " + d);
    System.out.println("Dir name: " + parts[parts.length - 1]);
    }
    }

    Output of the Split Example

    Complete path: D:\Books\J_LUJ\Programs\SplitAndJoinProject
    Dir name: SplitAndJoinProject

    StringBuilder Class

    When manipulating strings, Java creates a new object each time you modify a string. If you want to manipulate a string in place, use the StringBuilder class. It allows you to append, remove, replace, or insert characters using methods like append(), delete(), replace(), and insert().

    Array of Strings

    To handle multiple strings, you can create an array of strings. Here’s an example that checks a user-entered name against a predefined list:

    // Using array of strings
    package arrayofstringsproject;
    import java.util.*;

    public class ArrayOfStringsProject {
    public static void main(String[] args) {
    String[] masterList = new String[]{
    "Akshay", "Parag",
    "Raman", "Srinivas",
    "Gopal", "Rajesh"
    };
    boolean flag = false;
    Scanner scn = new Scanner(System.in);
    System.out.println("Enter your name:");
    String yourName = scn.nextLine();

    for (String name : masterList) {
    if (name.equals(yourName)) {
    System.out.println("You can enter the palace");
    flag = true;
    break;
    }
    }

    if (!flag) {
    System.out.println("Sorry, you are a trespasser");
    }
    }
    }

    Output of the Array Example

    Enter your name: Dinesh
    Sorry, you are a trespasser
    Enter your name: Raman
    You can enter the palace

    Sorting Strings

    To sort an array of strings alphabetically, you can implement a sorting algorithm. Below is an example using the Bubble Sort method:

    // Sorting array of Strings
    package sortingstringsproject;

    public class SortingStringsProject {
    public static void main(String[] args) {
    String[] names = new String[]{
    "Akshay", "Parag",
    "Raman", "Srinivas",
    "Gopal", "Rajesh"
    };

    for (int i = 0; i < names.length - 1; i++) {
    for (int j = i + 1; j < names.length; j++) {
    if (names[i].compareTo(names[j]) > 0) {
    // Swap
    String temp = names[i];
    names[i] = names[j];
    names[j] = temp;
    }
    }
    }

    System.out.println("Sorted names:");
    for (String name : names) {
    System.out.println(name);
    }
    }
    }

    Output of the Sorting Example

    Sorted names:
    Akshay
    Gopal
    Parag
    Rajesh
    Raman
    Srinivas

    Enums

    An enum (short for enumeration) is a special type used to define collections of constants. Here’s a simple example of an enum representing the days of the week:

    // Enum example
    package enumsproject;

    public class EnumsProject {
    public enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

    public static void main(String[] args) {
    Days today = Days.MONDAY;

    switch (today) {
    case SUNDAY:
    System.out.println("It's Sunday!");
    break;
    case MONDAY:
    System.out.println("It's Monday!");
    break;
    default:
    System.out.println("It's another day!");
    }
    }
    }

    Output of the Enum Example

    It's Monday!