Java string
Created By: chatGPT
In Java, a
String
is a special class that represents a sequence of characters. Strings are immutable, meaning once a String
object is created, it cannot be changed. Instead, any modification will create a new String
object. Here are some common operations you can perform with strings:To create a string, you can use either single quotes or the
String
constructor. However, it's more common to use double quotes.String example1 = "Hello, World!";
String example2 = new String("Hello, Java!");
You can find the length of a string using the
length()
method. This returns the number of characters in the string, including spaces.int length = example1.length(); // length = 13
To access a character at a specific index, you can use the
charAt(int index)
method. Remember that string indexing starts at 0.char firstChar = example1.charAt(0); // firstChar = 'H'
Strings can be concatenated using the
+
operator.String concatenated = example1 + " " + example2; // concatenated = "Hello, World! Hello, Java!"
To convert a string to uppercase or lowercase, you can use the
toUpperCase()
and toLowerCase()
methods, respectively.String upperCase = example1.toUpperCase(); // upperCase = "HELLO, WORLD!"
String lowerCase = example2.toLowerCase(); // lowerCase = "hello, java!"
To check if a string contains a substring, the
contains()
method is quite handy.boolean containsWorld = example1.contains("World"); // containsWorld = true
Lastly, to compare two strings, you can use the
equals()
method, which checks for content equality, or compareTo()
method for lexicographical comparison.boolean isEqual = example1.equals(example2); // isEqual = false
int comparison = example1.compareTo(example2); // comparison may be negative, zero, or positive