Java: Strings and String Methods

Apart from the primitive data types, Java also has a few advanced data types. This lesson will focus on strings, and the other one is arrays.

Strings

Let us start with Strings! In simple terms, a string is a piece of text such as “Hi There” or “Good Evening.”

Initializing and declaring a string variable is done in this manner: 

String evening = "Good Evening";

Where evening is the variable name of the String and “Good Evening” is the string value that has been assigned. Remember that while initializing a string, the string has to be enclosed in double-quotes (“).

It is also possible to assign an empty string to a string variable in this manner:

String message2 = "";

Combining two or more strings is extremely simple and can be done using the concatenate sign (+) between them. For example

String userName = "Hey Everybody, " + "I am James";

This is the same as

String userName = "Hey Everybody, I am James";

String Methods

A String is an object, which is quite different from the eight primitive types mentioned above. To be more precise, it is an object of the String class.

Classes and objects will be covered in the subsequent lessons. Firstly, just understand that there are many pre-written methods in the String class that can manipulate or change our strings. A method is a block of reusable code that executes a specific task. This will be discussed a little later. 

In Java language, a method can be used in different ways by exploiting its many variations. Our examples will only deal with one such variation of every method. However, the good news is that mastering the use of one variation can make it quite easy to learn the other variations. So, let us begin exploring the common String methods.

length()

As the name implies, the length() method will calculate the length of the string, or in other words, the number of characters that the string holds. 

Therefore, to find the length of the string “Good Evening,” write the following code.

"Good Evening".length();

The format to write a method is the dot operator, followed by the method name and then a parenthesis pair (). Typically, methods tend to return an answer once the task is executed. As stated, the length() method returns the number of characters in a string. The result can also be stored in another variable, as demonstrated below.  

int userLength = "Good Evening".length();

In the example above, userLength will return the result as 12 because “Good” is of 4 letters, “Evening” is 7, and space adds another character to the string. 

To display the length of the string using the length() method, use the following statements.

int userLength = "Good Evening".length();
System.out.println(userLength);

To use these statements to be included in a full-fledged program, they must include the length() method within the opening and closing brackets of the main() method. After running the program, number 12 is displayed in the output. The concept of outputs will be discussed in another lesson.  

toUpperCase()/toLowerCase()

The toUpperCase() method, as is self-explanatory, is used to convert all the characters in a string to uppercase. The toLowerCase() method is used to convert all the characters in a string to lowercase.

For example, the string “Good Evening” can be converted to upper case.

String upCase = "Good Evening".toUpperCase();

The string “Good Evening” has been used to call the toUpperCase() method on the operator’s right side. The result is assigned to upCase. Upon using this method, upCase will become “GOOD EVENING.” 

substring()

The substring() method is an extremely useful method that helps extract a substring from a long string. 

A few Java methods do not work unless data is provided within the parenthesis pair beside method name. The data is also known as arguments. The substring() method is one such method that cannot be executed without an argument.  

For example, let us extract a substring from “Good Evening.”

String exampleSubstring = "Good Evening".substring(5);

Like the previous example, the string “Good Evening” was used to call the substring() method. In the parenthesis, number 5 was used, which is the argument. What does it mean? Very simple. It informs the compiler regarding the point from which the programmers want their substring to be extracted. Here, the statement tells the compiler to extract the substring beginning from index 5 or the string’s 5th position until the end. 

An important point to remember is that indexing begins with the number ZERO instead of one in programming. This convention is common in most programming languages. Therefore, “G” is at index 0, and “E” is at 5.

Consequently, the example string will extract the substring “Evening,” assigned to the variable exampleSubstring

exampleSubstring is now equal to the term “Evening.”

There is another useful variation of the substring() method, wherein the exact index of the last character that is needed in our substring can be extracted. For instance, to extract from index 3 to index 6, use the following statement:    

String example1 = "Good Evening";
String example2 = example1.substring(3, 7);

Here, the first statement has assigned example1 with “Good Evening.” Then example1 is used to call the substring() method.

The two arguments entered are 3 and 7.

Like the previous example, the initial index informs the compiler regarding where it should begin extracting the substring. The second argument tells the compiler the index position of the first character that need not be extracted. Therefore, the compiler is being directed that position seven need not be extracted, which is “e.” The substring that is extracted is “d Ev.”    

example2 is now assigned the string “d Ev.”

example1 continues to remain “Good Evening.”

charAt()

The charAt() method is used to return the character that is present at a specified index. Therefore, it always returns only one character, which can be assigned to a char variable.

Again, let us take an example to understand better! 

char exampleChar = "Good Evening".charAt(3);

Will extract the character positioned at index 3 and assign it to exampleChar. Therefore, upon execution, exampleChar will become ‘d.’

equals()

The equals() method compares two different strings and returns a boolean value of ‘true’ if the two strings are equal and ‘false’ if they are not.  

Let us take two examples to see how it works:

boolean checkEquality = "Good Morning".equals("Good Evening");
boolean checkEquality2 = "Good Morning".equals("Good Morning");

While the first statement returns false, the second returns true.

split()

The split() method is used to split a string into several substrings, using a user-defined separator, commonly referred to as a delimiter. Once the string is split, the method returns an array comprised of the various substrings. Array is a topic that will be touched upon later, but basically, it is a set of related data.   

For example, to split the string “Joey, Ross, Rachel, Monica” into different substrings; use the following method:

String names1 = "Joey, Ross, Rachel, Monica";
String[] splitNames1 = names1.split(", ");

What just happened? Well, first, the string that will be split later was assigned. Then, the names1 variable was used to call the split() method. The split() method was given the argument of a comma followed by the space. The argument of this method must always be the delimiter used to separate the substring. 

Consequently, the result is the array stated below:

{"Joey", "Ross", "Rachel", "Monica"}

This array was assigned to the variable splitNames1.

While some of the most commonly used String methods in Java have been listed, the following link has all the available methods: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#method.summary

Strings are Immutable 

This topic is related to strings and their immutable nature in Java and most other programming languages. 

Immutable means that the value within a string variable cannot be altered. Therefore, each time a String variable is updated, a completely new string is created to which the memory address is allocated. For instance, consider this example. 

String message = "Perfect";

As studied earlier, the string “perfect” is created and stored somewhere in the computer’s memory by the compiler. The variable message only stores the path to that location. So now, if the content of message is changed to “Great” in this manner

message = "Great";

The compiler does not substitute “Perfect” with “Great.” A new string called “Great” is created and stored somewhere else in the computer’s memory. This new path is assigned to message. To explain it further, both “Perfect” and “Great” are present in the computer’s memory. However, the address of “Great” is assigned to message. In case “Perfect” does not serve any purpose in the program, it is destroyed gradually to free up some space in the memory. Java takes care of this process automatically, and it is known as garbage collection.

Leave a Reply

%d bloggers like this: