Java

TOPIC 49 – BASICS OF STRINGS

 

 

LESSON NOTE

 

 

STRINGS ARE NOT VARIABLES


The String class allows us to create String objects.  We’ve actually been using this class all along without really considering this.

There have been a few differences between String objects and other variable types though:

 

  • Variables such as int or double start with a lowercase letter.  The class String starts with an uppercase letter.

  • When comparing two types of variables, we use the “==” operator.  However when comparing to String objects, we’ve had to use the .equals method.

CREATING A STRING OBJECT

 

We can create a String by doing the following:

 

          String s = "hello";

 

`While the above is really a short form it is the most commonly used.

 

A more complete way of creating a String would be:

 

          String s = new String("hello");

 

While Strings are objects, we often incorrectly use the word variable to refer to them.

EMPTY STRING

 

It is often useful to have a String that contains no characters. This is called an empty String and is simply expressed as two double quotes "".

 

Example

 

String str = "";          //Creating an empty String.


STRING CONCATENATION

 

String concatenation is the action of “sticking” two Strings together. In Java, we use the + symbol to do this.

 

Example 1 – Store two different words in two different names and then combine them using the + symbol. Place a space between the two words.

String first = "Patrick";

String last = "Campeau";

String full = first + " " + last;


Example 2 – Create a greeting application.

 

System.out.println("Enter your name");

String name = DummiesIO.getString();

System.out.println("Hello " + name);

 

INDEX OF EACH CHARACTER

 

Each character in a String has an index. The first character has index 0, the second has index 1, and so on…

 

INSTANCE METHODS (OF STRING CLASS)

 

There are many built-in methods that are available to us for manipulating Strings. You can see a full listing in the API Specification on the Java website.

These methods are called instance methods. When we call instance methods, we must provide the object on which we are calling the method.

We will look at some of the more commonly used String methods:

 

1 – LENGTH

 

  • This method returns the length of the String on which it is called. Its prototype is:

 

int length()

 

  • Here is a simple example:


String s = "abc";

int length = s.length();

 

          The length variable gets the value 3.


  • The length of an empty String is 0.


2 - SUBSTRING

 

  • We can get a part of a String by using the substring method. This method has two parameters. Its prototype is:

String substring(int startAt, int endBefore)

 

  • Here is a simple example that will give the String s2 the first 4 letters of the String s1:

 

String s1 = "abcdefghijklmnopqrstuvxyz";

String s2 = s1.substring(0,4);

  • Here is a simple example that will give the String initial the first letter of the String name:

 

String name = "Patrick";

String initial = name.substring(0,1);

 

  • If the range you are requesting for your substring exceeds the range in the original String, you will get a run-time error.

 

3 – CHANGING THE CASE

 

  • We can get the upper case version of a String by using the method toUpperCase().


  • We can get the lower case version of a String by using the method toLowerCase().

 

  • Here is a simple example that gives the String s2 the lower case version of s1.

 

String s1 = "Hello";

String s2 = s1.toLowerCase(); //s1 will get "hello"

 

4 – COMPARING TWO STRINGS

 

  • Two Strings should not be compared for equality using the == operator. This works for variables but not for objects. (Note that this seems to work in most cases but should not be counted on.)

  • We can check if two Strings are equal by using the equals method. Its prototype is:

 

boolean equals(String s)


  • Here is an example that checks if two entered words are the same:

 

System.out.println(“Enter a word”);

String s1 = DummiesIO.getString();

System.out.println(“Enter another word”);

String s2 = DummiesIO.getString();

 

if (s1.equals(s2))

{

   System.out.println(“Same”);

}

else

{

   System.out.println(“Different”);

}

 

MULTIPLE METHOD CALLS USING “.”

 

  • We can place a sequence of method calls together. To do this, all method calls (except the last one) have to return an object on which we can call a method. Sequences of method calls are evaluated from the left to the right.

 

  • Example 1 - Get the first letter of the String name and make sure it is in upper case.

 

String name = "patrick";

String initial = name.substring(0,1).toUpperCase();

 

In the above code, the substring method is called. It returns a new String with a value of “p”. Then, the toUpperCase method is called on that new String returning “P”. The above code is equivalent to the following:

 

String name = "patrick";

String first = name.substring(0,1);

String initial = first.toUpperCase();

 

  • Example 2 – Compare the first letter of two Strings s1 and s2 (case sensitive).

 

          if (s1.substring(0,1).equals(s2.substring(0,1)))

          {

              System.out.println("Start with same");

}

 

  • Example 3 – Compare the first letter of two Strings s1 and s2 (not case sensitive).

 

                    if (s1.substring(0,1).toUpperCase().equals(s2.substring(0,1).toUpperCase()))

            {

                System.out.println("Start with same character");

}