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

Just like other objects, you can create a String object by 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 out of char array. You will learn about arrays in the next section.

public class StringDemo{
   public static void main(String args[]){
      char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
      String helloString = new String(helloArray);  
      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 necessity to make a lot of modifications to a String object, then 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

There are many methods you can invoke on a String object. 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:


This returns a new string that is string1 with string2 added to it at the end. 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


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

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};

However in this representation, you are unable to specify the marks you scored against a specific subject. A Map structure could be used to keep the subject name along with the score. You will learn about Map structure in the subsequent lessons.

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 double and compiler will give a warning of precision loss as double is 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 ""