String Class

Strings are used frequently in Java programming. You have already used Strings in the earlier lessons. In this lesson you will understand more on Strings. A String is a sequence of characters. In the Java programming language, Strings are objects and not primitives.

Creating Strings

The most common way of creating a String is:

String hello = "Hello world!";

But this expression is similar to assigning literal values to primitives. String is one of those special Object types which can be assigned values like a primitive.

Otherwise most objects are created using the new keyword. Since String is an Object, you can also create a String using the new keyword and a constructor. You will learn about the new keyword and constructors in the subsequent chapters. Here is an example of constructing a String using the new keyword:

public class StringDemo {
   public static void main(String args[]) {
      String helloString = new String("hello");  
      System.out.println( helloString );
   }
}

Note: The String class is immutable, which means that once created, a String object cannot be changed. If there is a need to change the value of a String object after it is constructed, you should use StringBuilder class instead of String class.

Here is an example of using StringBuilder

public class StringBuilderDemo {
   public static void main(String args[]) {
      StringBuilder myString = new StringBuilder("My String which can change. ");
      myString.append("I can append another sentence");
      System.out.println(myString);
   }
}

Output:

My String which can change. I can append another sentence

String Length

Since String is of an Object type, you can apply many methods on a String object. Here is the JavaDoc for String: https://docs.oracle.com/javase/9/docs/api/java/lang/String.html

To find the length of a String object we invoke length() method.

public class StringDemo {

   public static void main(String args[]) {
      String myString = "I am learning Java";
      int len = myString.length();
      System.out.println( "String Length is : " + len );
   }
}

What length did you get? and check if the answer is correct by counting the number of characters.

Concatenating Strings

The String class includes a method for concatenating two strings:

string1.concat(string2);

Remember however that string1 object was not concatenated. Instead a new String object is created by joining string1 and string2 and that String is returned.

You can also use the concat() method with string literals, as in:

"My cat’s name is ".concat("Kitty");

However strings are more commonly concatenated with the + operator, as in:

"Hello," + " world" + "!"

which results in: "Hello, world!"

Let us look at the following example:

public class StringDemo {

   public static void main(String args[]) {
      String string1 = "learning ";
      System.out.println("I am  " + string1 + " Java");
   }
}

This would produce the following result:

I am learning Java

To use equals or == to compare Strings?

When it comes to checking equality of two strings, you should use the equals method and not the relational operator for equality;

==

For primitives == is the only way to compare the equality. This may work for you with Strings also in certain compiler versions. However since String is an object, you should use equals method and that is the only right way of comparing Strings. Here is an example:


class StringComparison {

    public static void main(String[] args) {
        String firstString = "java";
        String secondString = "java";
        if (firstString.equals(secondString)) {
            System.out.println("Both firstString and secondString contain the same value");
        }
    }
}

Note: You may have completed a program using == instead of using equals and everything might have worked just fine. However this will not work with all versions of Java and hence your program will fail when it is run on a Java version where == is not supported for Strings. Official way of comparing Strings is only through equals method so you should stick to this method always.

Arrays

An array is a data structure, which stores a sequential collection of elements of the same data type.

Array of strings

Supposing you want to keep the names of your favorite fruits, then you could construct a String array as follows:

String[] favoriteFruits = {"mango", "banana", "apple", "grapes"}

How to get a specific element of your array? Array positions starts with 0 index number. In our example, you have an array of 4 elements with the 0th index position having "mango" and the 3rd index position having "grapes". Total length of the array is 4.

Length of an array is obtained by invoking length method on the array as shown in the example below. Notice how the last element of the array is derived by finding the length and subtracting 1.

public class ArrayExample {
    public static void main(String[] args) {
        String[] favoriteFruits = {"mango", "banana", "apple", "grapes"};
        System.out.println("My first favorite fruit is " + favoriteFruits[0]);
        System.out.println("My last favorite fruit is " + favoriteFruits[favoriteFruits.length -1]);
    }
}

Index out of bounds Exception!

If you try to access an element with an illegal index number then you get ArrayIndexOutOfBoundsException. All index numbers which are either negative or greater than or equal to the size of the array are illegal.

The above array contains data of type String and nothing else. An array can hold elements which are all of the same type only.

The above array can also be represented as follows:

String favoriteFruits[] = {"mango", "banana", "apple", "grapes"};

Notice where the left and right brackets are -- It is after the variable name and not after the data type. However this way of representing array is not a preferred way.

Array of numbers

Supposing you want to create an array to keep the marks you scored in every subject. Then you would declare an array of float to keep the values:

float[] marks = {90f,100f,88.9f,65.3f,100f};

2 dimensional arrays

Suppose you want to keep the scores along with the semester in which you scored, then you can create an array of arrays which is basically a 2-dimensional array and here is an example:

float[][] semesterMarks = { 
      {90f,100f,88.9f,65.3f,100f},
      {100f,90f,87.8f,88f,99f},
      {98.9f,98.7f,99.3f,100f}
     };

The above structure has marks for three semesters as you have three groups of marks. To get individual values of this 2 dimensional array, you first access the first dimension specifying the semester number and then the second dimension which is the marks. Positions always start with 0 be it one or multi dimensions.

In the above example why is there an 'f' at the end of every marks value?

It is not required. We can remove that It is there because semesterMarks is a float type. If 'f'is not given then the default value would be a 'double' and compiler will give a warning of precision loss as 'double' holds a bigger value.

If you want to access the second marks in first semester, how would you code?

semesterMarks[0][1] semesterMarks[1][2] Remember, the positions always start with 0, so the first semester is 0th position and the second marks is at 1st position

Creating Arrays using new operator

There is another way of creating an array and that is by using the new keyword:

dataType[] arrayRefVar = new dataType[arraySize];

The above statement does two things: It creates an array using new dataType[arraySize]; It assigns the reference of the newly created array to the variable arrayRefVar.

Example: Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList:

double[] myList = new double[10];

By default, the value in all the 10 positions is 0.

instanceof keyword

In case of objects, you can find out which type of object it is using the instanceof operator.

The instanceof keyword compares the given object instance with given type and returns either true or false based on if it is indeed instance of the given type or not.

Here is an example


public class InstanceOfTest {
  public static void main(String[] args) {
    String myString = "abc";
    System.out.println(myString instanceof String); // returns true
  }
}

results matching ""

    No results matching ""