Understanding Java Strings

Sona - Dec 14 '23 - - Dev Community

Understanding Java Strings:

In Java, a string is a sequence of characters encapsulated within double quotes (" "). Strings in Java are immutable, meaning their values cannot be changed once they are created. They are instances of the java.lang.String class and offer a multitude of methods for manipulation.

// Creating strings using string literals
String message = "Hello, Java!";

// Creating strings using the String class constructor
String greeting = new String("Welcome");

*Basic String Operation:
*

// Concatenation
String fullName = "John" + " " + "Doe";

// Length of a string
int length = fullName.length();

// Accessing characters at specific indexes
char firstChar = fullName.charAt(0); // Accessing the first character
char lastChar = fullName.charAt(length - 1); // Accessing the last character

*String Comparison:
*

String str1 = "Hello";
String str2 = "hello";

// Comparing strings for equality (case-sensitive)
boolean isEqual = str1.equals(str2); // false

// Comparing strings ignoring case
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // true

*Substring and Manipulation:
*

String sentence = "The quick brown fox jumps over the lazy dog";

// Extracting substrings
String subString1 = sentence.substring(10); // Extracts from index 10 to end
String subString2 = sentence.substring(4, 9); // Extracts from index 4 to 8

// Replacing characters or sequences
String replacedString = sentence.replace("fox", "cat");

// Splitting a string
String[] words = sentence.split(" ");

*Advanced String Operations:
*

String text = " Trim me ";

// Trimming whitespaces
String trimmedText = text.trim();

// Converting cases
String upperCaseText = text.toUpperCase();
String lowerCaseText = text.toLowerCase();

Java strings are powerful and versatile, offering a plethora of methods to manipulate and work with textual data. Understanding strings is fundamental in Java programming, enabling you to handle data effectively and perform various string operations efficiently.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player