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");


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:

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:


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 of two strings. 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 a program where instead of using equals you could have used == 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. Also official way of comparing Strings is only through equals method.


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 = {90,100,88.9,65.3,100};

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 = { 

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.

results matching ""

    No results matching ""