Operations on Strings in Java
Understanding Operations on Strings
String operations involve various manipulations such as concatenation, reversal, and comparison.
We will explore three different methods to perform operations on strings in Java.
Method 1: Using Standard Library Functions
This method uses built-in string functions for operations.
public class StringOperations { public static void main(String[] args) { String str1 = "Hello"; String str2 = " World"; str1 += str2; System.out.println("Concatenated String: " + str1); System.out.println("Length of String: " + str1.length()); } }
Length of String: 11
Method 2: Using Character Array Manipulation
This method manually processes each character for operations.
public class ReverseString { public static void main(String[] args) { String str = "Hello"; char[] charArray = str.toCharArray(); int left = 0, right = charArray.length - 1; while (left < right) { char temp = charArray[left]; charArray[left] = charArray[right]; charArray[right] = temp; left++; right--; } System.out.println("Reversed String: " + new String(charArray)); } }
Method 3: Using Pointer Manipulation (Character Comparison)
This method performs operations using character comparison.
public class CompareStrings { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; if (str1.equals(str2)) { System.out.println("Strings are equal"); } else { System.out.println("Strings are not equal"); } } }