Strings in JAVA

In Java, a string is a sequence of characters, represented by the String class, which is part of the java.lang package. Strings in Java are immutable, meaning once a string is created, it cannot be modified. Any modification results in the creation of a new string.

Create Strings in Java:

  1. Using String Literals:
				
					String str = "Hello, World!";
				
			

Here, “Hello, World!” is a string literal stored in the string pool.

The String Pool in Java is a special memory area where Java stores string literals. It helps save memory and makes the program run faster.

How it Works:

When you create a string using double quotes (like “Hello”), Java checks the string pool:

    • If the string already exists in the pool, Java reuses it.
    • If the string doesn’t exist, Java adds it to the pool.

Why Use a String Pool?

  • Saves Memory: Reuses strings instead of creating duplicates.
  • Improves Performance: Less memory usage = faster program.

2.Using the new Keyword:

				
					String str = new String("Hello, World!");
				
			

This creates a new string object in the heap memory but outside the string pool.

In Java, the String class is part of the java.lang package, which is automatically imported. This means you don’t need to manually import anything to use String and its methods. You can directly use all methods provided by the String class without any additional imports.

Commonly Used String Methods
Here are some important methods of the String class:

1. Length

  • Method: length()
  • Description: Returns the number of characters in the string.
				
					public class Example {
public static void main(String[] args) {
String str = "Mohit Sarkar";
System.out.println("Length: " + str.length()); // Output: 12
}
}
				
			

2. Character Access

  • Method: charAt(index)
  • Description: Returns the character at the specified index.
				
					public class Example {
    public static void main(String[] args) {
        String str = "anurag";
        System.out.println("Character at index 1: " + str.charAt(1)); // Output: a
    }
}

				
			

3. Substring

  • Methods: substring(beginIndex) and substring(beginIndex, endIndex)
  • Description: Extracts a portion of the string.
				
					public class Example {
    public static void main(String[] args) {
        String str = "Java Programming";
        System.out.println("Substring (6 to end): " + str.substring(6)); // Output: Programming
        System.out.println("Substring (0 to 4): " + str.substring(0, 4)); // Output: Java
    }
}

				
			

4. Split

  • Method: split(regex)
  • Description: Splits the string into parts based on a regex pattern.
				
					public class Example {
    public static void main(String[] args) {
        String str = "Munni,Sheela,Basanti";
        String[] fruits = str.split(",");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        // Output:
        // Munni
        // Sheela
        // Basanti
    }
}

				
			

5. Case Conversion

  • Methods: toUpperCase(), toLowerCase()
  • Description: Converts the string to uppercase or lowercase.
				
					public class Example {
    public static void main(String[] args) {
        String str = "Java";
        System.out.println("Uppercase: " + str.toUpperCase()); // Output: JAVA
        System.out.println("Lowercase: " + str.toLowerCase()); // Output: java
    }
}

				
			

6. Equality

  • Methods: equals(String) and equalsIgnoreCase(String)
  • Description: Compares two strings for equality, with or without case sensitivity.
				
					public class Example {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "hello";
        System.out.println("Equals: " + str1.equals(str2)); // Output: false
        System.out.println("Equals Ignore Case: " + str1.equalsIgnoreCase(str2)); // Output: true
    }
}

				
			

Note (Important hai dekh lo)

    In Java, equals() and == are used for comparison, but they work differently:

              1.  == (Reference Comparison)

    • It compares memory addresses (references) of two objects.
    • It checks if both references point to the same object in memory.
    • Example:
    • String str1 = new String(“Hello”);
      String str2 = new String(“Hello”);
      System.out.println(str1 == str2); // false (different objects)

             2. equals() (Content Comparison)

  • t compares the contents (actual data) of two strings.
  • The String class overrides equals() to check if the characters in both strings are identical.
  • Example:
  • String str1 = new String(“Hello”);
    String str2 = new String(“Hello”);
    System.out.println(str1.equals(str2)); // true (contents are the same)

7. Trim

  • Method: trim()
  • Description: Removes leading and trailing spaces.
				
					public class Example {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";
        System.out.println("Trimmed: " + str.trim()); // Output: Hello, World!
    }
}

				
			

8. Replace

  • Methods: replace(oldChar, newChar) and replaceAll(regex, replacement)
  • Description: Replaces all occurrences of a character or substring.
				
					public class Example {
    public static void main(String[] args) {
        String str = "Java is fun";
        System.out.println("Replace 'fun' with 'awesome': " + str.replace("fun", "awesome"));
        // Output: Java is awesome
    }
}

				
			

9. Search

  • Methods: indexOf(char/substring) and lastIndexOf(char/substring)
  • Description: Finds the position of a character or substring.
				
					public class Example {
    public static void main(String[] args) {
        String str = "Java Programming";
        System.out.println("Index of 'P': " + str.indexOf('P')); // Output: 5
        System.out.println("Last Index of 'a': " + str.lastIndexOf('a')); // Output: 13
    }
}

				
			

10. Convert to Character Array

  • Method: toCharArray()
  • Description: Converts the string to an array of characters.
				
					public class Example {
    public static void main(String[] args) {
        String str = "Hello";
        char[] chars = str.toCharArray();
        for (char c : chars) {
            System.out.println(c);
        }
        // Output:
        // H
        // e
        // l
        // l
        // o
    }
}

				
			

11. Concatenation

  • Method: concat(String)
  • Description: Joins two strings together.
				
					public class Example {
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = "Programming";
        System.out.println("Concatenated: " + str1.concat(" ").concat(str2)); // Output: Java Programming
    }
}

				
			

Thanks for Reading

4 thoughts on “Strings in JAVA”

Leave a Comment

Your email address will not be published. Required fields are marked *