Welcome to this course!
Before we delve deeper into Java essentials for interview prep, let's start with some foundational Java features — specifically, ArrayLists
and Strings
. These features allow Java to group multiple elements, such as numbers or characters, under a single entity.
As our starting point, it's crucial to understand how ArrayLists
and Strings
function in Java. ArrayList
is part of Java’s Collections Framework
and is mutable (we can change it after creation), while Strings
are immutable (unalterable post-creation). Let's see examples:
Java1import java.util.Arrays; 2import java.util.ArrayList; 3 4class Solution { 5 public static void main(String[] args) { 6 // Defining an ArrayList and a String 7 // <Integer> specifies the type of Objects the ArrayList will hold 8 ArrayList<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3, 4)); 9 String myString = "hello"; 10 11 // Now let's try to change the first element of both these features 12 // set method changes the element at the specified index (0 in this case) 13 myList.set(0, 100); 14 // There is no method set for Strings 15 // The following method does not change the string in place, 16 // but returns a new string where 'h' is replaced with 'H' 17 myString.replace('h', 'H'); 18 // So it is possible to obtain a new string like this: 19 String newString = myString.replace('h', 'H'); 20 21 System.out.println(myList); // prints [100, 2, 3, 4] 22 System.out.println(myString); // prints hello 23 System.out.println(newString); // prints Hello 24 } 25}
Imagine having to take an inventory of all flora in a forest without a list at your disposal — seems near impossible, right? That's precisely the purpose ArrayList
serves in Java. They let us organize data so that each item holds a definite position or an index. The index allows us to access or modify each item individually.
Working with Lists in Java is as simple as this:
Java1import java.util.ArrayList; 2import java.util.Arrays; 3 4class Solution { 5 public static void main(String[] args) { 6 // Creating an ArrayList 7 ArrayList<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "cherry")); 8 9 // Add a new element at the end 10 fruits.add("date"); // ['apple', 'banana', 'cherry', 'date'] 11 12 // Inserting an element at a specific position 13 fruits.add(1, "bilberry"); // ['apple', 'bilberry', 'banana', 'cherry', 'date'] 14 15 // Removing a particular element 16 fruits.remove("banana"); // ['apple', 'bilberry', 'cherry', 'date'] 17 18 // Accessing elements using indexing 19 String firstFruit = fruits.get(0); // apple 20 String lastFruit = fruits.get(fruits.size() - 1); // date 21 22 // Converting static array to ArrayList and vice versa 23 String[] fruitArray = {"kiwi", "lemon", "mango"}; 24 ArrayList<String> fruitList = new ArrayList<>(Arrays.asList(fruitArray)); 25 String[] newFruitArray = fruitList.toArray(new String[0]); 26 } 27}
Think of Strings as a sequence of letters or characters. So, whether you're writing down a message or noting a paragraph, it all boils down to a string in Java. Strings are enclosed by double quotes.
Java1class Solution { 2 public static void main(String[] args) { 3 // Creating a string 4 String greetingString = "Hello, world!"; 5 6 // Accessing characters using indexing 7 char firstChar = greetingString.charAt(0); // 'H' 8 char lastChar = greetingString.charAt(greetingString.length() - 1); // '!' 9 10 // Making the entire string lowercase 11 String lowercaseGreeting = greetingString.toLowerCase(); // "hello, world!" 12 } 13}
Though strings are immutable, we can use string methods such as .toLowerCase()
, .toUpperCase()
, and .trim()
, to effectively work with them. These methods essentially create a new string for us.
If you need to append or modify a string efficiently, you can use StringBuilder
. Here's how:
Java1class Solution { 2 public static void main(String[] args) { 3 // Using StringBuilder to create and modify a string 4 StringBuilder sb = new StringBuilder("Hello"); 5 6 // Append characters to the string 7 sb.append(", world!"); 8 9 // Insert characters at a specific position 10 sb.insert(5, ","); 11 12 // Convert StringBuilder back to a String 13 String finalString = sb.toString(); // "Hello,, world!" 14 } 15}
Both ArrayList
and Strings
allow us to access individual elements through indexing. In Java, we start counting from 0, implying the first element is at index 0, the second at index 1, and so on. Negative indexing is not directly supported in Java, but you can work around it by adjusting indices based on the length of the collection.
We have many operations we can perform on our lists and strings. We can slice them, concatenate them, and even find an occurrence of a particular element!
Java1import java.util.ArrayList; 2import java.util.Collections; 3import java.util.Arrays; 4 5class Solution { 6 public static void main(String[] args) { 7 // Define an ArrayList and a string 8 ArrayList<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); 9 String myString = "Hello"; 10 11 // Slicing: subList for ArrayList and substring for Strings 12 ArrayList<Integer> sliceList = new ArrayList<>(myList.subList(2, 4)); // [3, 4] 13 String sliceString = myString.substring(1, 3); // "el" 14 15 // Concatenation: addAll for lists and + operator for strings 16 ArrayList<Integer> concatenateList = new ArrayList<>(myList); 17 concatenateList.addAll(Arrays.asList(6, 7, 8)); // [1, 2, 3, 4, 5, 6, 7, 8] 18 String concatenateString = myString + ", world!"; // "Hello, world!" 19 20 // Finding the index of an element in a list or a string 21 // indexOf returns the first occurrence index of the element 22 // returns -1 if the list or the string doesn't contain the element 23 int indexList = myList.indexOf(3); // 2 - Index of element '3' 24 int indexString = myString.indexOf('e'); // 1 - Index of character 'e' 25 26 // Sorting items in ArrayList in non-increasing order 27 ArrayList<Integer> sortedList = new ArrayList<>(myList); 28 sortedList.sort(Collections.reverseOrder()); // [5, 4, 3, 2, 1] 29 } 30}
Give yourself a pat on the back! You've navigated through ArrayList
and Strings
, learning how to create, access, and manipulate them via various operations.
Up next, reinforce your understanding with plenty of hands-on practice. The comprehension of these concepts, combined with frequent practice, will enable you to tackle more complex problem statements with ease. Happy coding!