More About Java Data Type and Operators

More About Java Data Type and Operators

<strong>Originally published by </strong><a href="https://itnext.io/@dammnn" target="_blank">Dammnn</a><strong> </strong><em>at&nbsp;</em><a href="https://itnext.io/more-about-java-data-type-and-operators-ed8f649a2491" target="_blank"><strong>I</strong>tnext</a>

Originally published by Dammnn at Itnext

This article returns to the subject of Java’s data type and operators. It discuss arrays, the String type, the bitwise operator, and the ? ternary operator. It also covers Java’s for-each style for loop. Along the way, command line arguments are described!

Arrays

An array is a collection of variables of the same type, referred to by a common name. In Java, arrays can have one or more dimensions, although the one-dimensional array is the most common. Arrays are used for a variety of purposes because they offer a convenient means of grouping together related variables. For example, you might use an array to hold a record of the daily high temperature for a month, a list of stock price average, or a list of your collection of programming books.


The principal advantage of an array is that it organizes data in such a way that it can be easily manipulated. For example, if you have an array containing the incomes for a selected group of households, it is easy to compute the average income by cycling through the array. Also, arrays organize data in such a way that it can be easily sorted.

Although arrays in Java can be used just like arrays in other programming languages, they have one special attribute: they are implemented as objects. This fact is one reason that a discussion of arrays was deferred until objects have been introduced. By implementing arrays as objects, several important advantages are gained, not the least of which is that unused array can be garbage collected.

One-Dimensional Arrays

A one-dimensional array is a list of related variables. Such lists are common in programming. For example, you might use a one-dimensional array to store the account numbers of the active users on a network. Another array might be used to store the current averages for a baseball team.


To declare a one-dimensional array, you can use this general form:

type array-name[] = new type[size];

Here, type declares the element type of the array. The element type determines the data type of each element contained in the array. The number of elements that the array will hold is determined by size. Since arrays are implemented as objects, the creation of an array is a two-step process. First, you declare an array reference variable. Second, you allocate memory for the array, assigning a reference to that memory to the array variable. Thus, arrays in Java are dynamically allocated using the new operator.

Here is an example. The following creates an int array of 10 elements and links it to an array reference variable named sample:

int sample [];
sample = new int[10];

In this case, when the sample is first created, it refers to no physical object. It is only after the second statement executes that sample is linked with an array.

An individual element within an array is accessed by use of an index. An index describes the position of an element within an array. In Java, all arrays have zeros as the index of their first element. Because the sample has 10 elements, it has index values of 0 through 9. To index an array, specify the number of the element you want, surrounded by square brackets. Thus, the first element in sample is sample[0], and the last element is sample[9]. For example, the following program load sample with the numbers 0 through 9:

public class arraydemo {
    public static void main(String [] args) {
        int sample[] = new int[10];
        int i;

    for(i = 0; i &lt; 10; i = i+1)
        sample[i] = i;

    for(i = 0; i &lt; 10; i = i+1)
        System.out.println("This is sample[" + i + "]: " + sample[i]);
}

}

The output from the program is shown here:

This is sample[0]: 0
This is sample[1]: 1
This is sample[2]: 2
This is sample[3]: 3
This is sample[4]: 4
This is sample[5]: 5
This is sample[6]: 6
This is sample[7]: 7
This is sample[8]: 8
This is sample[9]: 9

Arrays are common in programming because they let you deal easily with large numbers of related variables. For example, the following program find the minimum and maximum values stored in the nums array by cycling through the array using a for loop:

public class minmax {
    public static void main(String [] args) {
        int nums[] = new int[10];
        int min, max;

    nums[0] = 99;
    nums[1] = -10;
    nums[2] = 100123;
    nums[3] = 18;
    nums[4] = -978;
    nums[5] = 5623;
    nums[6] = 463;
    nums[7] = -9;
    nums[8] = 287;
    nums[9] = 49;
    min = max = nums[0];
    for (int i = 1; i &lt; 10; i++) {
        if(nums[i] &lt; min) min = nums[i];
        if(nums[i] &gt; min) min = nums[i];
    }

    System.out.println("min and max: " + min + " " + max);
}

}

The output of the following program is shown here:

min and max: -978 100123

In the preceding program, the nums arrays were given values by hand, using 10 separate assignment statements. Although perfectly correct, there is an easier way to accomplish this. Arrays can be initialized when they are created. The general form for initializing a one-dimensional array is shown here:

type array-name[] = {val1, val2, val3,......., valN};

Here, the initial values are specified by val1 through valN. They are assigned in sequence, left to right, in index order. Java automatically allocates an array large enough to hold the initializers that you specify. There is no need to explicitly use the new operator. For example, here is a better way to write the MinMax program:

public class Minmax2 {
    public static void main(String [] args) {
        int nums[] = {99, -10, 100123, 213, -9873, 5623, -9, 287, 49};

    int min, max;

    min = max = nums[9];
    for(int i =1; i &lt; 9; i++) {
        if(nums[i] &lt; min) min = nums[i];
        if(nums[i] &gt; max) max = nums[i];
    }
    System.out.println("Min and max: " + min + " " + max);
}

}

Array boundaries are strictly enforced in Java; it is a runtime error to overrun or underrun the end of an array. If you want to confirm this for yourself, try the following program that purposely overruns an array:

public class arrayerr {
    public static void main(String [] args) {
        int sample[]  = new int[10];
        int i;
        //generate an array overrun 
        for(i = 0; i < 100; i = i+1)
            sample[i] = i;
    }
}

As soon as i reaches 10, an ArrayIndexOutOfBoundException is generated and the program is terminated.

Multidimensional Array

Although the one-dimensional array is the most commonly used array in programming, multidimensional arrays are certainly not rare. In Java, a multidimensional array is an array of arrays.


Two-Dimensional Arrays

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of a one-dimensional array. To declare a two-dimensional integer array table of size 10, 20 you would write.


int table[][] = new int[10][20];

Pay careful attention to the declaration. Unlike some other computer languages, which use commas to separate the array dimensions. Java places each dimension in its own set of brackets. Similarly, to access point 3, of array table, you would use table[3][5].

public class twod {
    public static void main(String [] args) {
        int t, i;
        int table[] [] = new int [3] [4];

    for(t = 0; t &lt; 3; ++t) {
        for (i = 0; i &lt; 4; ++i) {
            table [t] [i] = (t*4)+i+1;
            System.out.println(table[t][i] + " ");
            System.out.println(table [t] [i] + " ");
        }
        System.out.println();
    }
}

}

In this example, table[0][0] will have the value 1, table[0][1] the value 2, table[0][2] the value 3, and so on. The value of table[2][3] will be 12. Conceptually, the array will look like that shown down here:

Irregular Arrays

When you allocate memory for a multidimensional array, you need to specify only the memory for the first dimension. You can allocate the remaining dimensions separately. For example, the following code allocated memory for the first dimensions of table when it is declared. It allocates the second dimension manually.


int table[][] = new int [3][];
table[0] = new int[4];
table[1] = new int[4];
table[2] = new int[4];

Although there is no advantage to individually allocating the second dimensions arrays in this situation, there may be in other. For example, when you allocate dimensions separately, you do not need to allocate the same number of elements for each index. Since multidimensional arrays are implemented as arrays of arrays, the length of each array is under your control. For example, assume you are writing a program that stores the number of passengers that ride an airport shuttle. If the shuttle runs 10 times a day during the week and twice a day on Saturday and Sunday, you could use the rider arrays shown in the following program to store the information. Notice that the length of the second dimensions for the first five indices is 10 and the length of the second dimensions for the last two indices is 2.

public class ragged {
    public static void main(String [] args){
        int riders[][]= new int[7][];
        riders[0] = new int[10];
        riders[1] = new int[10];
        riders[2] = new int[10];
        riders[3] = new int[10];
        riders[4] = new int[10];
        riders[5] = new int[2];
        riders[6] = new int[2];

    int i, j;

    // fabricates some fake data
    for(i = 0; i &lt; 5; i++)
        for (j = 0; j &lt; 10; j++)
            riders[i][j] = i + j + 10;
    for(i = 5; i &lt; 7; i++)
        for(j = 0; j&lt; 2; j++)
            riders[i][j] = i + j + 10;

    System.out.println("riders per trip during the week: ");
    for(i = 0; i &lt; 5; i++) {
        for(j = 0; j &lt; 10; j++)
            System.out.println(riders[i][j] + " ");
        System.out.println();
    }

    System.out.println();

    System.out.println("Riders per trip on the weekend: ");
    for (i = 5; i &lt; 7; i++) {
        for(j=0; j &lt; 2; j++)
            System.out.println(riders[i][j] + " ");
        System.out.println();
    }
}

}

The use of irregular multidimensional arrays is not recommended for most application, because it runs contrary to what people expect to find when the multidimensional array is encountered. However, irregular arrays can be used effectively in some situations. For example, if you need a very large two-dimensional array that is sparsely populated, an irregular array might be a perfect solution.

Arrays of Three or More Dimensional

Java allows arrays with more than two dimensional. Here is the general form of a multidimensional array declaration:


type name []....[] = new type[size1][size2]....[sizeN];

For example, the following declaration creates a 4 x 10 x 3 three-dimensional integer array.

int multidim[][][] = new int [4][10][3];

Initializing Multidimensional Arrays

A multidimensional array can be initialized by enclosing each dimensions initializers list within its own set of curly braces. For example, the general form of array initialization for a two-dimensional array is shown here:


type-specifier array_name[][] = {
   {val, val, val,....val},
   {val, val, val,....val},
.
.
.
.
  {val,val, val, val....val}
};

Here, Val indicates an initialization value. Each inner block designates a row. Within each row, the first value will be stored in the first position of the subarray, the second value in the second position, and so on. Notice that commas separate the initializers block and that a semicolon follows the closing },

For example, the following program initializers an array called sqrs with the number 1 through 10 and their squares:

public class square {
    public static void main(String [] args) {
        int sqrs[][] = {
                {1, 1},
                {2, 4},
                {3, 9},
                {4, 16},
                {5, 25},
                {6, 36},
                {7, 49},
                {8, 64},
                {9, 81},
                {10, 100}
        };

    int i, j;

    for(i = 0; i &lt; 10; i++) {
        for(j = 0; j &lt; 2; j++)
            System.out.print(sqrs[i][j] + " ");
        System.out.println();
    }
}

}

Here is the output of the program:

1 1 
2 4 
3 9 
4 16 
5 25 
6 36 
7 49 
8 64 
9 81 
10 100

Alternative Array Declaration Syntax

This is a second form that can be used to declare an array:


type[] var-name;

Here, the square brackets follow the type specifier, not the name of the array variable. For example, the following two declarations are equivalent:

int counter[] = new int[3];
int[] counter = new int[3];

The following declarations are also equivalent:

char table [] [] = new char[3][4];
char[] [] table = new char[3][4];

This alternative declaration form offers convenience when declaring several arrays at the same time. For example,

int[] nums, nums2, nums3; //create three arrays

This creates three arrays variables of type int. It is the same as writing

int num[], num2[], num3[]; //also, create three arrays

The alternative declaration form is also useful when specifying an array as a return type for a method. For example,

int[] someMeth() { ....

This declares that someMeth() returns an array of type int. Because both forms of array declarations are in widespread use.

Assigning Array Reference

As with other objects, when you assign one array reference variable to another, you are simply changing what object that variable refers to. You are not causing a copy of the array to be made, nor are you causing the contents of one array to be copied to the other. For example, consider this program:


public class assignreff {
    public static void main(String [] args) {
        int i;

    int nums1[] = new int[10];
    int nums2[] = new int[10];

    for(i = 0; i &lt; 10; i++)
        nums1[i] = i;

    for(i = 0; i &lt; 10; i++)
        nums2[i] = -i;

    System.out.println("Here is num1: ");
    for(i = 0; i &lt; 10; i++)
        System.out.print(nums1[i] + " ");
    System.out.println();

    System.out.println("Here is num2: ");
    for(i = 0; i &lt; 10; i++)
        System.out.print(nums2[i] + " ");
    System.out.println();

    nums2 = nums1; // now nums2 refers to nums1

    System.out.println("Here is nums2 after assignment: ");
    for(i = 0; i &lt; 10; i++)
        System.out.print(nums2[i] + " ");
    System.out.println();

    // now operate on nums1 array through nums2
    nums2[3] = 99;

    System.out.println("Here is nums1 after assignment: ");
    for(i = 0; i &lt; 10; i++)
        System.out.print(nums1[i] + " ");
    System.out.println();


}

}

The output from the following code is:

Here is num1: 
0 1 2 3 4 5 6 7 8 9 
Here is num2: 
0 -1 -2 -3 -4 -5 -6 -7 -8 -9 
Here is nums2 after assignment: 
0 1 2 3 4 5 6 7 8 9 
Here is nums1 after assignment: 
0 1 2 99 4 5 6 7 8 9

As the output shows, after the assignment of nums1 to nums2, both array reference variables refer to the same object.

Using the Length Member

Because arrays are implemented as objects, each array has associated with it a length instance variable that contains the number of elements that the array can hold. Here is a program that demonstrates this property:


public class lengthdemo {
    public static void main(String [] args) {
        int list[] = new int[10];
        int nums[] = {1, 2, 3 };
        int table[][] = {// a variable length table
                {1, 2, 3},
                {4, 5},
                {6, 7, 8, 9}
        };

    System.out.println("length of ist is  " + list.length);
    System.out.println("length of nums is " + nums.length);
    System.out.println("length of table is " + table.length);
    System.out.println("length of table[0] is " + table[0].length);
    System.out.println("length of table[1] is " + table[1].length );
    System.out.println("length of table[2] is " + table[2].length);

    System.out.println();

    // use length to initialize list
    for(int i = 0; i &lt; list.length; i++)
        list[i] = i * i;

    System.out.println("here is a list: ");
    // now use length to display list
    for(int i = 0; i&lt; list.length; i++)
        System.out.print(list[i] + " ");
    System.out.println();
}

}

Here is the output of the following code:

length of ist is  10
length of nums is 3
length of table is 3
length of table[0] is 3
length of table[1] is 2
length of table[2] is 4
here is a list: 
0 1 4 9 16 25 36 49 64 81


Pay special attention to the way length is used with the two-dimensional array table. As explained, a two-dimensional array is an array of arrays. Thus, when the expression

table.length

is used, it obtains the number of arrays stored in a table, which is 3 in this case. To obtain the length of any individual array in the table, you will use an expression such as this,

table[0].length

which, in this case, obtains the length of the first array.

One other thing to notice in LengthDemo is the way that list.length is used by the for loops to govern the number of iterations that take place. Since each array carries with it its own length, you can use this information rather than manually keeping track of an array’s size. Keep in mind that the value of length has nothing to do with the number of elements that are actually in use. It contains the number of elements that the array is capable of holding.

The inclusion of the length member simplifies many algorithms by making certain types of array operations easier — and safer — to perform. For example, the following program uses length to copy one array to another while preventing an array overrun and its attendant runtime exception.

public class Acopy {
    public static void main(String [] args) {
        int i;
        int nums1[] = new int[10];
        int nums2[] = new int[10];

    for(i = 0; i &lt; nums1.length; i++)
        nums1[i] = i;

    //cppy nums1 to nums2
    if(nums2.length &gt;= nums1.length)
        for(i = 0; i &lt; nums1.length; i++)
            nums2[i] = nums1[i];

    for(i = 0; i &lt; nums2.length; i++)
        System.out.println(nums2[i] + " ");
}

}

Here, length helps perform two important functions. First, it is used to confirm that the target array is large enough to hold the contents of the source array. Second, it provides the termination condition of the loop that performs the copy. Of course, in this simple example, the sizes of the arrays are easily known, but this same approach can be applied to a wide range of more challenging situations.

The For-Each Style for Loop

When working with arrays, it is common to encounter situations in which each element in an array must be examined, from start to finish. For example, to compute the sum of the values held in an array, each element in the array must be examined. The same situation occurs when computing an average, searching for a value, copying an array, and so on. Because such “start to finish” operations are so common, Java defines a second form of the for loop that streamlines this operation.


The second form of the for implements a “for-each” style loop. A for-each loop cycles through a collection of objects, such as an array, in strictly sequential fashion, from start to finish. In recent years, for-each style loops have gained popularity among both computer language designers and programmers. Originally, Java did not offer a for-each style loop. However, with the release of JDK 5, the for loop was enhanced to provide this option. The for-each style of for is also referred to as the enhanced for loop.

The general form of the for-each style for is here:

for(type itr-var: collection) statement-block

Here, type specifies the type, and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end. The collection being cycled through is specified by the collection. There are various types of collections that can be used with the for, but the only type used in this book is the array. With each iteration of the loop, the next element in the collection is retrieved and stored in itr-var. The loop repeats until all elements in the collection have been obtained. Thus, when iterating over an array of size N, the enhanced for obtains the elements in the array in index order, from 0 to N–1.

Because the iteration variable receives values from the collection, type must be the same as (or compatible with) the elements stored in the collection. Thus, when iterating over arrays, the type must be compatible with the element type of the array.

To understand the motivation behind a for-each style loop, consider the type of for loop that it is designed to replace. The following fragment uses a traditional for loop to compute the sum of the values in an array:

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for(int i = 0; i < 10; i++) sum += nums[i];


To compute the sum, each element in nums is read, in order, from start to finish. Thus, the entire array is read in a strictly sequential order. This is accomplished by manually indexing the nums array by i, the loop control variable. Furthermore, the starting and ending value for the loop control variable and its increment must be explicitly specified.

The for-each style for automates the preceding loop. Specifically, it eliminates the need to establish a loop counter, specify a starting and ending value, and manually index the array. Instead, it automatically cycles through the entire array, obtaining one element at a time, in sequence, from beginning to end. For example, here is the preceding fragment rewritten using a for-each version of the for:

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
fo(int x: nums) sum += x;


With each pass through the loop, x is automatically given a value equal to the next element in nums. Thus, on the first iteration, x contains 1, on the second iteration, x contains 2, and so on. Not only is the syntax streamlined, it also prevents boundary errors.

Here is an entire program that demonstrates the for-each version of the for just described:

public class foreach {
    public static void main(String [] args) {
        int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int sum = 0;

    // use for-each style for to display and sum the values
    for(int x:  nums) {
        System.out.println("value is: " + x);
        sum += x;
    }

    System.out.println("Summation: " + sum);
}

}

The output of the program is shown here:

value is: 1
value is: 2
value is: 3
value is: 4
value is: 5
value is: 6
value is: 7
value is: 8
value is: 9
value is: 10
Summation: 55

As this output shows, the for-each style for automatically cycles through an array in sequence from the lowest index to the highest.

Although the for-each for loop iterates until all elements in an array have been examined, it is possible to terminate the loop early by using a break statement. For example, this loop sums only the first five elements of nums:

//sum only the first 5 elements. 
for(int x: nums) {
   System.out.println("Value is: " + x);
   sum += x;
   if(x == 5) break; // stop the loop when 5 is obtained 
}

There is one important point to understand about the for-each style for loop. Its iteration variable is “read-only” as it relates to the underlying array. An assignment to the iteration variable has no effect on the underlying array. In other words, you can’t change the contents of the array by assigning the iteration variable a new value. For example, consider this program:

public class nochange {
    public static void main(String [] args) {
        int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    for(int x : nums) {
        System.out.print(x + " ");
        x = x * 10; // no effect on nums
    }

    System.out.println();

    for(int x : nums)
        System.out.print(x + " ");

    System.out.println();
}

}

The first for loop increases the value of the iteration variable by a factor of 10. However, this assignment has no effect on the underlying array nums, as the second for loop illustrates. The output, shown here, proves this point:

1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10

Iterating Over Multidimensional Arrays

The enhanced for also works on multidimensional arrays. Remember, however, that in Java, multidimensional arrays consist of arrays. This is important when iterating over a multidimensional array because each iteration obtains the next array, not an individual element. Furthermore, the iteration variable in the for loop must be compatible with the type of array being obtained. For example, in the case of a two-dimensional array, the iteration variable must be a reference to a one-dimensional array. In general, when using the for-each for to iterate over an array of N dimensions, the objects obtained will be arrays of N-1 dimensions. To understand the implication of this, consider the following program. It uses nested for loop to obtain the elements of a two-dimensional array in row order, from first to last.


public class foreach2 {
    public static void main(String [] args){
        int sum = 0;
        int nums[][] = new int[3][5];

    //give nums some value
    for (int i = 0; i &lt; 3; i++)
        for(int j = 0; j &lt; 5; j++)
            nums [i][j] = (i + 1) * (j + 1);

    // use for each for loop to display and sum the values
    for(int x[] : nums) {
        for(int y: x) {
            System.out.println("Value is: " + y);
            sum += y;

        }
    }
    System.out.println("Summation: " + sum);
}

}

The output from this program is shown here:

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90

In the program, pay special attention to this line:

for(int x[[ : nums) {

Notice how x is declared. It is a reference to a one-dimensional array of integers. This is necessary because each iteration of the for obtains the next arrays in nums, beginning with the array specified by nums[0]. The inner for loop then cycles through each of these arrays, displaying the values of each element.

Applying the Enhanced for

Since the for-each style for can only cycle through an array sequentially, from start to finish, you might think that its use is limited. However, this is not true. A large number of algorithms require exactly this mechanism. One of the most common is searching. For example, the following program uses a for loop to search an unsorted array for a value. It stops if the value if found.


public class search {
    public static void main(String [] args){
        int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4};
        int val = 5;
        boolean found =false;

    //use for each styple for to search nums for val.
    for(int x: nums) {
        if(x == val) {
            found = true;
            break;
        }
    }

    if(found)
        System.out.println("value found!");
}

}

The for-each style is an excellent choice in this application because searching an unsorted array involves examining each element in the sequence. Other types of application that benefit from for each style loops include computing an average, finding the minimum or maximum of a set, looking for duplicates, and so on.

String

From a day-to-day programming standpoint, one of the most important of Java’s data type is String. String defines and supports character strings. In many other programming languages, a string is an array of characters. This is not the case with Java. In Java, strings are objects.


Actually, you have been using the String class since day one, but you might not know it. When you create a string literal, you are actually creating a String object. For example, in the statement

System.out.println("In Java, Strings are objects.");

the string, “In Java, strings are objects.” It automatically made into a String object by Java. Thus, the use of the String class has been “below the surface” in the preceding programs. In the following sections, you will learn to handle it explicitly. Be aware, however, that the String class is quite large, and I will only scratch its surface here. It is a class that you will want to explore on its own.

Constructing Strings

You can construct a String just like you construct any other type of object: by using new and calling the String constructor. For example:


String str = new String("Hello");

This creates a String object called str that contains the character string “Hello”. You can also construct a String from another String. For example:

String str = new String("Hello");
String str2 = new String(str);

After this sequence executes, str2 will also contain the character string “Hello”.

Another easy way to create a String is shown here:

String str = "Java strings are powerful.";

In this case, str is initialized to the character sequence, “Java strings are powerful.”

Once you have created a String object, you can use it anywhere that a quoted string is allowed. For example, you use a String object as an argument to println(), as shown in this example:

public class stringdemo {
    public static void main(String [] args) {
        // declare strings in various ways
        String str1 = new String("Java strings are objects");
        String str2 = "they are constructed various ways.";
        String str3 = new String(str2);

    System.out.println(str1);
    System.out.println(str2);
    System.out.println(str3);

}

}

The output from the program is shown here:

Java strings are objects
they are constructed various ways.
they are constructed various ways.

Arrays of Strings

Like any other data type, strings can be assembled into arrays. For example:


public class StringArrays {
    public static void main(String [] args) {
        String strs[] = {"this", "is", "a","test."};

    System.out.println("Original array: ");
    for(String s: strs)
        System.out.print(s + " ");
    System.out.println("\n");

    // change a string
    strs[1] = "was";
    strs[3] = "test, too!";

    System.out.println("Modified array: ");
    for(String s : strs)
        System.out.print(s + " ");
}

}

The output of the following program is:

Original array: 
this is a test.
Modified array: 
this was a test, too!


Strings Are Immutable

The contents of a String object are immutable. That is, once created, the character sequence that makes up the string cannot be altered. This restriction allows Java to implement strings more efficiently. Even though this probably sounds like a serious drawback, it isn't. When you need a string that is a variation on one that already exists, simply create a new string that contains the desired changes. Since unused String objects are automatically garbage collected, you don’t even need to worry about what happens to the discarded strings. It must be made clear, however, that String reference variable may, of course, change the object to which they refer. It is just that the contents of a specific String object cannot be changed after it is created.


To fully understand why immutable strings are not a hindrance, we will use another of String’s methods: substring(). The substring() method returns a new string that contains a specified portion of the invoking strings. Because a new String object is manufactured that contains the substring, the original string is unaltered, and the rule of immutability remains intact. The form of substring() that we will be using is shown here:

String substring(int startIndex, int endIndex)

Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. Here is a program that demonstrates substring() and the principle of immutable strings:

public class Substr {
    public static void main(String[] argss){
        String str = "Java makes the web move. ";

    //construct a substring
    String substr = str.substring(5, 18);

    System.out.println("str: " + str);
    System.out.println("substr:  "+ substr);
}

}

Here is the output of the following program:

str: Java makes the web move. 
substr:  makes the web

As you can see, the original string str is unchanged, and substr contains the substring.

Using a String to Control a switch Statement

A switch had to be controlled by an integer type, such as int or char. This precluded the use of a switch in situations in which one of the sveral actions is selected based on the content of a string. Instead, an if-else-if ladder was the typical solution. Although an if-else-if ladder is semantically correct a switch statement would be a more natural idiom for such a selection. Fortunately, this situation has been remedied. Today, you can use a String to control a switch. This results in a more readable, streamlined code in many situations.


public class Stringswithc {
    public static void main(String [] args) {

    String command = "cancel";

    switch (command) {
        case "connect":
            System.out.println("connecting");
            break;
        case "cancel":
            System.out.println("canceling");
            break;
        case "disconnect":
            System.out.println("Disconnecting");
            break;
        default:
            System.out.println("Command Error!");
            break;
    }
}

}

As you would expect, the output from the program is:

Canceling 

The string contained in command is tested against the case statement. When a match is found, the code sequence associated with that sequence is executed.

Being able to use strings in a switch statement can be very convenient and can improve the readability of some code. For example, using a string based switch is an improvement over using the equivalent sequence of if/else statement. However, switching on strings can be less efficient than switching on integers. Therefore, it is best to switch on strings only in cases in which the controlling data is already in string form. In other words, don’t use strings in a switch unnecessarily.

--------------------------------------------

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter


Learn More

☞ Java Programming Masterclass for Software Developers

☞ Selenium WebDriver with Java -Basics to Advanced+Frameworks

☞ Java In-Depth: Become a Complete Java Engineer!

☞ JSP, Servlets and JDBC for Beginners: Build a Database App

☞ JSP, Servlet, JSLT + Hibernate: A complete guide

☞ Java Hibernate Tutorial for Beginners

☞ 50+ Java Interview Questions for Programmers

☞ Top 5 Java Test Frameworks for Automation in 2019

☞ Spring Boot + JPA + Hibernate + Oracle

☞ Functional programming for Java developers

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners

Java Essentials : Learn Core Java From Basic to Advance

Learn Java Programming Using Practical Assignments. Start Building Back-end Web Applications Robust Test Automation Frameworks By End Of The Course. Learn More!

Fundamentos de Java: Aprende Java desde cero, sin misterios | Simpliv

Fundamentos de Java: Aprende Java desde cero, sin misterios