bscodinglab

Strings

In Java, a String is a class that represents a sequence of characters. A String variable contains a collection of characters surrounded by double quotes. It is a fundamental data type in the Java programming language and is part of the java.lang package, so you don’t need to import any additional libraries to work with strings.

   Definition:

  • A string is an object of the String class in Java.
  • It is a sequence of characters.
  • Strings are immutable, meaning their values cannot be changed once they are created.

String Creation :-  Strings in Java can be created in several ways.

Example :-

         Using a string literal :- “Hello, World!”.

         Using the new keyword and the String constructor :- String str = new String(“Hello, World!”);

Using the assignment operator :- String str = “Hello, World!”;. This is the most common way and is equivalent to using a string literal.

Example :-

String greeting = “Hello, World!”;

String fullName = new String(“John Doe”);

String Class :- In Java, strings are represented by the String class. This class provides a wide range of methods for manipulating and working with strings.

Example :-

String fullName = new String(“John Doe”);

Immutable:- Strings in Java are immutable, which means once a string object is created, its value cannot be changed. If you want to modify a string, you create a new string with the desired modifications.

Example :-

String s1 = “Hello”;

s1 = s1 + “, World!”; // This creates a new string and assigns it to s1

String Pool :- Java maintains a special memory area called the “string pool” for string literals. When you create a string using a literal (e.g., “Hello”), Java checks if it already exists in the pool. If it does, it reuses the existing string; otherwise, it creates a new one. This can help save memory and improve performance.

Example :-

String a = “Hello”;

String b = “Hello”; // Reuses the same “Hello” string from the pool

String Methods :- Java provides a wide range of methods for manipulating strings.

Some common methods include :-

length()

charAt()

substring()

toLowerCase()

toUpperCase()

equals()

startsWith()

endsWith()

and many more…..

String Comparison :- When comparing strings for equality, you should use the equals() method or its case-insensitive variant equalsIgnoreCase()  instead of ==. The == operator compares references, while equals() compares the content of the strings.

Example :-

String s1 = “Hello”;

String s2 = “Hello”;

boolean isEqual = s1.equals(s2); // true (content comparison)

boolean isReferenceEqual = s1 == s2; // true (reference comparison, not recommended)

String Formatting :- Java provides the String.format() method to create formatted strings using placeholders.

Example :-

int age = 30;

String message = String.format(“I am %d years old.”, age); // “I am 30 years old.”

Concatenation :- Concatenation with + Operator: You can concatenate string literals and variables using the + operator.

Example :-

String firstName = “John”;

String lastName = “Doe”;

String fullName = firstName + ” ” + lastName;

String Length :- Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

Example :-

int length = greeting.length();  // Returns 13

StringBuilder and StringBuffer :- If you need to perform a lot of string concatenation or modifications in a loop, it’s more efficient to use StringBuilder (or StringBuffer in multi-threaded environments) instead of repeatedly creating new strings. These classes allow you to modify strings without creating new objects for each change.

Example :-

StringBuilder sb = new StringBuilder();

sb.append(“Hello”);

sb.append(” “);

sb.append(“World”);

String result = sb.toString(); // Convert StringBuilder to String

Unicode Support :- Java’s String class is designed to support Unicode characters, making it suitable for internationalization and working with various languages and character sets.

Example :-

String unicode = “\u03A3”; // Represents the Greek letter Sigma

 An Example of string :-

public class StringExample {

    public static void main(String[] args) {

        String str1 = “Hello, “;

        String str2 = “World!”;

 

        // Concatenation

        String result = str1 + str2;

        System.out.println(“Concatenated String: ” + result);

 

        // String length

        int length = result.length();

        System.out.println(“Length of the String: ” + length);

 

        // Character at a specific position

        char charAtIndex = result.charAt(4);

        System.out.println(“Character at index 4: ” + charAtIndex);

 

        // Substring

        String subStr = result.substring(0, 5);

        System.out.println(“Substring from index 0 to 4: ” + subStr);

 

        // Replace

        String replaced = result.replace(“World”, “Java”);

        System.out.println(“String after replacement: ” + replaced);

 

        // Uppercase and lowercase

        String upperCase = result.toUpperCase();

        String lowerCase = result.toLowerCase();

        System.out.println(“Uppercase: ” + upperCase);

        System.out.println(“Lowercase: ” + lowerCase);

    }

}

Output :-   Concatenated String: Hello, World!

Length of the String: 13

Character at index 4: o

Substring from index 0 to 4: Hello

String after replacement: Hello, Java!

Uppercase: HELLO, WORLD!

Lowercase: hello, world!