Java Arrays and Strings
Reverse a string
Description: Reverse the text "Java" to "avaJ". Do it with a loop and with StringBuilder.
Hint:
- Go from the last index to 0 and join the characters.
StringBuilderhas areverse()method.
Solution
public class Main {
static String reverseLoop(String s) {
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result += s.charAt(i);
}
return result;
}
public static void main(String[] args) {
System.out.println(reverseLoop("Java"));
System.out.println(new StringBuilder("Java").reverse());
}
}
avaJ
avaJ
How it works
charAt(i)gives one character. The loop reads them from the end.StringBuilder.reverse()is the shortest way.
Read Java String Methods.
Check if a string is a palindrome
Description: A palindrome reads the same from both sides, like madam. Write isPalindrome(String s) which ignores the case and the spaces. Test it with “Madam”, “Nurses run” and “Java”.
Hint:
- Clean the text with
replace(" ", "")andtoLowerCase(), then compare it with its reverse.
Solution
public class Main {
static boolean isPalindrome(String s) {
String clean = s.replace(" ", "").toLowerCase();
String reversed = new StringBuilder(clean).reverse().toString();
return clean.equals(reversed);
}
public static void main(String[] args) {
for (String text : new String[]{"Madam", "Nurses run", "Java"}) {
System.out.println(text + " -> " + isPalindrome(text));
}
}
}
Madam -> true
Nurses run -> true
Java -> false
How it works
- We remove the spaces and use one case, so only the letters are compared.
equals()compares the text. Do not use==.
Read Java Strings.
Count the vowels in a string
Description: Count how many vowels (a, e, i, o, u) and how many consonants are in "Learn Java Programming".
Hint:
- Use
toCharArray(),Character.isLetter()andindexOfon the string"aeiou".
Solution
public class Main {
public static void main(String[] args) {
String text = "Learn Java Programming";
int vowels = 0, consonants = 0;
for (char c : text.toLowerCase().toCharArray()) {
if (!Character.isLetter(c)) continue; // skip the spaces
if ("aeiou".indexOf(c) >= 0) {
vowels++;
} else {
consonants++;
}
}
System.out.println("Vowels: " + vowels + ", consonants: " + consonants);
}
}
Vowels: 7, consonants: 13
How it works
"aeiou".indexOf(c)gives -1 when the letter is not a vowel.continueskips the spaces.
Read Java String Methods.
Find the second largest number in an array
Description: Find the second largest number in {12, 35, 1, 10, 34, 1} without sorting the array.
Hint:
- Keep two variables:
largestandsecond. Update both in one loop.
Solution
public class Main {
static int secondLargest(int[] a) {
int largest = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : a) {
if (n > largest) {
second = largest;
largest = n;
} else if (n > second && n != largest) {
second = n;
}
}
return second;
}
public static void main(String[] args) {
System.out.println(secondLargest(new int[]{12, 35, 1, 10, 34, 1}));
System.out.println(secondLargest(new int[]{5, 5, 5, 2}));
}
}
34
2
How it works
- When a new biggest value comes, the old biggest becomes the second.
n != largestignores the duplicates of the biggest value.
Read Java Arrays.
Sort an array with bubble sort
Description: Sort {64, 34, 25, 12, 22, 11, 90} in ascending order without using Arrays.sort(). Then check your answer with Arrays.sort().
Hint:
- Compare each pair of neighbours and swap them if they are in the wrong order. Repeat.
Solution
import java.util.Arrays;
public class Main {
static void bubbleSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
boolean swapped = false;
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break; // already sorted
}
}
public static void main(String[] args) {
int[] data = {64, 34, 25, 12, 22, 11, 90};
int[] check = data.clone();
bubbleSort(data);
Arrays.sort(check);
System.out.println(Arrays.toString(data));
System.out.println(Arrays.equals(data, check));
}
}
[11, 12, 22, 25, 34, 64, 90]
true
How it works
- After each round of the outer loop, the biggest remaining value goes to its place at the end.
- If a full round makes no swap, the array is sorted and we stop.
- Bubble sort is good to learn, but slow (O(n squared)). Real code uses
Arrays.sort().
Read Java Arrays.
Transpose a matrix
Description: Transpose the matrix {{1,2,3},{4,5,6}}. The result must be {{1,4},{2,5},{3,6}}.
Hint:
- The new matrix has
columnsrows androwscolumns. Copym[i][j]tot[j][i].
Solution
import java.util.Arrays;
public class Main {
static int[][] transpose(int[][] m) {
int rows = m.length, cols = m[0].length;
int[][] t = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
t[j][i] = m[i][j];
}
}
return t;
}
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}};
System.out.println(Arrays.deepToString(transpose(m)));
}
}
[[1, 4], [2, 5], [3, 6]]
How it works
- A 2 x 3 matrix becomes a 3 x 2 matrix, so a new array with the sizes swapped is needed.
Read Multidimensional Arrays.