You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The String class in Java represents a sequence of characters. It is one of the most commonly used classes and is immutable, meaning once created, its value cannot be changed.
Characteristics of String Class
Feature
Details
Package
java.lang
Immutable
Strings are immutable.
Default Value
null for uninitialized string references.
Key Features of the String Class
Immutability: Once created, the content of a String object cannot be changed.
Efficient Memory Management: Strings are stored in a special memory area called the "string pool."
Supports Multiple Constructors: Allows creating strings from character arrays, byte arrays, or directly using string literals.
Utility Methods: Provides numerous methods for manipulating and examining strings.
Operations on String Types
String Operations
Operation
Symbol
Example
Concatenation
+
str1 + str2
Static Methods
Method
Description
Return Type
Example
valueOf(Object obj)
Returns the string representation of the specified object.
String
String.valueOf(42); // "42"
format(String format, Object... args)
Returns a formatted string using the specified format and arguments.
publicclassStringExample {
publicstaticvoidmain(String[] args) {
// Create a stringStringstr = "Hello, World!";
// Get the length of the stringSystem.out.println("Length: " + str.length());
// Get a character at a specific indexSystem.out.println("Character at index 0: " + str.charAt(0));
// Get a substringSystem.out.println("Substring: " + str.substring(0, 5));
// Check equalitySystem.out.println("Equals 'Hello, World!': " + str.equals("Hello, World!"));
// Convert to lowercaseSystem.out.println("Lowercase: " + str.toLowerCase());
// Replace a characterSystem.out.println("Replace 'H' with 'h': " + str.replace('H', 'h'));
// Split the stringString[] words = str.split(", ");
System.out.println("First word: " + words[0]);
// Trim whitespaceStringpadded = " Hello ";
System.out.println("Trimmed: '" + padded.trim() + "'");
}
}