Strings
What is a String?
• A String is a sequence of characters used to represent text. Internally, Java
strings are objects of the String class in the [Link] package.
String greeting = "Hello, world!";
Strings Are Not Primitives — They're Objects!
• Unlike primitives (int, double, boolean, etc.), a String is a reference
type. That means:
• Belongs to the [Link] package.
• Accesses methods and properties like any object.
String str = "hello";
[Link]([Link]()); // 5
[Link]([Link]()); // "HELLO"
Declaring Strings
1. Using String Literals
String lang = "Java";
• Stored in the String pool (a part of heap memory).
• If another string with the same content exists, it reuses it.
• More memory-efficient.
2. Using the new Operator
String lang = new String("Java");
• Always creates a new object in the heap, even if the same
content exists in the pool.
• Used less often for this reason.
public static void main(String[] args)
{
String str1 = "Java";
String str2 = "Java";
String str3 = new String("Java");
[Link](str1 == str2); // true (same reference from pool)
[Link](str1 == str3); // false (different objects)
}
Strings Immutability
• In Java, Strings are immutable:
• Once created, their content cannot be changed.
• Any operation that seems to "modify" a string (like toUpperCase(),
concat(), etc.) returns a new String object.
• Example:
str1
String str1 = "Happy"; Memory
Happy
String str2 = str1;
str2
• Both str1 and str2 point to the same String object in the String
pool: "Happy"
str1 = str1 + " Birthday";
• What really happens under the hood:
1. Java takes the current value of str1 → "Happy"
2. Appends " Birthday" to it → yields "Happy Birthday"
3. Creates a new String object with the value "Happy Birthday"
4. Assigns the new object to str1
5. str2 still points to the original "Happy"
str2
Memory
Happy
Happy Birthday
str1
Category Method Description Example
Returns the number
length() "Java".length() → 4
of characters
Returns the char at
charAt(int index) "Java".charAt(2) → 'v'
given index
Inspection Checks if string is
isEmpty() "Java".isEmpty() → false
empty
Checks if string
contains(CharSequence s) contains the given "Java".contains("av") → true
sequence
Converts to
toUpperCase() "java".toUpperCase() → "JAVA"
uppercase
Converts to
toLowerCase() "JAVA".toLowerCase() → "java"
lowercase
Modification Removes
trim() leading/trailing " hi ".trim() → "hi"
whitespace
Replaces characters or
replace(a, b) "cat".replace("c", "b") → "bat"
substrings
substring(begin, [end]) Extracts substring "hello".substring(1,4) → "ell"
Category Method Description Example
Compares strings
equals(Object o) "abc".equals("ABC") → false
(case-sensitive)
Compares strings
Comparison equalsIgnoreCase(String s) "abc".equalsIgnoreCase("ABC") → true
(case-insensitive)
Lexicographically
compareTo(String s) "a".compareTo("b") → -1
compares
First occurrence of
indexOf(String s) "banana".indexOf("a") → 1
substring
Last occurrence of
lastIndexOf(String s) "banana".lastIndexOf("a") → 5
substring
Search
Checks if string
startsWith(String prefix) "java".startsWith("ja") → true
starts with prefix
Checks if string ends
endsWith(String suffix) "java".endsWith("va") → true
with suffix
concat(String s) Joins two strings "Hi ".concat("there") → "Hi there"
Concatenation
+ operator Joins strings "Hi " + "there" → "Hi there"
Splits into array
Splitting split(String regex) "a,b,c".split(",") → ["a", "b", "c"]
using regex
Converts to
toCharArray() "abc".toCharArray() → ['a', 'b', 'c']
character array
Conversion
Converts any type
[Link](anyType) [Link](123) → "123"
to String
Joins multiple
strings with a given
Joining [Link](anyType) [Link](":", "A", "B") → "A:B"
delimiter between
them.
• Validating an Email Format
String email = "user@[Link]";
if ([Link]("@") && [Link](".com"))
{
[Link]("Valid email format");
}
else
{
[Link]("Invalid email format");
}
• Masking Part of a Password
String password = "SuperSecret123";
String masked = [Link](0, 2) + "********";
[Link](masked); // Su********
• Extracting a File Extension
String fileName = "[Link]";
String extension = [Link]([Link](".") + 1);
[Link](extension); // pdf
• Cleaning Up User Input
String rawInput = " loginUser ";
String cleanedInput = [Link]().toLowerCase();
[Link](cleanedInput); // "loginuser"
• Generating a Welcome Message
String name = "Alex";
String message = "Welcome, " + name + "!";
[Link](message); // Welcome, Alex!
• Splitting CSV Data
String csvLine = "John,Doe,30,Engineer";
String[] parts = [Link](",");
[Link]("Name: " + parts[0] + " " + parts[1]);
[Link]("Age: " + parts[2]);
[Link]("Profession: " + parts[3]);
• Censoring Word
String comment = "This is a dumb idea!";
String badWord = "dumb";
// Censoring logic: replace each character with '*'
String stars = "";
for (int i = 0; i < [Link](); i++)
{
stars += "*";
}
String cleanComment = [Link](badWord, stars);
[Link](cleanComment); // Output: This is a **** idea!