Java Cheatsheet for Arrays and Strings
---
1. Array Basics
Declare and Initialize Arrays:
int[] arr = new int[5]; // Array of integers with size 5
String[] names = {"Alice", "Bob", "Charlie"}; // String array with values
Accessing Elements:
int x = arr[0]; // Access first element
arr[1] = 10; // Modify second element
Input/Output for Arrays:
// Taking input for an integer array
Scanner sc = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
// Printing array
for (int i : arr) {
System.out.print(i + " ");
}
---
2. Sorting Arrays
Bubble Sort (Swaps adjacent elements):
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
Using Built-in Sort (Arrays Class):
Arrays.sort(arr); // Sorts the array in ascending order
---
3. Searching in Arrays
Linear Search (Go through each element):
int target = 5;
boolean found = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
System.out.println("Found at index " + i);
found = true;
break;
}
}
if (!found) System.out.println("Not found");
Binary Search (Only on sorted arrays):
int low = 0, high = arr.length - 1;
int target = 10;
boolean found = false;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
System.out.println("Found at index " + mid);
found = true;
break;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (!found) System.out.println("Not found");
---
4. String Basics
Creating and Initializing Strings:
String s = "Hello World"; // Literal
String s2 = new String("Hello World"); // Using constructor
Basic String Methods:
s.length(); // Get length
s.charAt(2); // Get character at index 2
s.toLowerCase(); // Convert to lowercase
s.toUpperCase(); // Convert to uppercase
s.substring(1, 4); // Extract substring from index 1 to 3
s.equals("Hello"); // Check equality
s.equalsIgnoreCase("hello"); // Check equality ignoring case
---
5. Common String Programs
Palindrome Checker:
String str = "madam";
String rev = new StringBuilder(str).reverse().toString();
if (str.equalsIgnoreCase(rev)) System.out.println("Palindrome");
else System.out.println("Not a palindrome");
Count Vowels and Consonants:
int vowels = 0, consonants = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) != -1) vowels++;
else if (Character.isLetter(ch)) consonants++;
}
System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);
Reversing a String:
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println("Reversed: " + reversed);
Word Count in a Sentence:
String sentence = "Java is fun";
String[] words = sentence.split("\\s+"); // Split by spaces
System.out.println("Number of words: " + words.length);
Replace Vowels with '*':
String modified = str.replaceAll("[AEIOUaeiou]", "*");
System.out.println("Modified: " + modified);
---
6. Additional Tips for Arrays and Strings
Check Array Length: arr.length
Check String Length: str.length()
Convert Array to List (For Easy Printing):
System.out.println(Arrays.toString(arr)); // Prints array as a string
Trim a String (Remove spaces at ends): str.trim()
Comparing Strings (Alphabetically): s1.compareTo(s2)
Returns 0 if equal, <0 if s1 is lexicographically less, and >0 if more.
This cheatsheet should help you quickly revise the key concepts, syntax, and programs for
Java arrays and strings. Let me know if you'd like more in-depth explanations on any specific
part!