Lesson Introduction

Welcome! Today, we're going to delve into the fundamental operations and methods associated with Strings in Java. Strings are the bread and butter for most programs because they're used to represent and manipulate text data. This lesson will enable you to learn about basic string methods and operations in Java such as concatenation, comparison, and most common methods.

Revising String Concatenation

We already know what concatenation is and how it works, but worth revising it quickly! Concatenation means joining things together and is a crucial string operation. In Java, we accomplish this with the + operator or using StringBuilder.

In this case, "Hello, " and "World!" are combined to form one string: "Hello, World!".

Comparing Strings

There are often times when we need to compare Strings. Unfortunately, just a common comparison operators == and < will not work here. To accomplish this in Java, we use the equals() and compareTo() methods.

The equals() method, as the name suggests, checks if two Strings are identical.

Here, since firstWord and secondWord are equal, areEqual is true.

The compareTo() method, on the other hand, is used to compare two strings alphabetically. compareTo() will return 0 if the strings are equal, a negative number if the first string comes first alphabetically, and a positive number otherwise.

As you can see, the comparison result is negative, meaning that "Apple" is alphabetically smaller than "Banana"

Important String Methods

Now, let's explore the other common String methods:

  • length(): This method returns the number of characters in the String.
  • substring(int beginIndex, int endIndex): This method returns the section of the original String from beginIndex (inclusive) to endIndex (exclusive).
  • toLowerCase() and toUpperCase(): These methods return the string in either lowercase or uppercase, respectively.
  • trim(): This method removes all white spaces at the beginning and the end of the String.
Lesson Summary and Next Steps

Excellent job! You've learned the intricacies of String operations and methods, the steps necessary for manipulating Strings in Java, and how to combine and compare strings. Additionally, we've covered some of the most frequently used String methods in Java.

The upcoming practice exercises will provide you with an opportunity to apply what you've learned. You're getting closer to mastering Java with every step! Keep going, and good luck!

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