[1]\n";. Special case: you are free to omit the pointer dereferencing arrow between adjacent brackets (whether square or curly): print "$frame_events[1][1]\n";. In general you. Note: Technically, two-dimensional arrays in Perl are arrays of arrays. Each "row" is itself a reference to the anonymous array in brackets. To refer to an element in a two-dimensional array, specify the array variable as a scalar with two indexes indicating the row and column of the element you are referring to. The index.">
Skip to content

Perl 2d Array Assignment In Java

Array means collection. In Java also, an array is a collection of similar things. eg.- an array of int will contain only integers, an array of double will contain only doubles, etc.

Why array?

Suppose you want to store the marks of 100 students. Obviously, you need a better approach over defining 100 different variables and using them. Here the role of array comes in.


Declaration of array

int[] z = new int[10];

It looks similar to defining a variable and actually it is. Here we are declaring 10 variables at one go.

Let's understand this

int[] z is representing that 'z' is an array of type integer ( as [ ] represents array ) and 'new int[10]' is representing that is it an array of 10 integers. In other words, we can say that 'z' is a collection of 10 integers.

Now, a question comes to mind, how to use these 10 variables?

The pictorial view is like this.

Each array has some array elements. In the above array example, there are 10 array elements.

0,1,2....8,9 are indices. It is like, these are the identities of 10 different array elements. Index starts from 0. So, the first element of the array has index 0, the second element has index 1 and so on.

element231584813
index012345

Normally, we declare and assign a value to a variable as follows.

For an array, we do the same as follows.

int[] z = new int[10];
z[0] = 50;

int[] z = new int[10]; - This line will make an array of 10 integers.

z[0] = 50; - z[0] represents the first element of the array 'z' and a value of 50 is assigned to it. So, the first element (z[0]) of the array has value 50.

z[0],z[1]....,z[9] are similar to variables we have used before. So, to access an element of an array, we write its index in brackets '[ ]' after the array name i.e. array_name[index].

Thus, for the above example, z[0] is the first element of the array 'z', z[1] is the second element and so z[9] is the tenth element.

And z[0], z[1], ... , z[9] are now same as the variables we have already used.

One more declaration

If we know the elements of an array, then we can also declare the array and assign values to the its variables as:

int[] x = {23,32,43,12,43};

Here, we have declared 'x' with its elements. 'x' will automatically become an array of 5 elements as there are 5 elements in 'x'.

The value of the first element (x[0]) of the array is 23, that of the second element (x[1]) is 32 and thus the value of the fifth element (x[4]) is 43.

Now see this example:

Output

importjava.util.*;classA1{publicstaticvoidmain(String[]args){int[]z=newint[10];Scanners=newScanner(System.in);System.out.println("Enter 10 integers of array");for(inti=0;i<10;i++){z[i]=s.nextInt();}System.out.println("You have entered");for(inti=0;i<10;i++){System.out.println(z[i]);}}}

Enter 10 integers of array
11
2
34
2
4
54
96
54
80
44
You have entered:
11
2
34
2
4
54
96
54
80
44

The above example is given to make you understand how to use an array.

There are two for loops in the above example. In the first for loop, we are taking the values of the different elements of the array from user one by one. In the second for loop, we are printing the values of the elements of the array.

Going in the first for loop. In the first iteration, the value of 'i' is 0, so 'z[i]' is 'z[0]'.Thus by writing z[i] = s.nextInt(), z[0] will be given its value input by the user. Similary in the second iteration, the value of 'i' will be 1 and 'z[i]' will be 'z[1]'. So, 'z[i] = s.nextInt()' will be used to input value from the user for z[1] and so on. 'i' will go up to 9, so the indices of the array will be ( 0,1,2,...,9).

The second for loop is for printing the values of the different elements. It will work in the same way as the first for loop.

Java has a predefined function to get the length of an array ( number of elements in an array ).

Let's see an example of this function.

So, 'length' is a function in Java which gives you the size of an array ( as shown above ).

Let's write our own method to calculate the sum of all the elements of an array:

The above example is to show you how we can pass an array in a method. All the other parts are hopefully clear to you.

We called the method 'cal_sum' by passing the name of the array 'x' as its argument.

While declaring the method public static int cal_sum(int[] a), (int[] a) represents that this method requires an array of integer to be passed while calling this method.

So, by calling cal_sum(x), we have passed the array x to the function cal_sum. In the function public static int cal_sum(int[] a), this a will become x ( as we have passed x ) and further things will proceed.

a.length will give the length of the array. So, for an array of 5 elements, it will give 5. So, i in for loop must go till 4 only ( i < a.length ).

For-each loop


There is a new form of for loop. There is no official name to this for loop, but the term for-each is used most often. It is used to iterate over an array. Let's see an example of this.

This is very simple. Here, the variable m will go to every element of the array ar and will take its value.
So, in the first iteration, m is the 1st element of the array ar i.e. 1.
In the second iteration, it is the 2nd element i.e. 2 and so on. Just focus on the syntax of this for loop, rest of the part is very easy.

2D Arrays


Same as one-dimensional, we also have 2-dimensional array.

2-dimensional arrays are generally known as matrix. These consist of rows and columns.

Before going into its application, let's first see how to declare and assign values to a 2 D array.

Declaration of 2 D Array

We define 2-dimensional array as follows.

int[][] a = new int[2][4];

Here, a is a 2-D array of type int which consists of 2 rows and 4 columns.

Column 0Column 1Column 2Column 3
Row 0a[0][0]a[0][1]a[0][2]a[0][3]
Row 1a[1][0]a[1][1]a[1][2]a[1][3]

Now let's assign values to the elements of the 2-dimensional array.

Initialization of 2 D Array


We can assign values to a 2-dimensional array in two ways, same as we do in a one-dimensional array.

In the first method, just assign a value to the elements of the array.

Suppose we declared a 2-dimensional array a[2][2]. After declaring it, we assign a value to its elements.

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

The second way is to declare and assign values at the same time where each inner curly bracket represents one row.

int a[2][3] = {
  {1, 2, 3},
  {4, 5, 6 }
};

Here, the value of a[0][0] is 1, a[0][1] is 2, a[0][2] is 3, a[1][0] is 4, a[1][1] is 5 and a[1][2] is 6.

int[][] s = new int[2][2]; /* valid */
int[][] s = new int[2][]; /* valid */
int[][] s = new int[][2]; /* invalid */
int[][] s = new int[][]; /* invalid */

Use of 2 D Array


Suppose there are 3 students and both the students are studying 2 subjects (subject 1 and subject 2). We want to display the marks of both the students in the two subjects which we will be taking from the user.

Output

importjava.util.Scanner;classA4{publicstaticvoidmain(String[]args){float[][]s=newfloat[3][2];Scanners1=newScanner(System.in);for(inti=0;i<3;i++){System.out.println("Enter marks of student : "+(i+1));for(intj=0;j<2;j++){System.out.println("Subject : "+(j+1));s[i][j]=s1.nextFloat();}}for(inti=0;i<3;i++){System.out.println("Student"+(i+1));for(intj=0;j<2;j++){System.out.println("Subject"+(j+1)+":"+s[i][j]);}}}}

Enter marks of student : 1
Subject : 1
10
Subject : 2
20
Enter marks of student : 2
Subject : 1
30
Subject : 2
10
Enter marks of student : 3
Subject : 1
20
Subject : 2
40
Student1
Subject1:10.0
Subject2:20.0
Student2
Subject1:30.0
Subject2:10.0
Student3
Subject1:20.0
Subject2:40.0

In the above example, firstly we defined our array consisting of 3 rows and 2 columns as float[][] s = new float[3][2];

Here. the elements of the array will contain the marks of the 3 students in the 2 subjects as follows.

Subject 1Subject 2
Student 11020
Student 23040
Student 35060

In our example, firstly we are taking the value of each element of the array using a for loop inside another for loop.

In the first iteration of the outer for loop, the value of 'i' is 0. With the value of 'i' as 0, when the inner for loop first iterates, the value of 'j' becomes zero and so s[i][j] becomes s[0][0]. By writing s[i][j] = s1.nextFloat;, we are taking the value of s[0][0].

After that, the inner for loop again iterates and the value of 'j' becomes 1. s[i][j] becomes s[0][1] and its value is taken from the user.

Then, the outer loop iterates for the second time and the value of 'i' becomes 1 and the whole process continues.

After assigning the values to the elements of the array, we are printing the values of the elements of the array in the same way using another for loop inside this loop.

Let's see one more example of 2 D Array

Suppose there are 2 factories and each of these factories produces items of 4 different types, like some items of type 1, some items of type 2 and so on. We have to calculate the total product of each factory i.e. sum of the items of each type that a factory produces.

Output

classA5{publicstaticvoidmain(String[]args){int[][]s=newint[2][4];s[0][0]=2;s[0][1]=5;s[0][2]=7;s[0][3]=4;s[1][0]=9;s[1][1]=3;s[1][2]=2;s[1][3]=8;System.out.println("Sum of the items produced in the first factory :");intsum1=0,sum2=0;for(inti=0;i<4;i++){sum1+=s[0][i];}System.out.println(sum1);System.out.println("Sum of the items produced in the second factory :");for(intj=0;j<4;j++){sum2+=s[1][j];}System.out.println(sum2);}}

Sum of the items produced in the first factory :
18
Sum of the items produced in the second factory :
22

Here, s[0][i] represents the number of items of the first factory and type i, where i takes value from 0 to 3 using for loop and s[1][i] represents the nunmber of items of second factory of type i. E.g. - s[0][2] represents the third type of item of first factory and s[1][2] represents the third type of item of second factory. sum1 is the sum of all the items of factory 1. Similar is the case of the second factory.

So, initially sum1 is 0. Now in the first iteration, s[0][i] is s[0][0]. This means that it will represent the number of the first type of item of the first factory. So, sum1 += s[0][i] will become sum1 += s[0][0]. Thus, the value of sum1 will be 2. Similarly in the second iteration, s[0][i] will become s[0][1] and will represent the second type of items of the first factory. Now, sum1 will become 2+5 i.e. 7. Similarly, things will go further.

There is no glory in practice but there is no glory without practice.

PrevNext






Index of an array starts with 0.

Output

classA0{publicstaticvoidmain(String[]args){int[]z=newint[10];z[0]=223;z[1]=23;int[]x={23,32,43,12,43};System.out.println(z[0]);System.out.println(z[1]);System.out.println(x[3]);System.out.println(x[0]);}}

Output

classA2{publicstaticvoidmain(String[]args){int[]z=newint[10];System.out.println(z.length);}}

Output

classA3{publicstaticintcal_sum(int[]a){intsum=0;for(inti=0;i<a.length;i++){sum=sum+a[i];}returnsum;}publicstaticvoidmain(String[]args){int[]x={23,32,43,12,43};System.out.println(cal_sum(x));}}

Output

classA31{publicstaticvoidmain(String[]args){int[]ar={1,2,3,4,5,6,7,8,9,10};for(intm:ar){System.out.println(m);}}}

While assigning values to an array at the time of declaration, there is no need to give dimensions in one dimensional array, but in 2 D array, we need to give at least the first dimension.


by Laura Lemay



Although you could write Java programs using what you've learned so far, those programs would be pretty dull. Much of the good stuff in Java or in any programming language results when you have arrays to store values in and control-flow constructs (loops and conditionals) to execute different bits of a program based on tests. Today, you'll find out about the following:

  • Arrays, one of the most useful objects in Java, which enable you to collect objects or primitive types into an easy-to-manage list
  • Block statements, for grouping together related statements
  • and , for conditional tests
  • and loops, for iteration or repeating a statement or statements multiple times

Arrays in Java, as in other languages, are a way to store collections of items into a single unit. The array has some number of slots, each of which holds an individual item. You can add and delete items to those slots as needed. Unlike in other languages, however, arrays in Java are actual objects that can be passed around and treated just like other objects.

Arrays can contain any type of element value (primitive types or objects), but you can't store different types in a single array. You can have an array of integers or an array of strings or an array of arrays, but you can't have an array that contains, for example, both strings and integers.

To create an array in Java, you use three steps:

  1. Declare a variable to hold the array.
  2. Create a new array object and assign it to the array variable.
  3. Store things in that array.

Declaring Array Variables

The first step in creating an array is creating a variable that will hold the array, just as you would any other variable. Array variables indicate the type of object the array will hold (just as they do for any variable) and the name of the array, followed by empty brackets (). The following are all typical array variable declarations:

String difficultWords[]; Point hits[]; int temps[];

An alternate method of defining an array variable is to put the brackets after the type instead of after the variable. They are equivalent, but this latter form is often much more readable. So, for example, these three declarations could be written like this:

String[] difficultWords; Point[] hits; int[] temps;

Creating Array Objects

The second step is to create an array object and assign it to that variable. There are two ways to do this:

  • Using
  • Directly initializing the contents of that array

The first way is to use the operator to create a new instance of an array:

String[] names = new String[10];

That line creates a new array of s with 10 slots (sometimes called elements). When you create a new array object using , you must indicate how many slots that array will hold. This line does not put actual objects in the slots-you'll have to do that later.

Array objects can contain primitive types such as integers or booleans, just as they can contain objects:

int[] temps = new int[99];

When you create an array object using , all its slots are initialized for you ( for numeric arrays, for boolean, for character arrays, and for objects). You can then assign actual values or objects to the slots in that array. You can also create an array and initialize its contents at the same time. Instead of using to create the new array object, enclose the elements of the array inside braces, separated by commas:

String[] chiles = { "jalapeno", "anaheim", "serrano", "habanero", "thai" };

Each of the elements inside the braces must be of the same type and must be the same type as the variable that holds that array (the Java compiler will complain if they're not). An array the size of the number of elements you've included will be automatically created for you. This example creates an array of objects named that contains five elements.

Accessing Array Elements

Once you have an array with initial values, you can test and change the values in each slot of that array. To get at a value stored within an array, use the array subscript expression ():

myArray[subscript];

The part of this expression is a variable holding an array object, although it can also be an expression that results in an array. The part of the expression, inside the brackets, specifies the number of the slot within the array to access. Array subscripts start with , as they do in C and C++. So, an array with 10 elements has 10 array slots accessed using subscript to .

Note that all array subscripts are checked when your Java program is run to make sure that they are inside the boundaries of the array (greater than or equal to but less than the array's length). Unlike in C, it is impossible in Java to access or assign a value to an array slot outside the boundaries of the array (thereby avoiding a lot of the common problems and bugs that result from overrunning the bounds of an array in C-like languages). Note the following two statements, for example:

String[] arr = new String[10]; arr[10] = "eggplant";

A program with that last statement in it produces an error at that line when you try to run it. (Actually, to be more technically correct, it throws an exception. You'll learn more about exceptions on Day 18, "Multithreading.") The array stored in has only 10 slots numbered from , the element at subscript doesn't exist.

If the array subscript is calculated at runtime (for example, as part of a loop) and ends up outside the boundaries of the array, the Java interpreter also produces an error.

How can you keep from accidentally overrunning the end of an array in your own programs? You can test for the length of the array in your programs using the instance variable-it's available for all array objects, regardless of type:

int len = arr.length // returns 10

However, just to reiterate: The length of the array is , but its subscript can only go up to . Arrays start numbering from . Whenever you work with arrays, keep this in mind and subtract 1 from the length of the array to get its largest element.

Changing Array Elements

To assign an element value to a particular array slot, merely put an assignment statement after the array access expression:

myarray[1] = 15; sentence[0] = "The"; sentence[10] = sentence[0];

An important thing to note is that an array of objects in Java is an array of references to those objects (similar in some ways to an array of pointers in C or C++). When you assign a value to a slot in an array, you're creating a reference to that object, just as you do for a plain variable. When you move values around inside arrays (as in that last line), you just reassign the reference; you don't copy the value from one slot to another. Arrays of primitive types such as s or s do copy the values from one slot to another.

Arrays of references to objects, as opposed to the objects themselves, are particularly useful because you can have multiple references to the same objects both inside and outside arrays. For example, you can assign an object contained in an array to a variable and refer to that same object by using either the variable or the array position.

Got it? Arrays are pretty simple to create and modify, but they provide an enormous amount of functionality for Java. You'll find yourself running into arrays a lot the more you use Java.

To finish up the discussion on arrays, here's a simple program that shows how to create, initialize, modify, and examine parts of an array. Listing 5.1 has the code.


Listing 5.1. Various simple array operations.
1: class ArrayTest { 2: 3: String[] firstNames = { "Dennis", "Grace", "Bjarne", "James" }; 4: String[] lastNames = new String[firstNames.length]; 5: 6: void printNames() { 7: int i = 0; 8: System.out.println(firstNames[i] 9: + " " + lastNames[i]); 10: i++; 11: System.out.println(firstNames[i] 12: + " " + lastNames[i]); 13: i++; 14: System.out.println(firstNames[i] 15: + " " + lastNames[i]); 16: i++; 17: System.out.println(firstNames[i] 18: + " " + lastNames[i]); 19: } 20: 21: public static void main (String args[]) { 22: ArrayTest a = new ArrayTest(); 23: a.printNames(); 24: System.out.println("----------"); 25: a.lastNames[0] = "Ritchie"; 26: a.lastNames[1] = "Hopper"; 27: a.lastNames[2] = "Stroustrup"; 28: a.lastNames[3] = "Gosling"; 29: a.printNames(); 30: } 31:}

Dennis null Grace null Bjarne null James null ---------- Dennis Ritchie Grace Hopper Bjarne Stroustrup James Gosling

The class also has two methods: and . , defined in lines 6 through 19, is a utility method that does nothing but go through the and arrays sequentially, printing the values of each slot, one name per line. Note that the array index we've defined here () is initially set to because Java array slots all start numbering from .

Finally, there is , which performs the actual actions of this example. The method here does four things:

  • Line 22 creates an initial instance of , so we can set and modify its instance variables and call its methods.
  • Line 23 calls to show what the object looks like initially. The result is the first four lines of the output; note that the array was initialized, but the values in are all . If you don't initialize an array when you declare it, the values of the initial slots will be empty (or, actually, for object arrays, for numbers, and for booleans).
  • Lines 25 through 28 set the values of each of the slots in the array to actual strings.
  • Finally, line 29 calls once again to show that the array is now full of values, and each first and last name prints as you would expect. The results are shown in the last four lines of the output.

One other note I should make about Listing 5.1 is that it's a terrible example of programming style. Usually when you deal with arrays you do not hard code the number of elements into the code as we have here; instead you use a loop to go through each element of the array in turn. This makes the code a lot shorter and, in many cases, easier to read. You'll learn about loops later in this section, and we'll rewrite this example so that it works more flexibly.

Multidimensional Arrays

One last thing to note about arrays before we move on to the rest of this lesson is about multidimensional arrays. Java does not directly support multidimensional arrays. However, you can declare and create an array of arrays (and those arrays can contain arrays, and so on, for however many dimensions you need) and access the arrays as you would C-style multidimensional arrays:

int coords[][] = new int[12][12]; coords[0][0] = 1; coords[0][1] = 2;

Before we launch into the last two-thirds of this lesson, let's take a small detour into a topic I haven't mentioned a whole lot up to this point (but that will be important later on): block statements.

A block statement is simply a group of Java statements surrounded by braces (). You've seen blocks a whole lot already; you've used a block statement to contain the variables and methods in a class definition, and inside that block you've also used blocks to hold the body of a method definition. The opening brace opens the block, and the closing brace closes the nearest closing block. Easy, right?

You can also use blocks even further, inside method definitions. The rule is that you can use a block anywhere a single statement would go. Each statement inside the block is then executed sequentially.

So what's the difference between using a group of individual statements and using a block? The block creates a new local variable scope for the statements inside it. This means that you can declare and use local variables inside a block, and those variables will cease to exist after the block is finished executing. For example, here's a block inside a method definition that declares a new variable . You cannot use outside the block in which it's declared:

void testblock() { int x = 10; { // start of block int y = 50; System.out.println("inside the block:"); System.out.println("x:" + x); System.out.println("y:" + y); } // end of block }

Blocks are not usually used in this way-alone in a method definition, with random variable declarations inside them. You've mostly seen blocks up to this point surrounding class and method definitions, but another very common use of block statements is in the control flow constructs you'll learn about in the remainder of today's lesson.

The conditional statement is used when you want to execute different bits of code based on a simple test. conditions are nearly identical to statements in C: They contain the keyword , followed by a boolean test, followed by either a single statement or a block statement to execute if the test is . Here's a simple example that prints the message only if the value of is less than the value of :

if (x < y) System.out.println("x is smaller than y");

An optional keyword provides the alternative statement to execute if the test is :

if (x < y) System.out.println("x is smaller than y"); else System.out.println("y is bigger");

Using , you can only include a single statement as the code to execute after the test (in this case, the method for each one). But because a block can appear anywhere a single statement can, if you want to do more than just one thing (as you usually will), you can enclose those statements inside a block:

if (engineState == true ) System.out.println("Engine is already on."); else { System.out.println("Now starting Engine."); if (gasLevel >= 1) engineState = true; else System.out.println("Low on gas! Can't start engine."); }

This example uses the test . For boolean tests of this type, a common shortcut is merely to include the first part of the expression rather than explicitly test its value against or . Because it's a boolean variable, it automatically returns or all by itself, so you don't have to explicitly test it for that value. Here's a shorter version of the previous code, with the test replaced with the shorthand version:

if (engineState) System.out.println("Engine is on."); else System.out.println("Engine is off.");

Listing 5.2 shows another simple example-this one in full application form. The class contains one utility method called , which tests a value to see if it's even. If it is, it prints to the screen.


Listing 5.2. The class.
1: class Peeper { 2: 3: void peepMe(int val) { 4: System.out.println("Value is " 5: + val + ". "); 6: if (val % 2 == 0) 7: System.out.println("Peep!"); 8: } 9: 10: public static void main (String args[]) { 11: Peeper p = new Peeper(); 12: 13: p.peepMe(1); 14: p.peepMe(2); 15: p.peepMe(54); 16: p.peepMe(77); 17: p.peepMe(1346); 18: } 19: }

Value is 1. Value is 2. Peep! Value is 54. Peep! Value is 77. Value is 1346. Peep!

We'll use a method, as always, in this application to create a new instance of and test it, calling the method repeatedly with different values. In the output, only the values that are even get a message.

The Conditional Operator

An alternative to using the and keywords in a conditional statement is to use the conditional operator, sometimes called the ternary operator (ternary means three; the conditional operator has three parts).

The conditional operator is an expression, meaning that it returns a value (unlike the more general , which can only result in a statement or block being executed). The conditional operator is most useful for very short or simple conditionals and looks like this:

test ? trueresult : falseresult;

is a boolean expression that returns or , just like the test in the statement. If the test is , the conditional operator returns the value of ; if it's , it returns the value of . For example, the following conditional tests the values of and , returns the smaller of the two, and assigns that value to the variable :

int smaller = x < y ? x : y;

The conditional operator has a very low precedence; that is, it's usually evaluated only after all its subexpressions are evaluated. The only operators lower in precedence are the assign-ment operators. See the precedence chart in Day 3's lesson for a refresher on precedence of all the operators.

A common programming practice in any language is to test a variable against some value, and if it doesn't match that value, to test it again against a different value, and if it doesn't match that one to make yet another test, and so on until it matches with the right result. Using only statements, this can become unwieldy, depending on how it's formatted and how many different options you have to test. For example, you might end up with a set of statements something like this or longer:

if (oper == '+') addargs(arg1, arg2); else if (oper == '-') subargs(arg1, arg2); else if (oper == '*') multargs(arg1, arg2); else if (oper == '/') divargs(arg1, arg2);

This form of statement is called a nested because each statement in turn contains yet another , and so on, until all possible tests have been made.

Many languages have a shorthand version of the nested that is (somewhat) easier to read and allows you to group the tests and actions. Called a or statement, in Java it's called and behaves as it does in C:

switch (test) { case valueOne: resultOne; break; case valueTwo: resultTwo; break; case valueThree: resultThree; break; ... default: defaultresult; }

In the statement, the test (a variable or expression that evaluates to a , , , or ) is compared with each of the case values (, , and so on) in turn. If a match is found, the statement (or statements) after the test is executed. If no match is found, the statement is executed. The is optional, so if there isn't a match in any of the cases and doesn't exist, the statement completes without doing anything.

Note that the significant limitation of the in Java is that the tests and values can be only simple primitive types (and then only primitive types that are automatically castable to ). You cannot use larger primitive types (, ), strings, or other objects within a , nor can you test for any relationship other than simple equality. This limits the usefulness of ; nested s can work for any kind of test on any type.

Here's a simple example of a statement similar to the nested shown earlier:

switch (oper) { case '+': addargs(arg1, arg2); break; case '-': subargs(arg1, arg2); break; case '*': multargs(arg1, arg2); break; case '/': divargs(arg1, arg2); break; }

There are two things to be aware of in this example: The first is that after each case, you can include a single result statement or as many as you need. Unlike with , you don't need to surround multiple statements with braces for it to work. The second thing to note about this example is the statement included at the end of every case. Without the explicit break, once a match is made, the statements for that match (and also all the statements further down in the for all the other cases) are executed until a or the end of the is found. In some cases, this may be exactly what you want to do, but in most cases, you'll want to make sure to include the so that only the statements you want to be executed are actually executed (break, which you'll learn about in the section "Breaking Out of Loops," stops execution at the current point and jumps to the code outside of the next closing bracket ().

One handy use of allowing a to continue processing statements after a match is found occurs when you want multiple values to match to the same statements. In this instance, you can use multiple case lines with no result, and the will execute the first statement it finds. For example, in the following statement, the string is printed if has a value of , , , or . All other values of print the string :

switch (x) { case 2: case 4: case 6: case 8: System.out.println("x is an even number."); break; default: System.out.println("x is an odd number."); }

Listing 5.3 shows yet another example of a . This class, called , converts integer values to their actual English word equivalents using a method called .


Listing 5.3. The class.
1: class NumberReader { 2: 3: String convertNum(int val) { 4: switch (val) { 5: case 0: return "zero "; 6: case 1: return "one "; 7: case 2: return "two "; 8: case 3: return "three "; 9: case 4: return "four "; 10: case 5: return "five "; 11: case 6: return "six "; 12: case 7: return "seven "; 13: case 8: return "eight "; 14: case 9: return "nine "; 15: default: return " "; 16: } 17: } 18: 19: public static void main (String args[]) { 20: NumberReader n = new NumberReader(); 21: String num = n.convertNum(4) + n.convertNum(1) + n.convertNum(5); 22: System.out.println("415 converts to " + num); 23: } 24:}

415 converts to four one five

So where are the statements? You don't need them here because you're using instead. is similar to except that it breaks out of the entire method definition and returns a single value. Again, you'll learn more about this tomorrow when you learn all about how to define methods.

At this point you've probably seen enough methods to know what's going on, but let's run through this one quickly.

Line 20 creates a new instance of the class.

Line 21 defines a string called that will be the concatenation of the string values of three numbers. Each number is converted using a call to the method.

Finally, line 22 prints out the result.

The loop, as in C, repeats a statement or block of statements until a condition is matched. loops are frequently used for simple iterations in which you repeat a block of statements a certain number of times and then stop, but you can use loops for just about any kind of loop.

The loop in Java looks roughly like this:

for (initialization; test; increment) { statements; }

The start of the loop has three parts:

  • is an expression that initializes the start of the loop. If you have a loop index variable to keep track of how many times the loop has occurred, this expression might declare and initialize it-for example, . Variables that you declare in this part of the loop are local to the loop itself; they cease existing after the loop is finished executing.
  • is the test that occurs before each pass of the loop. The test must be a boolean expression or function that returns a boolean value-for example, . If the test is , the loop executes. Once the test is , the loop stops executing.
  • is any expression or function call. Commonly, the increment is used to change the value of the loop index to bring the state of the loop closer to returning and completing.

The statement part of the loop is the statements that are executed each time the loop iterates. Just as with , you can only include one statement, although a block will work just fine as well.

Remember the example in the section on arrays where I said that iterating over the contents of an array is usually done with a loop? Here's an example of a loop that does just that-it initializes all the values of a array to null strings:

String strArray[] = new String[10]; \\ the array int i; // loop index for (i = 0; i < strArray.length; i++) strArray[i] = "";

In this example, the variable keeps track of the number of times the loop has occurred; it also makes a convenient index for the array itself. Here, we start the loop with an index of . The test for when the loop will end is whether the current index is less than the length of the array (once the index is bigger than the array, you should stop), and the increment is simply to add 1 to the index each time. Then, for every loop you can put a null string () into the array at the given slot.

Any of the parts of the loop can be empty statements; that is, you can simply include a semicolon with no expression or statement, and that part of the loop will be ignored. Note that if you do use a null statement in your loop, you may have to initialize or increment any loop variables or loop indices yourself elsewhere in the program.

You can also have an empty statement for the body of your loop, if everything you want to do is in the first line of that loop. For example, here's one that finds the first prime number higher than 4000 (it calls a method called , which will theoretically have a way of figuring that out):

for (i = 4001; notPrime(i); i += 2) ;

Note that a common mistake in C that also occurs in Java is to accidentally put a semicolon after the first line of the loop:

for (i = 0; i < 10; i++); System.out.println("Loop!");

Because the first semicolon ends the loop with an empty statement, the loop doesn't actually do anything. The function will be printed only once because it's actually outside the loop entirely. Be careful not to make this mistake in your own Java programs.

To finish up loops, let's rewrite that example with the names from the array section. The original example is long and repetitive and only works with an array four elements long. This version, shown in Listing 5.4, is shorter and more flexible (but it returns the same output).


Listing 5.4. A modified array test with loops.
1: class NamesLoop { 2: 3: String[] firstNames = { "Dennis", "Grace", "Bjarne", "James" }; 4: String[] lastNames = new String[firstNames.length]; 5: 6: void printNames() { 7: for (int i = 0; i < firstNames.length; i++) 8: System.out.println(firstNames[i] + " " + lastNames[i]); 9: } 10: 11: public static void main (String args[]) { 12: ArrayTest a = new ArrayTest(); 13: a.printNames(); 14: System.out.println("----------"); 15: a.lastNames[0] = "Ritchie"; 16: a.lastNames[1] = "Hopper"; 17: a.lastNames[2] = "Stroustrup"; 18: a.lastNames[3] = "Gosling"; 19: 20: a.printNames(); 21:} 22:}

Dennis null Grace null Bjarne null James null ---------- Dennis Ritchie Grace Hopper Bjarne Stroustrup James Gosling

Loops

Finally, there are and loops. and loops, like loops, repeat the execution of a block of Java code until a specific condition is met. Whether you use a loop, a , or a is mostly a matter of your programming style.

and loops are exactly the same as in C and C++ except that their test conditions must be booleans.

Loops

The loop is used to repeat a statement or block of statements as long as a particular condition is . loops look like this:

while (condition) { bodyOfLoop; }

The is a boolean, the loop executes the statements in and then tests the condition again, repeating until the condition is . I've shown the loop here with a block statement because it's most commonly used, although you can use a single statement in place of the block.

Listing 5.5 shows an example of a loop that copies the elements of an array of integers (in ) to an array of s (in ), casting each element to a as it goes. The one catch is that if any of the elements in the first array is , the loop will immediately exit at that point.


Listing 5.5. loops to copy array elements.
1: class CopyArrayWhile { 2: public static void main (String args[]) { 3: int[] array1 = { 5, 7, 3, 6, 0, 3, 2, 1 }; 4: float[] array2 = new float[array1.length]; 5: 6: System.out.print("array1: [ "); 7: for (int i = 0; i < array1.length; i++) { 8: System.out.print(array1[i] + " "); 9: } 10: System.out.println("]"); 11: 12: System.out.print("array2: [ "); 13: int count = 0; 14: while ( count < array1.length && array1[count] != 0) { 15: array2[count] = (float) array1[count]; 16: System.out.print(array2[count++] + " "); 17: } 18: System.out.println("]"); 19: } 20:}

array1: [ 5 7 3 6 0 3 2 1 ] array2: [ 5 7 3 6 ]

I've done all the work here in to make things shorter. Here's what's going on here:

Lines 3 and 4, declare the arrays; is an array of s, which I've initialized to some suitable numbers. , or s, is the same length as , but doesn't have any initial values.

Lines 6 through 10 are for output purposes; they simply iterate through using a loop to print out its values.

Lines 13 through 17 are where the interesting stuff happens. This bunch of statements both assigns the values of (converting the numbers to floats along the array) and prints it out at the same time. We start with a variable, which keeps track of the array index elements. The test in the loop keeps track of the two conditions for existing the loop, where those two conditions are running out of elements in or encountering a in (remember, that was part of the original description of what this program does). We can use the logical conditional to keep track of the test; remember that makes sure both conditions are before the entire expression is . If either one is , the expression returns and the loop exits.

So what goes on in this particular example? The output shows that the first four elements in were copied to , but there was a in the middle that stopped the loop from going any further. Without the , should end up with all the same elements as .

Note that if the loop's test is initially the first time it is tested (for example, if the first element in that first array is ), the body of the loop will never be executed. If you need to execute the loop at least once, you can do one of two things:

  • Duplicate the body of the loop outside the loop.
  • Use a loop (which is described in the following section).
  • The loop is considered the better solution of the two.

Loops

The loop is just like a loop, except that executes a given statement or block until the condition is . The main difference is that loops test the condition before looping, making it possible that the body of the loop will never execute if the condition is the first time it's tested. loops run the body of the loop at least once before testing the condition. loops look like this:

do { bodyOfLoop; } while (condition);

Here, the part is the statements that are executed with each iteration. It's shown here with a block statement because it's most commonly used that way, but you can substitute the braces for a single statement as you can with the other control-flow constructs. The condition is a boolean test. If it returns , the loop is run again. If it returns , the loop exits. Keep in mind that with loops, the body of the loop executes at least once.

Listing 5.6 shows a simple example of a loop that prints a message each time the loop iterates (10 times, for this example):


Listing 5.6. A simple loop.
1: class DoTest { 2: public static void main (String args[]) { 3: int x = 1; 4: 5: do { 6: System.out.println("Looping, round " + x); 7: x++; 8: } while (x <= 10); 9: } 10: }

Looping, round 1 Looping, round 2 Looping, round 3 Looping, round 4 Looping, round 5 Looping, round 6 Looping, round 7 Looping, round 8 Looping, round 9 Looping, round 10

In all the loops (, , and ), the loop ends when the condition you're testing for is met. What happens if something odd occurs within the body of the loop and you want to exit the loop early? For that, you can use the and keywords.

You've already seen as part of the statement; it stops execution of the , and the program continues. The keyword, when used with a loop, does the same thing-it immediately halts execution of the current loop. If you've nested loops within loops, execution picks up in the next outer loop; otherwise, the program merely continues executing the next statement after the loop.

For example, take that loop that copied elements from an integer array into an array of floats until the end of the array or until a is reached. You can instead test for that latter case inside the body of the and then use a to exit the loop:

int count = 0; while (count < array1.length) { if (array1[count] == 0) { break; } array2[count] = (float) array1[count++]; }

is similar to except that instead of halting execution of the loop entirely, the loop starts over at the next iteration. For and loops, this means that the execution of the block starts over again; for loops, the increment and test expressions are evaluated and then the block is executed. is useful when you want to special-case elements within a loop. With the previous example of copying one array to another, you can test for whether the current element is and restart the loop if you find it so that the resulting array will never contain zero. Note that because you're skipping elements in the first array, you now have to keep track of two different array counters:

int count1 = 0; int count2 = 0; while (count < array1.length) { if (array1[count1] == 0) { continue; count1++ } array2[count2++] = (float)array1[count1++]; }

Labeled Loops

Both and can have an optional label that tells Java where to break to. Without a label, jumps outside the nearest loop (to an enclosing loop or to the next statement outside the loop), and restarts the enclosing loop. Using labeled s and s, you can break to specific points outside nested loops or continue a loop outside the current loop.

To use a labeled loop, add the label before the initial part of the loop, with a colon between them. Then, when you use or , add the name of the label after the keyword itself:

out: for (int i = 0; i <10; i++) { while (x < 50) { if (i * x == 400) break out; ... } ... }

In this snippet of code, the label labels the outer loop. Then, inside both the and the loops, when a particular condition is met, a causes the execution to break out of both loops and continue executing any code after both loops.

Here's another example: The program shown in Listing 5.7 contains a nested loop. Inside the innermost loop, if the summed values of the two counters is greater than 4, both loops exit at once.


Listing 5.7. A labeled loop example.
1: class LabelTest { 2: public static void main (String arg[]) { 3: 4: foo: 5: for (int i = 1; i <= 5; i++) 6: for (int j = 1; j <= 3; j++) { 7: System.out.println("i is " + i + ", j is " + j); 8: if (( i + j) > 4) 9: break foo; 10: } 11: System.out.println("end of loops"); 12: } 13:}

i is 1, j is 1 i is 1, j is 2 i is 1, j is 3 i is 2, j is 1 i is 2, j is 2 i is 2, j is 3 end of loops

As you can see, the loop iterated until the sum of and was greater than , and then both loops exited back to the outer block and the final message was printed.

Today you have learned about three main topics that you'll most likely use quite often in your own Java programs: arrays, conditionals, and loops.

You have learned how to declare an array variable, create and assign an array object to that variable, and access and change elements within that array.

Conditionals include the and statements, with which you can branch to different parts of your program based on a boolean test.

Finally, you have learned about the , , and loops, each of which enable you to execute a portion of your program repeatedly until a given condition is met.

Now that you've learned the small stuff, all that's left is to go over the bigger issues of declaring classes and creating methods within which instances of those classes can communicate with each other by calling methods. Get to bed early tonight, because tomorrow is going to be a wild ride.

If arrays are objects, and you use to create them, and they have an instance variable length, where is the class? I didn't see it in the Java class libraries.
Arrays are implemented kind of weirdly in Java. The class is constructed automatically when your Java program runs; provides the basic framework for arrays, including the variable. Additionally, each primitive type and object has an implicit subclass of that represents an array of that class or object. When you create a new array object, it may not have an actual class, but it behaves as if it does.
When you create an array, you have to give it the number of slots that the array has. What happens if you get halfway through your program and you've run out of slots in the array? Does the array get bigger automatically?
No, arrays stay the same size throughout their existence. And, as I noted in the part of this lesson on arrays, you cannot access slots outside the bounds of the array, so adding extra elements to a full array will cause an error.

So what do you do if an array is full? You have to do it the hard way: Create a new array that's bigger than the initial one and copy all the elements from the old array to the new.

Optionally, you can use a data structure other than an array if you expect to have widely varying numbers of elements in the array. The class, part of the package, is a growable collection you can use in place of an array.

Does Java have s?
The Java language defines the keyword , but it is not currently used for anything. In other words, no-Java does not have s.
I declared a variable inside a block statement for an . When the was done, the definition of that variable vanished. Where did it go?
In technical terms, block statements form a new lexical scope. What this means is that if you declare a variable inside a block, it's only visible and usable inside that block. When the block finishes executing, all the variables you declared go away.

It's a good idea to declare most of your variables in the outermost block in which they'll be needed-usually at the top of a block statement. The exception might be very simple variables, such as index counters in loops, where declaring them in the first line of the loop is an easy shortcut.

Why can't you use with strings?
Strings are objects, and in Java works only for the primitive types , , , and . To compare strings, you have to use nested s, which enable more general expression tests, including string comparison.
It seems to me that a lot of loops could be written as loops, and vice versa.
True. The loop is actually a special case of that enables you to iterate a loop a specific number of times. You could just as easily do this with a and then increment a counter inside the loop. Either works equally well. This is mostly just a question of programming style and personal choice.