Java provides robust mechanisms for handling strings and characters through the String
and Character
classes. This allows developers to perform various operations, including comparisons, manipulations, and conversions.
String Immutability and Creation
In Java, strings are represented by the String
class. A key characteristic of String
objects is their immutability – once created, their values cannot be changed. This immutability allows for efficient string sharing. String literals, like "abc"
, are implemented as instances of the String
class.
You can create a String
object in several ways. For instance:
String str1 = "abc";
char data[] = {'a', 'b', 'c'};
String str2 = new String(data);
Both examples create a String
object representing “abc”.
String Manipulation Methods
The String
class offers a wide range of methods for manipulating strings:
-
substring()
: Extracts a portion of the string. For example,"abc".substring(2, 3)
returns “c”. -
concat()
: Joins two strings together. For instance,"abc".concat("def")
returns “abcdef”. The+
operator also performs string concatenation. Behind the scenes, Java utilizesStringBuilder
(orStringBuffer
) and itsappend()
method for efficient concatenation. -
length()
: Returns the number of characters in the string. -
toUpperCase()
andtoLowerCase()
: Convert the string to uppercase or lowercase, respectively, based on Unicode Standard rules specified by theCharacter
class.
String Comparison
Java allows comparing strings using methods like:
-
equals()
: Checks if two strings have the same sequence of characters. -
equalsIgnoreCase()
: Compares strings ignoring case. -
compareTo()
: Compares strings lexicographically.
Character Class
The Character
class provides methods for working with individual characters:
-
isDigit()
: Checks if a character is a digit. -
isLetter()
: Checks if a character is a letter. -
isWhitespace()
: Checks if a character is whitespace. -
toUpperCase()
andtoLowerCase()
: Convert a character to uppercase or lowercase.
Unicode Support
Java strings are based on the UTF-16 format, which supports supplementary characters through surrogate pairs. The String
class provides methods to handle both Unicode code units (char
values) and Unicode code points (characters). The Character
class provides detailed information about Unicode character representations.
NullPointerException
It’s crucial to remember that passing a null
argument to a String
constructor or method will result in a NullPointerException
. Always check for null
values before performing string operations.