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:

java

public 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:

  1. Concatenation: We use the + operator to concatenate str1 and str2 with a space in between. The result is stored in a new string variable str4.

  2. Substring extraction: We use the substring method to extract a substring starting from the 6th character of str4, which corresponds to the word "World".

  3. String comparison: We use the equals method to compare str1 and str3 for equality. Note that this comparison is case-sensitive, so the result is false because str1 contains an uppercase "H" while str3 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:

  1. Length: The length method returns the number of characters in a string.
java
String str = "Hello World"
int len = str.length(); 
// len will be 11
  1. IndexOf: The indexOf method returns the index of the first occurrence of a specified substring in a string.
java with mohit

String str = "Hello World"
int index = str.indexOf("o"); 
// index will be 4

  1. Replace: The replace method replaces all occurrences of a specified substring with another substring.
java

String str = "Hello World"
String newStr = str.replace("o", "a"); // newStr will be "Hella Warld"

  1. Trim: The trim method removes any leading and trailing whitespace from a string.
java

String str = " Hello World "
String newStr = str.trim(); 
// newStr will be "Hello World"

  1. Split: The split method splits a string into an array of substrings based on a specified delimiter.
java
String str = "Hello,World,Java"; String[] arr = str.split(","); 
// arr will be {"Hello", "World", //"Java"}
  1. CharAt: The charAt method returns the character at a specified index in a string.
java
String str = "Hello World"; char ch = str.charAt(6); 

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java