Sample Code from "Java How to Program, Fifth Edition" from Deitel and De itel.


There are three ways of declaring a simple array:

  1. int myarray[];
    myarray=new int[10];
  2. int myarray[]=new int [10];
  3. int myarray[]={1, 22, 58, 66, 82, 88, 66, 2, 5, 0};

note that arrays are objects, therefore need to use keyword "new"

Cool thing about arrays: they have a data member "length" which knows the length of the array

The following code shows the initialization of an array. InitArray.java


An application of using arrays to calculate the statistics of a die which has been rolled 6000 times.

RollDie.java

Pass by Value or Pass by Reference

General rule:

Code (Applet) that demonstrates passing by reference and pass by value
PassArray.java
PassArray.html


Dealing with Multi Dimensional Arrays

Can have different number of columns for each row

Two ways of creating Multi Dimensional Arrays

  1. Initialization method:
    int myarray[][]={{1,2,3},{4,5},{6}};
  2. Declaring (without initialization)
    int myarray[][];
    int myarray= new int[3][]; //how many rows
    int myarray[0]=new int[3]; //how many columns in first row
    int myarray[1]=new int[2]; //how many columns in second row
    int myarray[2]=new int[1]; //how many columns in third row
Multi.java

Notice how the print function is able to determine how many rows using: "array.length" and how many columns in each row using "array[row].length"


Strings

First, we should discuss the basis of strings: chars. Why are chars 16 bits instead of 8 bits like in C/C++? Because of Unicode.

Unicode expands ascii and has the capability of handling characters from different languages.

For more on Unicode go to: www.unicode.org

Some sample code showing Unicode characters (Let me know if it works on your machines--I'm having John look at fixing Unicode on the Sun Rays)

Unicode.java


Code showing the multiple String Constructors:

StringConstructors

The constructors with 3 arguments have the breakdown:

  1. arg1: array name
  2. arg2: starting index of array
  3. arg3: number of characters to copy

Bonus: not shown in study group. Demonstrates the following functions:

StringMiscellaneous.java

Comparing Strings through the following functions/operators:

StringCompare.java

String is the only object that you don't have to use the keyword "new" with.
For instance, you can say:
String mystring="hello";

Exercise: explore the difference between
String mystring="hello"; and
String mystring= new String("hello");


For further exploration on this, I suggest you use the following code with Object Tool (downloadable from the online course)

StringCompare2.java

Breakdown: