CodeGym /Java Course /Module 1. Java Syntax /Working with strings in Java

Working with strings in Java

Module 1. Java Syntax
Level 10 , Lesson 4
Available

1. Comparing strings

One of the most common operations with strings is comparison. The String class has over ten different methods that are used to compare one string with another string. Below we will take a look at seven of the main ones.

Methods Description
boolean equals(String str)
Strings are considered equal if all of their characters match.
boolean equalsIgnoreCase(String str)
Compares strings, ignoring the case of letters (ignores whether they are uppercase or lowercase)
int compareTo(String str)
Compares strings lexicographically. Returns 0 if the strings are equal. The return value is less than zero if the current string is less than the string parameter. The return value is greater than if the current string is greater than the string parameter.
int compareToIgnoreCase(String str)
Compares strings lexicographically while ignoring case. Returns 0 if the strings are equal. The return value is negative if the current string is less than the string parameter. The return value is greater than if the current string is greater than the string parameter.
boolean regionMatches(int toffset, String str, int offset, int len)
Compares parts of strings
boolean startsWith(String prefix)
Checks whether the current string starts with the string prefix
boolean endsWith(String suffix)
Checks whether the current string ends with the string suffix

Let's say you want to write a program that asks the user for a path to a file and then checks the file type based on its extension. The code of such a program might look something like this:

Code Notes
Scanner console = new Scanner(System.in);
String path = console.nextLine();

if (path.endsWith(".jpg") || path.endsWith(".jpeg"))
{
   System.out.println("This is a jpeg!");
}
else if (path.endsWith(".htm") || path.endsWith(".html"))
{
   System.out.println("This is an HTML page");
}
else if (path.endsWith(".doc") || path.endsWith(".docx"))
{
   System.out.println("This is a Word document");
}
else
{
   System.out.println("Unknown format");
}
Create a Scanner object
Read a line from the console

Check whether the string path ends with the given string

10
Task
New Java Syntax, level 10, lesson 4
Locked
Populate the Friend class
A friend (Friend class) must have three initializers (three initialize methods): - Name - Name, age - Name, age, sex. Note: name is a String, age is an int, and sex is a char.

2. Searching for substrings

After comparing strings, the second most popular operation is finding one string inside another. The String class also has a few methods for this:

Methods Description
int indexOf(String str)
Searches for the string str in the current string. Returns the index of the first character of the first occurrence.
int indexOf(String str, int index)
Searches for the string str in the current string, skipping the first index characters. Returns the index of the occurrence.
int lastIndexOf(String str)
Searches for the string str in the current string, starting from the end. Returns the index of the first occurrence.
int lastIndexOf(String str, int index)
Searches for the string str in the current string from the end, skipping the first index characters.
boolean matches(String regex)
Checks whether the current string matches a pattern specified by a regular expression.

The indexOf(String) and indexOf(String, index) methods are often used in combination. The first method lets you find the first occurrence of the passed substring in the current string. And the second method lets you find the second, third, etc. occurrences by skipping the first index characters.

Suppose we have a url like "https://domain.com/about/reviews", and we want to replace the domain name with "codegym.cc". Urls can have all sorts of different domain names, but we know the following:

  • The domain name is preceded by two forward slashes — "//"
  • The domain name is followed by a single forward slash — "/"

Here's what the code for such a program would look like:

Code Notes
Scanner console = new Scanner(System.in);
String path = console.nextLine();

int index = path.indexOf("//");
int index2 = path.indexOf("/", index + 2);

String first = path.substring(0, index + 2);
String last = path.substring(index2);

String result = first + "codegym.cc" + last;
System.out.println(result);
Create a Scanner object
Read a line from the console

Get the index of the first occurrence of the string "//"
We get the index of the first occurrence of the string /, but look only after an occurrence of the characters //.
We get the string from the beginning to the end of the characters //
We get the string from / to the end.

We concatenate the strings and the new domain.

The lastIndexOf(String) and lastIndexOf(String, index) methods work the same way, only the search is performed from the end of the string to the beginning.


10
Task
New Java Syntax, level 10, lesson 4
Locked
Populate the Dog class
A dog (Dog class) must have three initializers: - Name - Name, height - Name, height, color.

3. Creating substrings

In addition to comparing strings and finding substrings, there is another very popular action: getting a substring from a string. As it happens, the previous example showed you a substring() method call that returned part of a string.

Here is a list of 8 methods that return substrings from the current string:

Methods Description
String substring(int beginIndex, int endIndex)
Returns the substring specified by the index range beginIndex..endIndex.
String repeat(int count)
Repeats the current string n times
String replace(char oldChar, char newChar)
Returns a new string: replaces the character oldChar with the character newChar
String replaceFirst(String regex, String replacement)
Replaces the first substring, specified by a regular expression, in the current string.
String replaceAll(String regex, String replacement)
Replaces all substrings in the current string that match the regular expression.
String toLowerCase()
Converts the string to lowercase
String toUpperCase()
Converts the string to uppercase
String trim()
Removes all spaces at the beginning and end of a string

Here is a summary of the available methods:

substring(int beginIndex, int endIndex) method

The substring method returns a new string that consists of characters in the current string, starting at the character with index beginIndex and ending at endIndex. As with all intervals in Java, the character with index endIndex is not included in the interval. Examples:

Code Result
"Hellos".substring(0, 3);
"Hel"
"Hellos".substring(1, 4);
"ell"
"Hellos".substring(1, 6);
"ellos"
"Hellos".substring(1);
"ellos"

If the endIndex parameter is not specified (which is possible), then the substring is taken from character at beginIndex to the end of the string.

repeat(int n) method

The repeat method simply repeats the current string n times. Example:

Code Result
"Hello".repeat(3);
"HelloHelloHello"
"Hello".repeat(2);
"HelloHello"
"Hello".repeat(1);
"Hello"
"Hello".repeat(0);
""

replace(char oldChar, char newChar) method

The replace() method returns a new string in which all characters oldChar are replaced with the character newChar. This does not change the length of the string. Example:

Code Result
"Programming".replace('Z', 'z');
"Programming"
"Programming".replace('g', 'd');
"Prodrammind"
"Programming".replace('a', 'e');
"Progremming"
"Programming".replace('m', 'w');
"Prograwwing"

replaceFirst() and replaceAll() methods

The replaceAll() method replaces all occurrences of one substring with another. The replaceFirst() method replaces the first occurrence of the passed substring with the specified substring. The string to be replaced is specified by a regular expression. We will delve into regular expressions in the Java Multithreading quest.

Examples:

Code Result
"Good news everyone!".replaceAll("e.", "EX");
"Good nEXs EXEXyonEX"
"Good news everyone!".replaceAll("o.", "-o-");
"G-o-d news every-o-e!"
"Good news everyone!".replaceFirst("e.", "EX");
"Good nEXs everyone!"
"Good news everyone!".replaceFirst("o.", "-o-");
"G-o-d news everyone!"

toLowerCase() and toUpperCase() methods

We got to know these methods when we first learned about calling the methods of the String class.

trim() method

The trim() method removes leading and trailing spaces from a string. Does not touch spaces that are inside a string (i.e. not at the beginning or end). Examples:

Code Result
"     ".trim();
""
"Hello".trim();
"Hello"
" Hello\n how are you?\n   ".trim();
"Hello\n how are you?\n"
"  Password\n   \n ".trim();
"Password\n   \n"

10
Task
New Java Syntax, level 10, lesson 4
Locked
Let's put together a rectangle
The data for the rectangle (Rectangle class) will be top, left, width, and height. Create as many initialize(...) methods as possible Examples: - 4 parameters are specified: left, top, width, height - width/height is not specified (both are 0); - height is not specified (it is equal to the width), w
10
Task
New Java Syntax, level 10, lesson 4
Locked
Initializing objects
A person (Person class) should have a String name and int age. Add the initialize(String name, int age) method where you will initialize the variables name and age. In the main method, create a Person object and store a reference to it in the variable person. Call the initialize method with any valu
10
Task
New Java Syntax, level 10, lesson 4
Locked
Initializing cats
A cat (Cat class) must have five initializers: - Name - Name, weight, age - Name, age (standard weight) - Weight, color (unknown name, address and age, i.e. a homeless cat) - Weight, color, address (someone else's pet). The initializer's job is to make the object valid. For example, if the weight i
10
Task
New Java Syntax, level 10, lesson 4
Locked
Populate the Circle class
The Circle class must have three initializers: - centerX, centerY, radius - centerX, centerY, radius, width - centerX, centerY, radius, width, color.
10
Task
New Java Syntax, level 10, lesson 4
Locked
Initializing objects
Study the Person class carefully. Correct the class so that only one initialize method initializes all of the Person class's instance variables.
Comments (19)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Evgeniia Shabaeva Level 32, Budapest, Hungary
19 April 2024
Thank you for the lesson. I'd like to see a few examples of how boolean matches(String regex) can be used, for instance, to check if a certain string contains a group of several letters or digits in different positions.
oniks nik Level 10, Ukraine
30 January 2024
path.replaceFirst("jdk.+/", jdk+"/"); Output /usr/java/jdk-13/bin But it's not verify. Why?)))
Ranganathan Kasiganesan Level 76, Chennai, India Expert
22 November 2023
Most simple solution: path.replaceFirst("jdk1.8", jdk); But it is not expected solution.:)
Campbell, Jackson Level 12, Corona, USA
30 October 2023
Bro mine worked first try, letz goooooooo ඩ
2 October 2023
If you want us to use a specific method then say so. Or at least give us enough information to figure out what you want. These instructions are not getting any better. I can see why .indexOf could be a better choice because if we didn't know the path before hand there could be other /s in the path after the JDK and that would make .lastIndexOf a bad choice.
Tomasz Enyeart Level 16, United States
7 February 2024
i worry the requirements are getting worse
Kristian Kelij Level 18, Slovakia
30 November 2022
Can anybody tell me why it won't pass the test, althought it has correct output ?

public static String changePath(String path, String jdk) {
                //write your code here
                int startOfJDK = path.indexOf("jdk");
                int endOfJDK = path.lastIndexOf("/");
                return path.substring(0,startOfJDK) + jdk + path.substring(endOfJDK, path.length());
        }
output : /usr/java/jdk-13/bin also same output when testing input with longer jdk version for example :

String path = "/usr/java/jdk58.787/bin"
also not working after editing return statement of changePath:

return new String(path.substring(0,startOfJDK) + jdk + path.substring(endOfJDK, path.length()));
Takuya Yi Level 17, United States of America, United States
12 December 2022
similar issue, cannot pass this one
Zac Level 17, Austin, United States
2 June 2023
Try leaving off the second parameter in your final substring. So instead of: path.substring(endOfJDK, path.length()) try path.substring(endOfJDK)
Chrizzly Level 12, Earth, Germany
19 November 2022
Hey guys, got a really stupid question, but maybe one can answer it, so that I can understand it better: How does the compiler know in the changePath-method, what the String jdk is? If I let it print -> System.out.println(jdk); //it knows, it's jdk-13 But how? It the method there is no variable called jdk, nor is it in the main method. I expected an error, because this is not initialized. Thank you. :)
Chrizzly Level 12, Earth, Germany
19 November 2022
I guess it's some recursive thinking... It's just Null while it is not called in the main method via: System.out.println(changePath(path, jdk13)); and because it is called there, it gets initialized with whatever is inside the String jdk13, right?
Supersnubben Level 16, Stockholm, Sweden
15 July 2023

String path = "/usr/java/jdk1.8/bin";

 String jdk13 = "jdk-13";
 System.out.println(changePath(path, jdk13));
In the main method the variables path and jdk13 are declared and initialized with values. Then in the print statement the changePath method is called with those variables as parameters. In other words the variables are passed into the method.
Parsa Level 62, Bangalore, India Expert
29 October 2023
jdk is the parameter.

public static String changePath(String path, String jdk) {
And jdk13 is the argument passed to the method.

String jdk13 = "jdk-13";
System.out.println(changePath(path, jdk13));
manny9876 Level 34, Israel
27 October 2022
Can anyone explain in simple terms what is a 'regular expression'? Thanks!
Supersnubben Level 16, Stockholm, Sweden
15 July 2023
A regular expression, or RegEx, is a "language" to match certain substrings or characters of a String. Let's say you are writing a program that will ask a user to input a email adress. You can use regular expressions to check if the input is in a correct email format. For example <whatever>@<whatever>.<whatever>. Let's write an example:
Supersnubben Level 16, Stockholm, Sweden
15 July 2023

        String email = "example@example.com";
        // The string you want to match.
        String pattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+\\.[A-Za-z]{2,}$";
        /* 
           This is the regex matching pattern. It looks advanced, but really isn't. Let me break it down.
           
           The ^ sign indicates the start of the string. The $ indicates the end of the string.  

           [A-Za-z0-9._%+-]+ indicates that your patterns wants to match any character between A-Z, a- 
           z, 0-9 and the symbols given. See the [ ] brackets like a box of characters. When the box is 
           placed after the ^ it means you want to match any character inside that box from the start of 
           the string. The + after the box means you want to continue to match characters from the start 
           of the string until your pattern say otherwise. In this case until the @ sign. 

           Same thing after the @ sign, until the . sign ( \\. is an escaped character for dot). 

           Then lastly  [A-Za-]{2,}  indicates that you want to match any character in the box, at least 2 or 
           more times. The first number inside the { } brackets means how many characters you want to 
           match AT LEAST, the second number means AT MOST. In this case there isn't a second 
           number so this pattern requires there to be at least 2 characters after the last dot.
         */

         System.out.println(email.matches(pattern));
         // Match your pattern with the matches method and it returns a bool result of true and false.
         
tokyoocean Level 14, Ukraine
28 July 2022
Why, in the last exercise, if I put code like this it do not accepted by verifier?

return "/usr/java/jdk1.8/bin".replace("jdk1.8", jdk);
output is correct: /usr/java/jdk-13/bin
MoGunz Level 13, Muskegon, United States
6 August 2022
It's not stated in the parameters, but they want you to use the indexOf method.
Андрей Пинчук Level 33, San Francisco, Ukraine
15 August 2022
Your code won't work with path like "/usr/java/jdk-1.8/bin" etc CodeGym tests uses different strings. The main method is only for programmers to easily check if their code works.