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 concatenatestr1
andstr2
with a space in between. The result is stored in a new string variablestr4
.Substring extraction: We use the
substring
method to extract a substring starting from the 6th character ofstr4
, which corresponds to the word "World".String comparison: We use the
equals
method to comparestr1
andstr3
for equality. Note that this comparison is case-sensitive, so the result isfalse
becausestr1
contains an uppercase "H" whilestr3
contains 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
length
method returns the number of characters in a string.
javaString str = "Hello World";
int len = str.length();
// len will be 11
- IndexOf: The
indexOf
method 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
replace
method 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
trim
method removes any leading and trailing whitespace from a string.
javaString str = " Hello World ";
String newStr = str.trim();
// newStr will be "Hello World"
- Split: The
split
method 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
charAt
method returns the character at a specified index in a string.
javaString str = "Hello World";
char ch = str.charAt(6);
Comments
Post a Comment