Common String Operations in Java
1. Creating Strings
// Direct initialization
String str1 = "def";
// Using the constructor
String str2 = new String("def");
2. Comparing Strings: '==', 'equals', 'equalsIgnoreCase'
(1) '==':
// Compares memory addresses for reference types
// String literals are stored in a pool, and if a matching string exists, the address is reused
// This saves memory
String str1 = "def";
String str2 = "def";
System.out.println(str1 == str2); // true
String str3 = new String("def");
System.out.println(str1 == str3); // false
(2) 'equals':
String str1 = "def";
String str2 = "def";
boolean result1 = str1.equals(str2);
System.out.println(result1); // true
String str3 = new String("def");
boolean result2 = str1.equals(str3);
System.out.println(result2); // true
String str4 = "Def";
boolean result3 = str4.equals(str1);
System.out.println(result3); // false (case-sensitive)
(3) 'equalsIgnoreCase':
String str1 = "def";
String str2 = "DEF";
boolean result = str1.equalsIgnoreCase(str2);
System.out.println(result); // true
Note: Input from the keyboard is also considered as using 'new'.
3. Iterating Through a String
Using charAt():
String source = "wxyz";
for(int i = 0; i < source.length(); i++) {
char ch = source.charAt(i);
System.out.println(ch); // w x y z
}
4. Concateantion and Reversal of Strings
(1) Concatenation:
public class demo {
public static void main(String[] args) {
int[] arr = {4, 5, 6};
System.out.print("[");
for(int i = 0; i < arr.length; i++) {
System.out.print(i == arr.length - 1 ? arr[i] + "]" : arr[i] + ", ");
}
}
}
(2) Reversal:
public class demo {
public static void main(String[] args) {
String input = "abcde";
for(int i = input.length() - 1; i >= 0; i--) {
System.out.print(input.charAt(i));
}
}
}
public clas demo {
public static void main(String[] args) {
String input = "abcde";
String output = "";
for(int i = enput.length() - 1; i >= 0; i--) {
char c = input.charAt(i);
output += c;
}
System.out.println(output);
}
}