Java Strings Basics

In this post, you will learn to:

  • Describe strings.
  • Describe the various methods of String class.
  • Describe a String array and its use.
  • Describe command line arguments in Java and their uses.

Consider an application, that maintains employee information, such as Employee ID, name, type of work and salary details. With the help of the provided information, the possible data types for the employee information are:

The Employee ID and salary details can be represented as a numeric value. Employee name and the type of work are represented as text data.

So, what does text data actually mean? Basically, it is a collection of individual characters that form meaningful words. For example, the name of an employee is a sequential collection of characters that form some meaningful text and so is the case with the type of work. This type of text data can be stored using strings in Java. Java provides a class called String to represent text data.

The figure below shows the allocation of memory for storing strings.

Create a ‘String’ Object

The String class is used to represent character strings. Strings are constant, which means their values cannot be changed after they are created. In Java, strings are objects. An instance of a String class can be created with the new keyword. The following code creates a new object of class String, and assigns it to the reference variable, str. Then, it assigns a value to the string variable.

Code Snippet:

String str = new String();
str = "Hello World";

The following code snippet demonstrates the usage of String objects.

Code Snippet:

String empName = new String();   //string object, empName
String typeOfWork = new String();   //string object, //typeOfWork
 
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee name: ");
empName = input.nextLine();   //accepts employee name
System.out.println("Enter type of work: ");
typeOfWork = input.nextLine();    //accepts type of work
 
// Displaying details
System.out.println("Employee Name: "+empName);
System.out.println("Type of Work: "+typeOfWork);

The code accepts values into two string variables, empName and typeOfWork and prints them. The nextLine() method of the Scanner class can be used to input string values.

Output:

Enter Employee name: David Blake
Enter type of work: Programming
Employee Name: David Blake
Type of Work: Programming

Methods

The class String includes various methods to compare strings, find length of strings, remove white space characters of a string, and much more.

length()

The length() method can be used to find the length of a string.

Syntax:

int length();

The following code demonstrates the length() method of String class.

Code Snippet:

String empName = new String(); //string object, empName
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee name: ");
empName = input.nextLine(); //accepts employee name 
//counts the number of characters including whitespaces and prints total
System.out.printf("Length of the string = %d",empName.length()); 

//Displaying details
System.out.println("Employee Name: "+empName);

Output:

Enter Employee name: David Blake
Length of the string = 11
Employee Name: David Blake.

charAt()

The charAt() method can be used to get the character value at the specified index.

Syntax:

char charAt(int index);

The index ranges from zero to length() – 1. The index of the first character starts at zero. The following code demonstrates the charAt() method of String class.

Code Snippet:

String empName = new String();   //string object, empName
empName = "David Blake";
System.out.println(empName.charAt(9));   //prints k

The code snippet prints the character at index 9, which is ‘k’.

concat()

The concat() method can be used to concatenate the specified string to the end of a string.

Syntax:

String concat(String str)

If the length of the string is zero, the String object is returned, otherwise a new String object is returned. The following code demonstrates the concat() method of String class.

Code Snippet:

String empName = new String(); //string object, empName
empName = "David Blake";
 
System.out.println(empName.concat(" Martin")); //joins the two strings

Output:

David Blake Martin.

compareTo()

The compareTo() method compares two particular objects of String class and returns an integer as the result. The comparison is based on the Unicode value of each character in the strings.

Syntax:

int compareTo(Object anotherString)

The result is a negative integer if the argument string anotherString is lexicographically greater than the original string. The result is a positive integer, if the argument string anotherString is lexicographically lesser than the original string. The result is zero, if the strings are equal. The following code demonstrates the compareTo() method of String class.

Code Snippet:

String empName = new String(); //string object, empName
empName = "David Blake";
// returns a positive integer
System.out.println(empName.compareTo("Angelina Jack")); 
//returns 0
System.out.println(empName.compareTo("David Blake")); 
// returns a negative integer
System.out.println(empName.compareTo("Elton John")); 

Output:

3
0
-1

indexOf()

This method returns the index of the first occurrence of the specified character or string within a string. If the character or string is not found, the method returns -1.

Syntax:

int indexOf(int ch)
int indexOf(String str)
int indexOf(int ch, int fromIndex)
int indexOf(String str, int fromIndex)

where,
ch is the character whose index will be returned.
str is the string whose index will be returned.
fromIndex is the index from where the indexOf method will start searching for the character ch or string str.

A value zero is returned if str is empty, but not null. The following code demonstrates the various indexOf() methods of String class.

Code Snippet:

String empName = new String(); //string object, empName
empName = "David Blake";
 
/*
 * Character 'D' at index 0
 * Character 'a' at index 1
 * Character 'v' at index 2
 * Character 'i' at index 3
 * Character 'd' at index 4
 * Character ' ' at index 5
 * Character 'B' at index 6
 * Character 'l' at index 7
 * Character 'a' at index 8
 * Character 'k' at index 9
 * Character 'e' at index 10
 */ 
//search starts at position 0
 System.out.println(empName.indexOf('i')); //returns 3
 
//search starts at position 3
System.out.println(empName.indexOf('a',3)); //returns 8

//search starts at position 0
System.out.println(empName.indexOf('a',0)); //returns 1

//search starts at position 0
System.out.println(empName.indexOf("lake")); //returns 7

//search starts at position 0
System.out.println(empName.indexOf("lake",0)); //returns 7
 
//search starts at position 8
System.out.println(empName.indexOf("lake",8)); //returns -1

The String class also contains methods to extract substrings, remove white space characters of a string, and much more.

lastIndexOf()

The lastIndexOf() method is used to return the index of the last occurrence of a specified character or string within a string. The specified character or string is searched backwards that is the search begins from the last character.

Syntax:

int lastIndexOf(int ch)
int lastIndexOf(String str)
int lastIndexOf(int ch, int fromIndex)
int lastIndexOf(String str, int fromIndex)

where,
ch is the character whose index will be returned.
str is the string whose index will be returned.
fromIndex is the index from where the lastIndexOf() method will start searching for the character ch or string str.

The following code demonstrates the lastIndexOf() methods of String class.

Code Snippet:

String empName = new String(); //string object, empName
empName = "Java is the most elegant and the cleanest object-oriented language available";
 
//search starts from the end of the string
System.out.println(empName.lastIndexOf('a')); //returns 72
 
//search starts at position 5 to zero
System.out.println(empName.lastIndexOf('a',5)); //returns 3
 
//search starts at position 30 to zero
System.out.println(empName.lastIndexOf('l',30));//returns 18
 
//search starts at position 0
System.out.println(empName.lastIndexOf("the")); //returns 29
 
//search starts at position 10 to zero
System.out.println(empName.lastIndexOf("the",10));//returns 8

//search starts at position 7 to zero
System.out.println(empName.lastIndexOf("the",7));//returns -1 

replace()

The replace() method replaces all the occurrences of a specified character in the current string with a given new character. If the specified character does not exist, the reference of original String is returned.

Syntax:

String replace(char oldChar, char newChar);

The following code demonstrates the replace() method of String class.

Code Snippet:

String empName = new String(); //string object, empName
empName = "David Blake";

//replace all 'a' with 'e'
System.out.println(empName.replace('a','e')); 

Output:

Devid Bleke

substring()

The substring() method can be used to retrieve a part of a string, that is, substring from the given string.

Syntax:

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

where,
startIndex is the index from where the substring begins.
endIndex is the index where the substring ends.

The following code demonstrates the substring() method of String class.

Code Snippet:

String empName = new String(); //string object, empName
empName = "David Blake";

System.out.println(empName.substring(2)); 
System.out.println(empName.substring(6,10));

Output:

vid Blake
Blak

toString()

The toString() method can be used to return a String object.

Syntax:

String toString()

The following code demonstrates the toString() method of String class.

Code Snippet:

String empName = new String();   //string object, empName
empName = "David Blake";
String newEmpName = empName.toString();
System.out.println(newEmpName.toString());

The code stores the value of empName string variable into another variable copyEmpName. Now, both the variables have the same value.

Output:

David Blake

trim()

The trim() method returns a new string by trimming the leading and trailing whitespace from the current string.

Syntax:

String trim();

The following code demonstrates the trim() method of String class.

Code Snippet:

String empName = new String(); //string object, empName
empName = "\n\t\tDavid Blake.\t\n";
System.out.println(empName);
String newEmpName = empName.trim();   //trims the whitespaces from the front and back of the string
System.out.println(newEmpName);

The code snippet creates a new String variable, newEmpName that will store the same value as empName, but without whitespace characters.

Output:

      David Blake.   

David Blake.

codePointAt()

The codePointAt() method returns the character (Unicode code point) at the specified index.The key concept in Unicode is the code point. Unicode code points are just numbers. For example, in Unicode, the code point 65 has the typographic representation ‘A’.

Syntax:

int codePointAt(int index);

The following code demonstrates the codePointAt() method of String class.

Code Snippet:

String str = "Aptech Global Learning Solutions";
System.out.println(str.codePointAt(0));

Output:

65

codePointBefore()

The codePointBefore() method returns the character (Unicode code point) before the specified index.

Syntax:

int codePointBefore(int index);

The following code demonstrates the codePointBefore() method of String class.

Code Snippet:

String str = "Aptech Global Learning Solutions";
System.out.println(str.codePointBefore(1));

Output:

65

codePointCount()

The codePointCount() method returns the number of Unicode code points between two indices in the string.

Syntax:

int codePointCount(int start, int end);

The following code demonstrates the codePointCount() method of String class.

Code Snippet:

String str = "Aptech Global Learning Solutions";
System.out.println(str.codePointCount(0, 5));

Output:

5

startsWith()

The startsWith() method returns a boolean value to test whether the string starts with a specified prefix.

Syntax:

boolean startsWith(String prefix);

The following code demonstrates the startsWith() method of String class.

Code Snippet:

String str = "Aptech Global Learning Solutions";
System.out.println(str.startsWith("Apt"));

Output:

true

endsWith()

The endsWith() method returns a boolean value to test whether the string ends with a specified suffix.

Syntax:

boolean endsWith(String suffix);

The following code demonstrates the endsWith() method of String class.

Code Snippet:

String str = "The Geek Diary";
System.out.println(str.endsWith("ary"));

Output:

true

toUpperCase()

The toUpperCase() method converts the characters in the string to upper case.

Syntax:

String toUpperCase();

The following code demonstrates the toUpperCase() method of String class.

Code Snippet:

String str = "The Geek Diary";
System.out.println(str.toUpperCase());

Output:

THE GEEK DIARY

toLowerCase()

The toLowerCase() method converts the characters in the string to lower case.

Syntax:

String toLowerCase();

The following code demonstrates the toLowerCase() method of String class.

Code Snippet:

String str = "The Geek Diary";
System.out.println(str.toLowerCase());

Output:

the geek diary

valueOf()

The valueOf() method returns the string representation of the specified argument. The argument can have any one of the values: boolean, char, float, double, int, long, char array, or object.

Syntax:

static String valueOf(char[] data);
static String valueOf(char[] data, int offset, int count);

The following code demonstrates the valueOf() method of String class.

Code Snippet:

char[] array = {'T','h','e','K','i','d',' ','G','l','o','b','a','l'};
System.out.println(String.valueOf(array));
System.out.println(String.valueOf(array,7, 6));

Output:

The Kid
Global

toCharArray()

The toCharArray() method copies the content of the string to a new character array.

Syntax:

char[] toCharArray();

The following code demonstrates the toCharArray() method of String class.

Code Snippet:

char[] array;
String str = "The Geek Diary Blog";
array = str.toCharArray();
System.out.println(String.valueOf(array));

Output:

The Geek Diary Blog

equalsIgnoreCase()

The equalsIgnoreCase() method compares two strings, ignoring case, and returns a boolean value. If the strings are equal the method returns a true value, otherwise false.

Syntax:

boolean equalsIgnoreCase(String anotherString);

The following code demonstrates the equalsIgnoreCase() method of String class.

Code Snippet:

String str = "The Geek Diary Blog";
String anotherString = "THE GEEK DIARY BLOG";
System.out.println(str.equalsIgnoreCase(anotherString));

Output:

true

String Arrays

Sometimes, while programming, there is a need to store a collection of strings. You can create an array of string references in Java to achieve this. The following code declares and instantiates an array of references to 10 String objects.

Code Snippet:

String[] studentNames = new String[10];
studentNames[0] = new String("David Blake");
studentNames[1] = new String("Mike Jordan");

The statement, String[] studentNames = new String[10]; in the code simply sets aside memory for storage of 10 references to strings. No memory has been set aside to store the characters hat make up the individual strings. You must allocate the memory for the actual string objects separately at each index of an array, studentNames[0] = new String(“David Blake”);

Alternatively, you can declare, instantiate, and initialize an array using a single statement as follows:

String[] studentNames={"David Blake","John Pearson" };

Use a loop to initialize

Individual components of a string array are referenced by the array name and by an integer which represents their position in the array. It is a tedious task to initialize each component individually for even a medium sized string array. It is often helpful to use a looping construct to initialize a string array.

The following code demonstrates the use of loop construct to initialize a string array.

Code Snippet:

//string array of 5 references
String[] studentNames = new String[5]; 
int count; 
Scanner input = new Scanner(System.in);
//for loop to iterate through the string array
for (count = 0;count <studentNames.length;count++){
   System.out.println("\nEnter student name: ");
   //creating the actual string variable
   studentNames[count] = new String();
   //accepting values
   studentNames[count] = input.nextLine();
 }

Here, to store the names of five students, a String array studentNames is declared. A for loop is used to allocate memory to each individual array and also to accept values into the array.

Display Arrays

To print the contents of an array, a loop construct is preferred. The ‘%s’ format specifier along with the printf() method in Java 5.0 can be used to get a formatted output.

The following code creates a String array and displays its values using the printf() method.

Code Snippet:

//string array of 5 references
String[] studentNames = {
                         "David Blake",
                         "John Pearson",
                         "Mike Johnson",
                         "Bill Moore",
                         "Maria Jones" };
int count;
//display the string objects

for (count = 0;count <studentNames.length;count++){
   System.out.printf("\nStudent name: %s", studentNames[count]);
}

The array studentNames is declared and initialized with five string values. The strings are displayed in a for loop by using the printf() method.

Output:

Student name: David Blake 
Student name: John Pearson 
Student name: Mike Johnson 
Student name: Bill Moore 
Student name: Maria Jones

String Arguments

A Java application can accept any number of arguments from the operating system command line. The basic purpose of command line arguments is to specify the configuration information for the application. The main() method is the entry point of a Java program, where you create objects and invoke other methods. There can be only one entry point in a Java program.

The main() method takes an argument, which is of the following form:

public static void main(String[] args){
...
}   //end of main method

The parameter of the main() method is a String array that represents the command-line arguments.

Passing Command line arguments

The command line arguments are entered while invoking the application. For example, you have a Java application, called Games.class, to execute certain statements based on the command line values. To execute the statements based on Football or Hockey, you would run it like this:

java Games Football Hockey

When the application is invoked, the values will be passed to the main() method as an array of strings. Each string in the array contains one of the command-line arguments. The first element,that is, args[0] is the first argument passed from the command line, not the name of the class. In this example, args[0] is Football not Games.class.

You can check for the existence of the arguments by testing the length property.

if(args.length==0) {
   System.out.println("You have not entered any arguments");
 }

The following code prints each of the command line arguments using a for-each loop.

Code Snippet:

public class Games {
   public Games() {
   }
 
   public static void main(String[] args) {
      // command line arguments
      if(args.length==0){
         System.out.println("You have not entered any arguments");
      } //end of if
      else {
         for(String str: args){
            System.out.println(str);
            } //end of for loop
         } //end of else
      } //end of main method

   } //end of class Games

You run the application, Games, in the following manner:

java Games Football Hockey Volleyball Badminton

The output of the program will be:

Football
Hockey
Volleyball
Badminton

The application displays each word – Football Hockey Volleyball Badminton – on a line by itself. The whitespace character separates the command-line arguments. If you want to join all the arguments as a single argument, you could join them with double quotes. For that, you can run the application as follows:

java Games "Football Hockey Volleyball Badminton"

The output of the program will be:

Football Hockey Volleyball Badminton
Related Post