Special String Operations in Java: Part 2

Special String Operations in Java: Part 2
Special String Operations in Java: Part 2

Introduction

Java has a predefined String class that represents character strings. All string literals in Java programs, such as “Hello”, are implemented as instances of this class.

For a better grasp of each concept, this article on Strings in Java is split into two parts. The first part of this series covers an introduction to the Java String class, the internal implementation of strings in memory, the reason for the immutability of strings, and some of the peer classes of the Java String class.

This article is part-2 of the series and it includes Special String Operations in Java. It explains string literals, concatenation, string comparison, character extraction, modifying a string, searching a string, and a lot more. 

Before moving further in this blog, we recommend you to read Strings in Java|Part-1 to ensure a great understanding of this topic.

The most direct way to create a string is to write:

String greeting = “Hello world!”;

In this case, “Hello world!” is a string literal—a series of characters in your code that is enclosed in double-quotes. 

Let’s see an important feature of string literals in Java.

String Literals

For every string literal in the program, Java automatically creates a String object. Thus, a string literal can be used to initialize a String. 

For example: Both the methods create two equivalent strings: 

blog banner 1
  1. char chars[] = { ‘a’, ‘b’, ‘c’ }; 

String s1 = new String(chars); 

  1. String s2 = “abc”; 
  • A string literal can be used in any place where a String object can be used.
  • We can call methods directly on a quoted string as an object reference, as shown below. 
System.out.println("abc".length());      // 3         

The length( ) method is called on the string “abc”. And the output comes “3”. 

Concatenation of Strings

One of the important string operations in Java is concatenation. Concatenation means adding things together in a series. In Java, operators are not applied to String objects except the “+” operator, which concatenates two strings, producing a String object as a result. 

For example

String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);

Output: 

He is 9 years old.
  • String Concatenation with Other Data Types

In Java, we can concatenate strings with other data types as well. Below is an example of this case:

For example: Let’s consider this version of the previous example:

int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);

Output: 

He is 9 years old.

In this case, age is an integer, still, the output is the same. 

The reason is that the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before. 

Note: The compiler converts an operand to its string equivalent whenever the other operand of the + is an instance of a string.

Here’s a program based on the above concept whose output might surprise you. Let’s see:

Code 1Code 2
String s = “four: ” + 2 + 2; System.out.println(s);String s = “four: ” + (2 + 2);System.out.println(s);
Output- four: 22Output- four: 4
  • The reason is operator precedence. It causes the concatenation of “four” with the string equivalent of 2 as the first preference. And then concatenated with the string equivalent of 2 a second time. 
  • To complete the integer addition first, we must use parentheses, like in code 2.

String Conversion using toString( ) 

In Java, every class implements the toString( ) method of the Object class. For representing any object as a string, this method is used. 

General form: String toString( )

  • By overriding toString( ) in our program, we allow them to be fully integrated inside our code.
  • It can be used in print( ) and println( ) statements as well as in concatenation expressions. 

For example, The following program demonstrates the above method.

class Demo 
{
    double width;
    double height;
    double depth;
    Demo(double w, double h, double d) 
    {
        width = w;
        height = h;
        depth = d;
    }

    // overriding toString() method of the object class
    @Override
    public String toString() 
    {
        return "Dimensions given " + width + " by " + depth + " by " + height + ".";
    }
}

public class toStringDemo 
{
    public static void main(String args[]) 
    {
        Demo b = new Demo(10, 12, 14);
        String s = "Demo b: " + b; // concatenate Demo object

        /*
             println() method internally calls toString() method of the object class
             but here the toString() method is overridden by Demo class
        */
        System.out.println(b); // convert Demo to string
        System.out.println(s);
    }
}

Output:

Dimensions given 10.0 by 14.0 by 12.0
Demo b: Dimensions given 10.0 by 14.0 by 12.0

As we can see, Demo’s toString( ) method is automatically invoked when a Demo object

is used in a concatenation expression or a call to println( ).

Character Extraction

The String class in Java provides several ways to extract characters from a String object. Just like arrays, the string indexes begin at zero. Some of the string operations in Java to perform character extraction are given below:

  1. charAt(int index): 

This method is used to return the char value at the specified index. 

The value of the index must be nonnegative and specify a location within the string. 

For example:

char ch;
ch = "abc".charAt(1);

Result: 

assigns the value “b” to ch.
  1. getChars( )

To extract more than one character from a String object, we can use this method.

General form: 

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

Here, sourceStart specifies the starting index of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. The variable target specifies the resultant array. 

For example, The following program demonstrates the above method.

class getCharsDemo 
{
public static void main(String args[]) 
{
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}

Output:

demo
  1. getBytes( ): 

This is an alternative method to getChars( ). It stores the characters in a byte array.  

General form:

  • byte[ ] getBytes( )
  1. toCharArray( )

To convert all the characters of a String object into a character array, this method is used. It returns a character array for the given string. 

General form:

  • char[ ] toCharArray( )

String Comparison

The String class in Java includes several methods to compare strings or substrings. Some of the important string operations in Java to compare strings are given below:

  1. equals( ) and equalsIgnoreCase( )

It returns true if the strings contain the same characters in the same order and false otherwise. The comparison is case-sensitive in equals() only. The equalsIgnoreCase( ) doesn’t consider the case of a string. 

General form:

  • boolean equals(Object str)
  • boolean equalsIgnoreCase(String str)

For example, The below program demonstrates the above methods.

class equalsDemo 
{
public static void main(String args[]) 
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}

Output :

Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

Note: The equals( ) method and the “==”operator perform different functions. 

The equals( ) method compares the characters of a String object, whereas the == operator compares the references of two string objects to see whether they refer to the same instance.

A simple program to demonstrate the above difference is given below:

The variable s1 is pointing to the String “Hello”. The object pointed by s2 is constructed with the help of s1. Thus, the values inside the two String objects are the same, but they are distinct objects.

class Demo 
{
public static void main(String args[]) 
{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}

Output:

Hello equals Hello -> true
Hello == Hello -> false
  1. compareTo()

The compareTo() method of the Java String class compares the string lexicographically. It returns a positive, negative, or zero value. To perform a sorting operation on strings, the compareTo() method comes in handy. 

  • A string is less than another if it comes before in the dictionary order. 
  • A string is greater than another if it comes after in the dictionary order. 

General form:

  • int compareTo(String str)

Here, str is the string being compared with the invoking string. 

For example, Here is a sample program that sorts an array of strings. The program uses the above method to determine the sort order.

class SortStringFunc 
{
static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men","to", "come", "to", "the", "aid", "of", "their", "country" };
public static void main(String args[]) 
{
for(int j = 0; j < arr.length; j++) 
{
for(int i = j + 1; i < arr.length; i++) 
{
if(arr[i].compareTo(arr[j]) < 0) 
{
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}

Output:

Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
  1. compareToIgnoreCase():

This method is the same as compareTo( ), but it ignores the lowercase and uppercase differences of the strings while comparing.

Searching Strings

The Java String class provides two methods that allow us to search a character or substring in another string. 

  • indexOf( ): It searches the first occurrence of a character or substring.
  • lastIndexOf( ): It searches the last occurrence of a character or substring.

For example, The program below demonstrates the above methods.

class indexOfDemo 
{
public static void main(String args[]) 
{
String s = "Now is the time for all good men " + "to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " + s.indexOf('t'));
System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println("indexOf(the) = " + s.indexOf("the"));
System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
}

Output:

Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

Modifying a String

In Java, String objects are immutable, and to modify a String, we must use one of the following String methods, which will construct a new copy of the string with the modifications. 

Some of the important string operations in Java to modify strings are given below:

  1. substring( )

As the name suggests, ‘sub + string’, is a subset of a string. By subset, we mean the contiguous part of a character array or string.

For example:

illustrative_diagram

In the diagram above, CODING, NINJA, DING all are substrings of the string ‘CODINGNINJAS’.

The substring() method is used to fetch a substring from a string in Java. 

General form:

  • String substring(int startIndex)
  • String substring(int startIndex, int endIndex)

Here, startIndex specifies the beginning index, and endIndex specifies the stopping point.

The string returned contains all the characters from the beginning index, up to, but not including, the ending index i.e [startindex,endindex-1]

For example: 

In this program, “is” is replaced with “was” every time it is encountered, the substring method is used to do so.

// Substring replacement.
class StringReplace 
{
public static void main(String args[]) 
{
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
do { 
// replace all matching substrings
System.out.println(org);
i = org.indexOf(search);
if(i != -1) 
{
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}

Output :

This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.
  1. concat( )

To concatenate two strings in Java, we can use the concat( ) method apart from the “+” operator. 

General form:

  • String concat(String str)

This method creates a new object containing the invoking string with the str appended to the end. This performs the same function as the + operator. Refer to the comparison table below:

Using concat()Using “+” operator
String s1 = “one”;String s2 = s1.concat(“two”);String s1 = “one”;String s2 = s1 + “two”;

Result: s2= “onetwo”

  1. replace( )

This method is used to replace a character with some other character in a string. It has two forms. 

  • The first replaces all occurrences of one character in the invoking string with another character. 

General form:

  • String replace(char original, char replacement)

Here, the original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. 

For example:

String s = "Hello".replace('l', 'w');

Result: s= “Hewwo”

  • The second form replaces one character sequence with another. 

General form:

  • String replace(CharSequence original, CharSequence replacement)
  1. trim( )

The trim( ) method returns a copy of the invoking string from which any leading and trailing

whitespace has been removed. 

General form:

  • String trim( )

For example:

String s = "    Hello World    ".trim();

Result: s= “Hello World” 

Data Conversion Using valueOf( )

For converting different data types into strings, the valueOf() method is used. It is a static method defined in the Java String class. 

General form:

  • static String valueOf(double num) 
  • static String valueOf(long num) 
  • static String valueOf(Object ob) 
  • static String valueOf(char chars[ ])

For example:

int num=20; 
String s1=String.valueOf(num); 
s1 = s1+10; //concatenating string s1 with 10 

Result s1=2010

Changing the Case of Characters in a String

Sometimes while dealing with real-life programs and in competitive programming, we need to change lower case strings into upper case strings and vice versa. The String class in Java provides the following methods to change the case of a string:

  • The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. 
  • The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase.

Here is an example to demonstrate the the above methods:

// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase 
{
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}

Output:

Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.

Let’s see some frequently asked questions on this topic.

Frequently asked questions

Is String a keyword in Java?

String is not a keyword in Java. It is a final class in java.lang package which is used to represent the set of characters in Java.

Is String a primitive type or derived type?

String is a derived or non-primitive type.

Which string operations in java are used to compare two strings?

There are multiple string operations in java to compare two String like equals() method, equalsIgnoreCase().

Which string class method is used to find a character at a particular index?

The charAt() method of the Java String class is used to find a character at a particular index.

How do we compare two String in Java?

There are multiple ways to compare two String like equals() method, equalsIgnoreCase().

What does the substring() method do in Java?

This method is used to find a substring in a given string in Java.

Key Takeaways

In this tutorial, we learned about various methods of Java String class with the help of various programs and code snippets. String class is undoubtedly the special class in Java, and it has a rich library of methods and constructors.

To read more about Strings in Java, its memory implementation, StringBuffer, and StringBuilder class, we recommend you to visit the Strings in Java| part-1 of this tutorial.

Apart from the above String class methods, there are several other Java regular expressions methods. To learn more about Java regex and the methods, check out this amazing blog: Tutorial On Java Regular Expressions.

Java is one of the most popular languages. It finds wide applications in Android development and server development. Learning Java in-depth will get you a lucrative placement.

To learn more about Java, take a look at various courses offered by Coding Ninjas. To know more about the best books of Java, check out our blog on 21 Best Java Programming Books for Beginners & Experts.

Happy Learning!