Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Characters

  • a character is a single 16-bit Unicode character, represented by the char primitive data type.
  • It can store any character from the Unicode character set (e.g., letters, digits, symbols).
    char ch = 'A'; // Stores the character 'A'
    char unicodeChar = '\u0041'; // Unicode for 'A'
    

Strings

  • A string is a sequence of characters.
  • In Java, strings are objects of the String class (from the java.lang package), not primitive types.
  • Strings are immutable, meaning their content cannot be changed after creation.
    String str = "Hello, World!";
    

string class

key features

  • immutability: ensures thread safety and security (e.g., in class loading or as keys in hash-based collections).

  • string pool: java maintains a pool of string literals to optimize memory. Strings created using literals (e.g., "Hello") are stored in the pool, while those created with new String("Hello") are not (unless interned).

    String str1 = new String(); // Empty string
    String str2 = new String("Hello"); // String from literal
    char[] chars = {'H', 'i'};
    String str3 = new String(chars); // String from char array
    
  • string methods

    • length(): Returns the number of characters.
    • charAt(int index): Returns the character at the specified index.
    • substring(int beginIndex, int endIndex): Returns a substring.
    • toUpperCase() / toLowerCase(): Converts case.
    • indexOf(String str): Returns the index of the first occurrence of str.
    • equals(Object obj) / equalsIgnoreCase(String str): Compares strings.
    • trim(): Removes leading/trailing whitespace.
    • replace(char oldChar, char newChar): Replaces characters.

valueO()

The String class provides valueOf() methods to convert various data types to strings. These are static methods.

int num = 42;
String strNum = String.valueOf(num); // "42"

double d = 3.14;
String strDouble = String.valueOf(d); // "3.14"

boolean b = true;
String strBool = String.valueOf(b); // "true"

char[] chars = {'H', 'i'};
String strChars = String.valueOf(chars); // "Hi"

StringBuffer Class

  • The StringBuffer class is used for mutable strings, unlike the immutable String class. It is thread-safe (synchronized methods), making it suitable for multi-threaded applications.
  • Key Features of StringBuffer hello
    • Mutable: Allows in-place modification of the character sequence.
    • Thread-safe: Synchronized methods ensure safe use in multi-threaded environments.
    • Capacity: Internal buffer size, which grows dynamically (default initial capacity is 16).
StringBuffer sb1 = new StringBuffer(); // Empty, capacity 16
StringBuffer sb2 = new StringBuffer("Hello"); // Initialized with "Hello"
StringBuffer sb3 = new StringBuffer(50); // Empty, capacity 50
  • StringBuffer Methods
    • append(String str): Appends data (overloaded for various types: int, double, etc.).
    • insert(int offset, String str): Inserts data at the specified position.
    • delete(int start, int end): Removes characters from start to end-1.
    • replace(int start, int end, String str): Replaces characters from start to end-1 with str.
    • reverse(): Reverses the character sequence.
    • capacity(): Returns the current capacity.
    • ensureCapacity(int minCapacity): Ensures the buffer has at least the specified capacity.
    • toString(): Converts the StringBuffer to a String.

When to Use StringBuffer

  • Use StringBuffer for string manipulation in multi-threaded environments.
  • For single-threaded applications, prefer StringBuilder for better performance (no synchronization overhead).
  • Example:
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 1000; i++) {
        sb.append(i); // Efficient for repeated modifications
    }
    

String vs. StringBuffer

FeatureStringStringBuffer
MutabilityImmutableMutable
Thread-SafetyThread-safe (immutable)Thread-safe (synchronized)
PerformanceSlower for modificationsFaster for modifications
Memory UsageCreates new objectsModifies in-place
Use CaseFixed stringsDynamic string manipulation