Home » Java » String

Category Archives: String

String

What is a String?

In java and unlike C++, the string data type is now an object type. Notice that the class name is starts with an uppercase. If you mess this up, Java will not know what you are referring to.

By it’s conception, a string is anything and everything grouped together between 2 double quotes. For example, “Hello world” is one string while “sdad anesd ccn ” is another.

Using Strings

Strings can be manipulated in numerous ways. The first is with some member functions of the string class. Let’s see an example first before we continue.

Example 1:
Different String functions

public class StringExample{

   public static void main(String args[]){

      String word;

      //assign the string to the variable:
      word = "Alexander";

      //preform some actions on the string:

      //1. retrieve the length by calling the
      //length method:
      int length = word.length();
      System.out.println("Length: " + length);

      //2. use the case functions:
      System.out.println("toUpperCase: " + word.toUpperCase());
      System.out.println("toLowerCase: " + word.toLowerCase());

      //3. use the trim function to eliminate leading
      //or trailing white spaces:
      word = word.trim();
      System.out.println("trim: " + word);

      //4. check for a certain character using indexOf()
      System.out.println("indexOf('s'): " + word.indexOf('s'));

      //5. print out the beginning character using charAt()
      System.out.println("first character: " + word.charAt(0));

      //6. make the string shorter
      word = word.substring(0, 4);
      System.out.println("shorter string: " + word);
   }
}

When you run the above program, here is the output that you will get:

Length: 9
toUpperCase: ALEXANDER
toLowerCase: alexander
trim: Alexander
indexOf('s'): -1
first character: A
shorter string: Alex

A lot certainly has happened in this program. Let’s observe some of the most used functions in the String class.

int length()

The length function will simply return the length of a string as an integer.

String toUpperCase()

The toUpperCase function will return the uppercase version of a string. Say you have a string “Welcome”. This function will return “WELCOME”.

String toLowerCase()

The toLowerCase function will return the lowercase version of a string. Say you have a string “Welcome TO Earth”. This function will return “welcome to earth”.

String trim()

The trim function will return the string without leading or trailing white space characters. Say that a string was ” hello “. There are 4 spaces in the front and 3 spaces at the end. The trim function would make this “hello”.

int indexOf(int ch)
int indexOf(int ch, int begin)
int indexOf(String ch)
int indexOf(String ch, int begin)

Notice that there are 4 different functions listed here. All of them preform the same overall action of returning an integer, which represents the FIRST OCCURRANCE of a character or String contained in that string. So say that we have the string “Hello” and we say indexOf(‘l’). This function will use the first function above and return 2. Notice it doesn’t reutrn 3.

We can also say, using the same string “Hello”, indexOf(“He”). It will return 0 as the string that you are searching for starts at index 0.

By default, if a string or character is not found in the string, the any of the functions will return -1.

char charAt(int index)

This function will look for a character at a specific index. It will return that character if it is found. Say we have the string “Hello” and we say charAt(4). It will return ‘o’ as that character is at index 4.

String substring(int begin)
String substring(int begin, int end)

Either of these functions will shorten a string when called. If no ending index is specified, it will return the rest of that string. Say we have the string “Hello there” and we say substring(4), the function will return “o there”. Let’s use substring(2,5), the function will return “llo”.

String Equalities

With Java, there are numerous methods they provide that check for two strings being equal. To show this, here is a small program that will check for a certain string as a command line argument.

Example 2:
String equalities

public class StringExample2{

   private static String word = null;
   private static String keyword = "HELLO";

   public static void main(String args[]){
	//standard error check:
	if(args.length < 1){
		System.out.println("Argument requires one word.");
		System.exit(1);
	}

	//retreive the sentence:
	word = args[0];

	//check for the keyword using different equals methods:
	if(word.equals(keyword)){
		System.out.println("equals true: "
                   + word);
	}
	if(word.equalsIgnoreCase(keyword)){
		System.out.println("ignoreCase true: "
                   + word);
	}

	//check for the keyword using different compareTo methods:
	if(word.compareTo(keyword) != -1){
		System.out.println("found using compareTo: " +
		   word.compareTo(keyword));
	}
	if(word.compareToIgnoreCase(keyword) != -1){
		System.out.println("found using compareToIgnoreCase: " +
		   word.compareToIgnoreCase(keyword));
	}
   }
}

This program will accept as a command-line argument, one word which we will call our “keyword”. It will then preform 4 checks using different member functions of the String class. Here is the output when you run the program with the argument “hello” SPELT EXACTLY AS IS (all lowercase).

ignoreCase true: hello
found using compareTo: 32
found using compareToIgnoreCase: 0

Let’s discover why. Here are the descriptions of the member functions:

boolean equals(String another)

The equals() function will take another String as its parameter and check if it is EXACTLY like the initial String. The initial string is what you called the member function from. So in the above program, the initial string is the variable word.

This method reutrns a boolean value. If true, the string parameter is an exact copy of the initial string. If false, the argument is not a copy as something differs in the string.

As noted, the above program returns false when the equals() method is used because of the case difference.

boolean equalsIgnoreCase(String another)

This method is similar to the regular equals() method with the exception of this method not taking into account the case (either upper or lower) of BOTH strings.

So in the program above, this function returns true because of the ignoring of the case. If the keyword above was “HelloA”, this function will return false because they are still different strings.

int compareTo(String another)

This method compares two Strings lexicographically, meaning it will compare the strings in alphabetical order character by character. The method will return a negative number of the differences between the strings, a 0 if they are equal or a positive number representing how much they differ. The negative return means that string comes before the other lexicographically while the positive return means it comes after the other.

So in the above program, the function returns a 32 because of the following reason; when they compare the first characters of both string (initial string = ‘h’ and argument string = ‘H’), they differ by an ASCII value of 32. The function returns 32 to the user. ASCII values are computer codes for different letters and numbers.

int compareToIgnoreCase(String another)

This method preforms the same actions of the regualr compareTo() method but this one will ignore any case difference. The method returns the same values as the compareTo().