String Objects: Concatenation, Literals, and More
String Objects: Concatenation, Literals, and More
Understanding String Objects
- A String object represents a sequence of characters and is an example of an object in object-oriented programming.
- In Java, unlike other simple data types, Strings are objects created from the
Stringclass. - Strings can be created either by using the new keyword:
String str = new String("Hello");or by directly assigning a String literal to the String instance:String str = "Hello";.
String Literals
- String literals are any text enclosed in double quotes, such as “Hello, World!”.
- String literals are treated as instances of the
Stringclass in Java. - All string literals are automatically instances of the
Stringclass, there’s no need to explicitly create a new instance. - String literals in Java are immutable, meaning that once they’re created, they cannot be changed.
String Concatenation
- String concatenation is the operation of joining two strings end-to-end.
- In Java, string concatenation can be done using the
+operator: e.g.String str = "Hello" + " World";. - If any of the operands of the
+operator is a String, the operator acts as a concatenation operator and not an addition operator. For example:"Hello " + 123produces the string"Hello 123". - The
concatmethod in theStringclass can also be used to concatenate strings: e.g.String str = "Hello".concat(" World");.
Manipulating Strings
- The
Stringclass in Java provides a lot of methods to work with strings, such as to obtain their length (length()), convert to upper or lower case (toUpperCase(),toLowerCase()), or replace characters (replace()). - Methods like
substring(),charAt(), andsplit()etc., can be used to retrieve or manipulate parts of the String object.
Using == Operator and equals() Method
- To compare the content of two String objects, the
equals()orequalsIgnoreCase()methods should be used, not the==operator. - The
==operator compares the references, not the content. So,==will only return true if two references are pointing to the same objects. - The
equals()method compares whether the content is identical, even when the instances are different. For example:str1.equals(str2)will return true if str1 and str2 have the same characters in the same order.
Importance of String class
- The class
Stringis one of the most used classes in Java. - It provides a comprehensive set of operations that can be performed on Strings.
- Mastering the use of String objects and their methods is fundamental to effective programming in Java.