Strings In Java
In Java, a string is a sequence of characters that represents text. The String
class in Java is used to create and manipulate strings. Strings are commonly used for various purposes such as storing user input, displaying messages, working with file paths, and more. Here's a basic overview of working with strings in Java:
Creating Strings: You can create strings using the following methods:
javaCopy codeString str1 = "Hello, world!"; // Using string literals String str2 = new String("Java"); // Using the String constructor
String Concatenation: You can concatenate strings using the
+
operator or theconcat()
method:javaCopy codeString firstName = "John"; String lastName = "Doe"; String fullName = firstName + " " + lastName; // Using the + operator String greeting = firstName.concat(" ").concat(lastName); // Using the concat() method
String Length: You can find the length of a string using the
length()
method:javaCopy codeString text = "Hello, Java!"; int length = text.length();
Accessing Characters: Individual characters within a string can be accessed using their index (0-based) with the
charAt()
method:javaCopy codeString message = "Hello"; char firstChar = message.charAt(0); // Gets the first character 'H'
Substring: You can extract substrings using the
substring()
method:javaCopy codeString text = "Java Programming"; String sub = text.substring(5, 12); // Gets "Program"
String Comparison: You can compare strings using the
equals()
method for content comparison andcompareTo()
method for lexicographic comparison:javaCopy codeString str1 = "Java"; String str2 = "java"; boolean isEqual = str1.equals(str2); // false, as the case is different int compareResult = str1.compareTo(str2); // Returns a positive/negative/zero value based on comparison
String Manipulation: The
String
class provides various methods for manipulating strings, such as converting case, replacing characters, trimming, etc.javaCopy codeString text = " Hello, Java! "; String trimmed = text.trim(); // Removes leading and trailing whitespace String upperCase = text.toUpperCase(); String replaced = text.replace("Java", "Programming");
String Formatting: You can format strings using the
String.format()
method or theprintf()
method (from theSystem.out
stream):javaCopy codeString formatted = String.format("Name: %s, Age: %d", "John", 30); System.out.printf("Formatted: %s%n", formatted);
String Splitting: You can split a string into an array of substrings using the
split()
method:javaCopy codeString csvData = "John,Doe,30"; String[] parts = csvData.split(",");
Remember that strings in Java are immutable, meaning once a string is created, you cannot modify its contents. Any operation that appears to modify a string actually creates a new string object. If you need to perform a lot of string manipulation, consider using the StringBuilder
class for improved performance, as it provides mutable sequences of characters.