Java Strings
An Introduction to Strings in Java
What is a String?
• • A String in Java is an object that represents a
sequence of characters.
• • Strings are immutable, meaning their values
cannot be changed after creation.
• • Strings are widely used in Java programming
to handle text.
Creating Strings
• • Using String Literals:
• String str = "Hello";
• • Using the 'new' Keyword:
• String str = new String("Hello");
Common String Methods
• • length(): Returns the length of the string.
• Example: str.length();
• • charAt(index): Returns the character at the
specified index.
• Example: str.charAt(0);
• • substring(start, end): Extracts a substring.
• Example: str.substring(0, 5);
String Comparison
• • equals(): Compares the content of two
strings.
• Example: str1.equals(str2);
• • equalsIgnoreCase(): Compares strings
ignoring case.
• Example: str1.equalsIgnoreCase(str2);
• • compareTo(): Compares strings
String Concatenation
• • Using the '+' Operator:
• String result = str1 + str2;
• • Using concat() Method:
• String result = str1.concat(str2);
String Immutability
• • Strings in Java are immutable.
• • Once a string is created, it cannot be
modified.
• • Any operation on a string creates a new
string object.
Summary
• • Strings are an essential part of Java
programming.
• • Strings are immutable objects.
• • Java provides various methods to
manipulate and compare strings.