Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 293


Previous 1060 Stories (530 Pages, 2 Per Page) Next

The Java Lesson 20: Initializing and processing arrays of objects

Go to all tips in Java Lessons by Jon Huhtala
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Initializing and processing arrays of objects


Overview

Java requires that all the elements within an array be of the same type. In the previous lesson, we constructed arrays in which all the elements were of the same primitive type (boolean, float, char, etc.).

In this lesson, we will construct arrays in which all the elements are of the same non-primitive, class type (such as String or StringBuffer). Such arrays are called object arrays.

Object arrays

  • Are declared with the class name as the type. For example,

String[] names = new String[5];

Constructs an array of 5 String object references. It is important to understand that no String objects are created by this declaration. We have simply created an array of null object references which may later be assigned to individual String objects (as shown by the following diagram).

names

Heap space

----->

null

null

null

null

null

The statement

names[3] = new String("Hello World!");

would instantiate a String object and assign it to the fourth element in the names array (which would look like the following).

names

Heap space

----->

null

null

null

null

----->

"Hello World!"

To display the value of this particular String object, one might code

System.out.println(names[3]);

which retrieves the String object referenced by the fourth element in the names array.

  • Are arrays of object references. Each element is either the reference of an instantiated object or is null. The general syntax to access an instance method of the object being referenced is

array-identifier[index].method-name(arguments)

For example, to determine the length of the encapsulated string in the fourth element of the names array one would code the expression

names[3].length()

  • Can result in runtime errors if improperly used. In addition to an ArrayIndexOutOfBoundsException, it is possible for a NullPointerException to occur if an attempt is made to reference an object when the object reference is null.

Example: Attempting to call an instance method of an object that doesn't exist.

public class App {
public static void main(String[] args) {
String[] names = new String[5];
System.out.println("Length of first string: " + names[0].length());
}
}

  • Can be constructed from a value list. This requires the instantiation or the existence of the objects to be referenced by each array element. For example,

String aString = new String("def");
String[] x = {new String("abc"), aString, "xyz"};

creates a three element array of String object references. The first element references a String object having the value "abc", the second element references a String object having the value "def", and the third references the String object in the literal pool having the value "xyz".


Sample program

The following program allows a user to specify the number of elements and element values for an array of String objects where each object encapsulates a person's name. After all names have been entered, they are displayed in their original order. The array is then sorted into the alphabetical order of the names being referenced and the sorted list of names is displayed. The user is then asked if they want to do another array.

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

// Loop control variable.

char again = 'y';

// Main loop. One array is entered and processed in each iteration.

another:

while (again == 'Y' || again =='y') {

// Local variables for performing array processing.

String[] names;
int noElements;
boolean didSwap;
int sortPasses;

// Prompt for and read how many names the array is to contain.

Utility.separator(40, '=');
System.out.print("How many names will you enter? " );
noElements = Keyboard.readInt();

// If the number of elements is invalid, display an error message
// and continue the main loop from the beginning.

if (noElements <= 0) {
Utility.skip();
System.out.println(" Invalid number of elements");
continue another;
}

// Instantiate the array and loop to load its elements with values
// entered by the user.

names = new String[noElements];
Utility.skip();
for (int i = 0; i < noElements; i++) {
System.out.print("Element (" + i + "): ");
names[i] = Keyboard.readString();
}

// Display a message saying that loading is complete.

Utility.skip();
System.out.println(" Loading is complete.");
System.out.println(" The unsorted array contains:");
Utility.skip();

// Loop through the entire array to display the value of each
// element.

for (int i = 0; i < noElements; i++) {
System.out.println(" " + names[i]);
}

// Sort the array. This is accomplished by passing through the
// entire array comparing adjacent element values. If the second
// of the two elements should come first, they are swapped and an
// indicator set that specifies that a swap occurred. Additional
// passes are made until no swap occurs.

sortPasses = 0;
do {

// When a new pass begins, no swap has occurred.

didSwap = false;

// Loop through the entire array to compare adjacent elements.

for (int i = 0; i < names.length - 1; i++) {

// If the second of the two elements should come first,
// swap them and indicate that a swap occurred.

if (names[i + 1].compareTo(names[i]) < 0) {
String temp = names[i];
names[i] = names[i + 1];
names[i + 1] = temp;
didSwap = true;
}
}

// Increment the counter of the number of sort passes and
// continue looping as long as a swap occurred.

sortPasses++;
} while (didSwap);

// Display sort statistics.

Utility.skip();
System.out.println(" Sort required " + sortPasses + " pass(es).");
System.out.println(" The sorted array contains:");
Utility.skip();

// Display the sorted array's contents by looping through the
// entire array to display the value of each element.

for (int i = 0; i < noElements; i++) {
System.out.println(" " + names[i]);
}

// Ask the user if they want to do it again and repeat the loop as
// requested.

Utility.separator(40, '=');
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
}
}
}

Note: There are many sorting techniques. The one shown here is not necessarily the best, but is fairly straightforward.

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

Review questions

  1. Which of the statements below are true after executing the following? (choose three)

String[] s = new String[10];

  1. s.length is 10

  2. s[0] is null

  3. s[0].length() is 0

  4. s[0] == s[1]

  5. s[0].equals(s[1])

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following code? The line numbers are for reference purposes only.

1
2
3
4
5
String[] x = {"a", "bc", "def"};
if (x.length == x[2].length())
System.out.println("equal");
else
System.out.println("not equal");
  1. Compilation will fail at line 1

  2. Compilation will fail at line 2

  3. Compilation will succeed but a runtime error will occur

  4. Compiles and runs to display "equal"

  5. Compiles and runs to display "not equal"

  1. How many objects are created by the following statement?

StringBuffer[] zBuffers = new StringBuffer[10];

  1. none

  2. one

  3. ten

  4. eleven

  1. Assume that table is an array of String object references where no element is null (each element references an instantiated String object). Code a single statement to extract the first character of the first String object referenced by the array and assign it to a previously defined char variable named first.


9503 bytes more | 3 comments | Printer Friendly Page  Send to a Friend | Score: 0
Posted by jalex on Monday, January 24, 2005 (00:00:00) (13655 reads)

Gif4J PRO 2.0 and Gif4J LIGHT 1.0 released

Go to all tips in Graphics
Gif4J PRO Java GIF Imaging Library - the professional edition of the Gif4J Java GIF imaging library offers the most comprehensive GIF image processing solution for imaging professionals.


Using Gif4J PRO you can:

  • load and decode GIF images for the further processing with a single method call;

  • encode and save images and image arrays as one-image and animated GIFs;

  • control image color depth (number of unique colors) using the fastest, most intelligent and qualitative Gif4J java color quantizer;

  • transform GIF images including resize, scale, rotate and flip operations;

  • watermark and stamp the whole GIF images and separate GIF image frames;

  • extract, add and remove GIF image textual comments;

  • extract all GIF image format specific meta information including GIF format version, logic GIF image size, number of frames, frames' sizes, frames' positions, color models, transparency and interlace support etc.

  • access and manipulate internal GIF image frames in the random order;

  • generate amazing image tours, animations and banners;

  • render text information;

  • and much more.





Gif4J LIGHT Java GIF Encoder - the light edition of the Gif4J Java GIF imaging library
is the fast, easy-to-use and royalty-free* java-based GIF encoder with the embedded java color quantizer to
save images as animated and non-animated GIFs.
The footprint is just over 20K and it is compatible with Java 1.1 and later.

* Gif4J Light offers royalty-free distribution of applets and stand-alone end-user java applications.




Please visit http://www.gif4j.com for more information


8 comments | Printer Friendly Page  Send to a Friend | Score: 0
Posted by Anonymous on Saturday, January 22, 2005 (00:00:00) (3077 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490| 489| 488| 487| 486| 485| 484| 483| 482| 481| 480| 479| 478| 477| 476| 475| 474| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394| 393| 392| 391| 390| 389| 388| 387| 386| 385| 384| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331| 330| 329| 328| 327| 326| 325| 324| 323| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312| 311| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294|
293
| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy