Data Structures using Java Part 5: More on arrays, initialisers, function parameters, do loop, break ,continue and final

Automatic Array Construction

int[][] table = new int[x][y];

1. Creates an array of x referecnces to array.
2. Creates x arrays of y int.



Human[] b = {amy, danny, Human(" Jacky")};
int[][] c = {{2,4,5},{45},{2,4,5,6},{1,3,},{x},{y+3, 4}};

int[] a,b,c; // specifies the type and all are reference arrays
int a[], b, c[][]; // a is 1D , b is just an int and c is 2D; proper C style
int[] a , b[]; // a is 1D and b is 2D

Array of objects
When you create an array of objects, Java does not automatically create the objects for you. And you need to create a loop for the same.

Fraction[] f = new Fraction[5];
for (int i = 0; i<5; i++) {
	f[i] = new Fraction[i][6];

Main functions parameters

class Echo{

	public static void main(String[] args ){
		for(int i =0; i< args.length; i++){


1. String[] args consists of the arguments you type in at the unix prompt.
2. args.length gives the number of arguments.
For example if we type this in the unix prompt:

$ java Echo my name is Daniel


Note that java Echo is not a part of the argument list.

do loops
1. Executes the loop body at least once.

 s = keybd.readLine(); // read a line from the keyboard
 process(s); // do something
 }while(s.length > 0); //  if size of s is 0 , then exit the loop

There might be an ambiguity as in what to do if the user enter anything in the beginning. This will cause the process method to break down and ultimately an error occurs. This can be corrected by the following code:

The break and continue statement
break statement always exits the innermost “switch” or loop enclosing the break.

 // method one
 s = keybd.readLine();
 	while(s.length > 0){       // process only if the length is greater than 0
		 s = keybd.readLine();

1. Repeated code s = keybd.readLine()


 // method two: with the break statement
 while (true){

 	s = keybd.readLine();
 	if(s.length == 0)


1. Obfuscated
2. Loop is not aligned with natural alignment


1. It only applies to loops
2. Doesnt exit the loop.
3. Another iteration my commence if condition of do/while/for loop is satisfied.

 while(i < 9){
 		case 1: break;
 		case 2: break stuff; // breaks the loop and continues at statement 1
 		case 3: continue; // jumps out of switch but still inside while loop and so next iteration occurs
 		case 4: continue loop; // same as above

 		//statement 1
	//statement 2

“final” keyword – value that can never be changed.


if (month == 2){ // if 2 represents something like a month february and it is difficult to change


 public static final int FEB =2; // change code only in one place
 if (month == FEB){

For any array x, x.length is considered to be a final field and thus cannot be changed!

Data Structures using Java Part 5: More on arrays, initialisers, function parameters, do loop, break ,continue and final