Java Docs
Java Documentation
Java Strings
In Java, a string is a sequence of characters, represented using double quotes. Strings are objects of the predefined String class.
Creating Strings
// Using string literals
String first = "Java";
String second = "Python";
// Using the new keyword
String third = new String("Java String");String Operations
1. Get Length
String greet = "Hello! World";
int length = greet.length();
System.out.println("Length: " + length); // Output: 122. Concatenate Strings
String first = "Java "; String second = "Programming"; String joined = first.concat(second); System.out.println(joined); // Output: Java Programming // Or using + String joined2 = first + second;
3. Compare Strings
String first = "java programming"; String second = "java programming"; String third = "python programming"; System.out.println(first.equals(second)); // true System.out.println(first.equals(third)); // false
4. Escape Characters
String example = "This is the "String" class."; System.out.println(example); // Output: This is the "String" class.
5. Strings are Immutable
String example = "Hello! ";
example = example.concat("World");
System.out.println(example); // Output: Hello! World
// Original string "Hello! " remains unchanged6. String Literals vs New Keyword
// Literal
String s1 = "Java"; // stored in string pool
String s2 = "Java"; // same reference as s1
// New keyword
String s3 = new String("Java"); // new object created
String s4 = new String("Java"); // different object than s3Common String Methods
| Method | Description |
|---|---|
| contains() | Checks whether the string contains a substring. |
| substring() | Returns a substring from the string. |
| replace() | Replaces characters or substrings in the string. |
| charAt() | Returns the character at a specific index. |
| toUpperCase() | Converts string to uppercase. |
| toLowerCase() | Converts string to lowercase. |
| split() | Breaks the string into an array of substrings. |
| trim() | Removes leading and trailing whitespaces. |