String Operations in Java
 In Java, a string is a sequence of characters that is represented using the String class. There are several operations that can be performed on strings in Java, including concatenation, substring extraction, and string comparison.
Here is an example program that demonstrates some common string operations:
javapublic class StringOperations 
{ 
public static void main(String[] args)
 { 
String str1 = "Hello"; 
String str2 = "World"; 
String str3 = "hello"; 
// Concatenation 
String str4 = str1 + " " + str2;
        System.out.println(str4); 
// Output: Hello World 
// Substring extraction 
String substr = str4.substring(6);
        System.out.println(substr);
// Output: World 
// String comparison 
boolean equal = str1.equals(str3);
        System.out.println(equal); 
// Output: false 
 } 
}
In this example program, we create three string variables: str1, str2, and str3. We then perform three different operations on these strings:
- Concatenation: We use the - +operator to concatenate- str1and- str2with a space in between. The result is stored in a new string variable- str4.
- Substring extraction: We use the - substringmethod to extract a substring starting from the 6th character of- str4, which corresponds to the word "World".
- String comparison: We use the - equalsmethod to compare- str1and- str3for equality. Note that this comparison is case-sensitive, so the result is- falsebecause- str1contains an uppercase "H" while- str3contains a lowercase "h".
These are just a few examples of the many string operations that can be performed in Java.
Here are some more string operations in Java with examples:
- Length: The lengthmethod returns the number of characters in a string.
javaString str = "Hello World"; int len = str.length(); // len will be 11
- IndexOf: The indexOfmethod returns the index of the first occurrence of a specified substring in a string.
java with mohitString str = "Hello World"; 
int index = str.indexOf("o"); 
// index will be 4
- Replace: The replacemethod replaces all occurrences of a specified substring with another substring.
javaString str = "Hello World"; 
String newStr = str.replace("o", "a"); // newStr will be "Hella Warld"
- Trim: The trimmethod removes any leading and trailing whitespace from a string.
javaString str = "   Hello World   "; 
String newStr = str.trim(); 
// newStr will be "Hello World"
- Split: The splitmethod splits a string into an array of substrings based on a specified delimiter.
javaString str = "Hello,World,Java";
String[] arr = str.split(","); // arr will be {"Hello", "World", //"Java"}
- CharAt: The charAtmethod returns the character at a specified index in a string.
javaString str = "Hello World";
char ch = str.charAt(6); 
Comments
Post a Comment