Introduction

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.

Understanding ArrayLists and Strings

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:

import java.util.Arrays;
import java.util.ArrayList;

class Solution {
    public static void main(String[] args) {
        // Defining an ArrayList and a String
        // <Integer> specifies the type of Objects the ArrayList will hold
        ArrayList<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
        String myString = "hello";

        // Now let's try to change the first element of both these features
        // set method changes the element at the specified index (0 in this case)
        myList.set(0, 100);
        // There is no method set for Strings
        // The following method does not change the string in place,
        // but returns a new string where 'h' is replaced with 'H'
        myString.replace('h', 'H');
        // So it is possible to obtain a new string like this:
        String newString = myString.replace('h', 'H');
        
        System.out.println(myList); // prints [100, 2, 3, 4]
        System.out.println(myString); // prints hello
        System.out.println(newString); // prints Hello
    }
}
Diving Into Lists

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:

import java.util.ArrayList;
import java.util.Arrays;

class Solution {
    public static void main(String[] args) {
        // Creating an ArrayList
        ArrayList<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));

        // Add a new element at the end
        fruits.add("date"); // ['apple', 'banana', 'cherry', 'date']

        // Inserting an element at a specific position
        fruits.add(1, "bilberry"); // ['apple', 'bilberry', 'banana', 'cherry', 'date']

        // Removing a particular element
        fruits.remove("banana"); // ['apple', 'bilberry', 'cherry', 'date']

        // Accessing elements using indexing
        String firstFruit = fruits.get(0); // apple
        String lastFruit = fruits.get(fruits.size() - 1); // date

        // Converting static array to ArrayList and vice versa
        String[] fruitArray = {"kiwi", "lemon", "mango"};
        ArrayList<String> fruitList = new ArrayList<>(Arrays.asList(fruitArray));
        String[] newFruitArray = fruitList.toArray(new String[0]);
    }
}
Understanding Strings

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.

class Solution {
    public static void main(String[] args) {
        // Creating a string
        String greetingString = "Hello, world!";

        // Accessing characters using indexing
        char firstChar = greetingString.charAt(0);  // 'H'
        char lastChar = greetingString.charAt(greetingString.length() - 1);  // '!'

        // Making the entire string lowercase
        String lowercaseGreeting = greetingString.toLowerCase();  // "hello, world!"
    }
}

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:

class Solution {
    public static void main(String[] args) {
        // Using StringBuilder to create and modify a string
        StringBuilder sb = new StringBuilder("Hello");

        // Append characters to the string
        sb.append(", world!");

        // Insert characters at a specific position
        sb.insert(5, ",");

        // Convert StringBuilder back to a String
        String finalString = sb.toString();  // "Hello,, world!"
    }
}
Indexing and Common Operations

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!

import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;

class Solution {
    public static void main(String[] args) {
        // Define an ArrayList and a string
        ArrayList<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        String myString = "Hello";

        // Slicing: subList for ArrayList and substring for Strings
        ArrayList<Integer> sliceList = new ArrayList<>(myList.subList(2, 4)); // [3, 4]
        String sliceString = myString.substring(1, 3); // "el"

        // Concatenation: addAll for lists and + operator for strings
        ArrayList<Integer> concatenateList = new ArrayList<>(myList);
        concatenateList.addAll(Arrays.asList(6, 7, 8)); // [1, 2, 3, 4, 5, 6, 7, 8]
        String concatenateString = myString + ", world!"; // "Hello, world!"
        
        // Finding the index of an element in a list or a string
        // indexOf returns the first occurrence index of the element
        // returns -1 if the list or the string doesn't contain the element
        int indexList = myList.indexOf(3); // 2 - Index of element '3'
        int indexString = myString.indexOf('e'); // 1 - Index of character 'e'

        // Sorting items in ArrayList in non-increasing order
        ArrayList<Integer> sortedList = new ArrayList<>(myList);
        sortedList.sort(Collections.reverseOrder()); // [5, 4, 3, 2, 1]
    }
}
Lesson Summary and Practice

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal