Monday, October 12, 2015

java - How to initialize string array

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get widget reference from XML layout
        TextView tv = (TextView) findViewById(R.id.tv);

        // Declare a new String array
        String[] colors;

        // Initialize the colors String array
        // Also specify the initial length of colors array
        // Allocate the memory storage for the array elements
        colors = new String[3];

        // Put values to colors String array
        colors[0] ="Red";
        colors[1] ="Green";
        colors[2] ="Blue";

        tv.setText("Colors : ");
        // Loop through the colors String array
        for(int i=0;i<colors.length;i++){
            tv.setText(tv.getText() + colors[i] + ", ");
        }

        // Another way to initializing a new String array
        // Also allocate the correct memory storage for the array elements
        String[] redColors = new String[4];
        redColors[0] = "Red";
        redColors[1] = "Crimson";
        redColors[2] = "IndianRed";
        redColors[3] = "DarkRed";

        tv.setText(tv.getText() + "\n\nRed colors : ");
        // Loop through the red colors String array
        for(int i=0;i<redColors.length;i++){
            tv.setText(tv.getText() + redColors[i] + ", ");
        }

        // Another way to initialize a new String array
        // This also add elements at the time of array initialization
        String[] blueColors = new String[]{"Blue","AliceBlue","CornflowerBlue"};

        tv.setText(tv.getText() + "\nBlue colors : ");
        // Loop through the blue colors String array
        for(int i=0;i<blueColors.length;i++){
            tv.setText(tv.getText() + blueColors[i] + ", ");
        }

        // Initialize a new empty String array
        String[] pinkColors = new String[]{};

        tv.setText(tv.getText() + "\n\nPink colors : ");
        // Loop through the pink colors String array
        for(int i=0;i<pinkColors.length;i++){
            tv.setText(tv.getText() + pinkColors[i] + ", ");
        }

        // Reinitialize the same String array with values
        // It will overwrite the String array
        pinkColors = new String[]{"Pink","HotPink","DeepPink","LightPink"};

        tv.setText(tv.getText() + "\nPink colors : ");
        // Loop through the pink colors String array
        for(int i=0;i<pinkColors.length;i++){
            tv.setText(tv.getText() + pinkColors[i] + ", ");
        }
    }
}
More android examples