aspose file tools*
The moose likes Java in General and the fly likes Key Advantages of Java 5 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Key Advantages of Java 5" Watch "Key Advantages of Java 5" New topic
Author

Key Advantages of Java 5

Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
Greetings! Many thanks to JavaRanch for choosing my book, Beginning Java Objects, Second Edition as their featured book of the week.

When my publisher, Apress LP, asked me to update B.J.O. (first published in 2000) to highlight J2SE 5 (aka Java v. 1.5), my first reaction was to decline. The primary intent of my book is to focus on object concepts and Java features that are language version {B}neutral[/B]. However, the more I learned about J2SE 5, the more I realized that in order to do justice to the power of Java, I simply had to incorporate significant features of v. 5 in B.J.O. because they were SOOOO NIFTY!

In particular, I'd like to chat with you about the following two v. 5 features:

The improved ease with which collections are handled, thanks to the notion of generics

The introduction of enum(eration)s as a new type, to complement classes and interfaces

That being said, I've added a lot more to the second edition of B.J.O. than simply touching upon version 5 enhancements. I've been teaching Java for over five years since my first edition came out, and each group of new students = new questions = better ways of explaining Java!

I look forward to chatting with you on JavaRanch.

Best regards,

Jacquie
[ July 13, 2005: Message edited by: Jacquie Barker ]

Author of Beginning Java Objects, Beginning C# Objects, and Taming the Technology Tidal Wave
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
The power of enum(erations) - Part 1

Prior to the introduction of enumerations in Java 5, the best we could do to enumerate permitted values for a method/constructor parameter was to declare public static final variables for a class, assigning a different symbolic name to each permitted value.

As an example, if we wanted to enumerate the possible values of a Student's major field of study (stored as a String attribute in the Student class):

one typical way of doing so would be to declare public static final variables in the Student class -- one per valid major -- as follows:

We could then take advantage of these symbolic constants in our client code as follows:

However, since the second argument to our Student constructor is declared to be a String, there is no way to prevent client code from disregarding all of our carefully crafted symbolic values to assign an invalid String value as a student�s major -- for example:

Thus, prior to Java 5, we could at best provide a list of preferred values as a convenience, but could not enforce their use at compile time.

The other pre-5 approach for preventing an invalid major from being passed in was a run time solution: namely, to invent our own custom exception type, e.g.,

and then to have our Student constructors/methods throw such an exception as appropriate, e.g.,

This would in turn force client code to provide exception handling:

but, as we see above, an attempt to pass an invalid major would still get past the compiler, such that we'd have to deal with it at run time.

Fortunately, with Java 5, there's now a compile time way of ensuring that improper arguments will never get passed -- via enum(eration)s!

Stay tuned for part 2 ...

Jacquie
[ July 11, 2005: Message edited by: Jacquie Barker ]
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30764
    
156

Jacquie,
Welcome back!

I've seen some examples where methods are provided for enums. What do you think of this practice?

For one or two one line methods it is somewhat clear. After that it looks like a bunch of subclasses in one file to me.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
i'm tuned and curious about the end of your enum adventures

anyway i'd like to know how you relate your book to introducing OO and design patterns: is that your main goal?


java amateur
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
Originally posted by Jeanne Boyarsky:
Jacquie,
Welcome back!

I've seen some examples where methods are provided for enums. What do you think of this practice?

For one or two one line methods it is somewhat clear. After that it looks like a bunch of subclasses in one file to me.


I'm sorry, but I'm quite sure what you are referring to ... can you perhaps send me an example off-line, in which case I'd be happy to comment!

Meanwhile, I think after you read part 2 of my enum story that they are truly an elegant way to go!

Best,

J.
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
Originally posted by miguel lisboa:
i'd like to know how you relate your book to introducing OO and design patterns: is that your main goal?


My main purpose for writing BJO was that I couldn't find a beginning Java book that did what I considered to be a thorough job of explaining "why objects?" and "HOW objects?". Many people dive into Java as their first OO language, and while they do wind up building applications, they haven't necessarily tapped into the true power of Java as an OO language.

My book is organized into three parts, all based on the same central case study of a Student Registration System:

Part 1: teaches the basics of objects/sound OOP principles while introducing Java syntax side-by-side

Part 2: introduces the basics of object modeling; I touch EVER SO BRIEFLY on the notion of design patterns, but only to indicate their value

Part 3: shows how to translate the UML model for the SRS -- developed in part 2 of the book -- into a full-blown SRS application, something that few if any other books present.

I teach Java at the college level (for both The George Washington University and George Mason University) and after several years of looking for -- and failing to find -- a single book that would cover all of the bases to use as a textbook, I wound up writing my own (back in Nov. 2000). To my delight, I seemed to have filled a gap that existed despite the many Java books that were already on the market.

The second edition is a "freshening" of my message based on 5+ additional years of teaching, and also gave me an opportunity to highlight some of the particularly significant improvements made with v. 5.

Thanks for asking!

Now, on to part 2 of the enum story ...

Best,

J.
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
The power of enum(eration)s - part 2

Continuing my earlier example, we know that there are only a handful of valid String values for a student�s major � is there perhaps a way to constrain the "major" attribute so that we can prevent mis-assignment at compile time? As of Java version 5.0, the answer is yes! We use a construct called an enum � short for "enumeration" � to define/enumerate a finite set of values that a given variable may assume.

Along with classes and interfaces, an enum is another form of user-defined type in Java that lives in its own .java source code file and is compiled into bytecode:

More specifically, an enum is a very simplistic sort of class, consisting of only:

* A single attribute, named "value", declared to be of whatever (primitive or reference) type we wish for it to be:

Note that value is declared to be both private and final; the keyword final indicates that an enum instance�s "value" attribute may only be assigned a value once in its "lifetime," after which the value cannot be changed.

* A list (enumeration) of values that the value attribute is permitted to assume, represented as a comma separated list of symbolic name-value pairs:


* A simple constructor, used to initialize the value attribute:

Note that an enum�s constructor isn�t declared to be public, because it is *not* invoked from client code; rather, it is used internally to the enum (in declaring the list of symbolic name-value pairs above).

* A single accessor method, value(), used by client code to retrieve the value of the enum�s lone attribute.

Putting this all together, the general template for declaring an enum is as follows, where the italicized items are those that we can customize:

OK, that's an enum ... so, what's the big deal? Plenty!!!

Let�s go back to our example involving students' majors, and retrofit an enum called Major to control the assignment of valid major values at [B}compile[/B] time.

* Behind the scenes, the values that Major can assume will be declared as Strings:

* Hence, the type of the "value" attribute, the type of the parameter passed to the Major constructor, and the return type of the value() method are all declared to be String to match:

Now, let�s reengineer our Student class to take advantage of the new Major enum/type. In particular, we�ll:

* Change the declaration of the Student class�s "major" attribute to be of type Major instead of String;

* Change the type of the second parameter that we�re passing into our Student constructor accordingly;

* Eliminate our use of the InvalidMajorException;

* Change the setMajor method to accept an argument of type Major versus String.

And, while we�re at it, let�s add a display method for use in testing our improvements to the Student class. The "new and improved" Student class code is thus as follows:


To really appreciate what this buys us, we now need to look at the other side of the coin: namely, how our Student class is used from client code. This will be covered in part 3 (the final part, I promise!)
[ July 11, 2005: Message edited by: Jacquie Barker ]
Nirav Patel
Greenhorn

Joined: May 27, 2005
Posts: 22
Hi,
I have read couple of books on OOP and Java.
I find all of then kinda 'awkward', as one of the book start with swing directly wihout any OOPs concepts and other one jumps on the UML from the second chapter!
Though for the intermeiate it's not difficult to cope up, for beginners it's tough to swallow those heavy 'words' (like JOptionPane, etc without knowing Java basic packages).
How does your book starts climbing OOPs with Java...?
(Even Complete Reference is good one for OOPs, but goes more on language features rather than OOPs concepts!)

Regards,
Nirav


----<br />Nirav Patel<br />Software is the bottleneck in the digital world!
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
I introduce object concepts gently, using Java to illustrate them (although virtually all of the concepts apply equally well to any other OO language: C++, C#, etc.)

I assume *NO* prior object experience whatsoever from my readers (or from my students, when I teach Java). In fact, some of my favorite students/readers are folks who last programmed in Fortran, or COBOL, or -- gasp! -- assembly language! Why? Because such folks often understand the fundamentals of how computers work "under the hood", which makes understanding object referencing (akin to pointers in C) much easier for them to grasp.

Again, I encourage you to read the reader reviews of my book on Amazon to get a sense of who my book has helped, and how.

Best regards,

Jacquie
perry forman
Greenhorn

Joined: Jan 11, 2005
Posts: 7
Thanks Jacquie.

I can tell from the intro on Amazon, as well as reviews there, that this would be a valuable book for me. I am in the throes of deciding between Java / Dot.net. It's great to find books that will help in either endevor.

I really appreciate when others who have great writing ability see the holes in available education material and are able to fill in the gaps.

PF
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Hi Jeanne!

Originally posted by Jeanne Boyarsky:
I've seen some examples where methods are provided for enums. What do you think of this practice?

For one or two one line methods it is somewhat clear. After that it looks like a bunch of subclasses in one file to me.


It's true that it can be overdone. If used selectively, it's a great feature, though - for example for providing a Visitor for the enum, or for implementing simple States/Strategies!


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
The power of enum(eration)s -- part 3 of 3

Let�s now demonstrate how our newly designed Student class might be utilized from client code:

When executed, this program would produce the following output:

where the symbolic name Major.CS has been translated to its behind-the-scenes String equivalent, "Computer Science", courtesy of our call to the value() method from within the Student�s display method. Had we instead written the display method as follows:

then the symbolic name of the enum would be printed instead:

It is now physically impossible to assign any value as a Student�s major other than one of the five enum-approved values Major.Math, Major.Bio, Major.Chem, Major.CS, Major.PhysEd;
anything else simply won�t compile!

* The following line of code won�t compile � a String is not a Major:

Compiler error:


* This next line won�t compile either � our Major enum doesn�t define Basketweaving as a valid value:

Compiler error:

Here�s another example of an enum called Grade that renders a double value:

and a bit of client code to illustrate its use:

Output:

Here�s a final example of an enum called StudentBody that uses a reference type, Student, as the encapsulated enum type:

plus a bit of client code to illustrate its use:

Enums are a very powerful feature of Java 5 -- make sure to take time to fully master them!

Best regards,

Jacquie
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30764
    
156

Originally posted by Ilja Preuss:
Hi Jeanne!



It's true that it can be overdone. If used selectively, it's a great feature, though - for example for providing a Visitor for the enum, or for implementing simple States/Strategies!

Ilja, Makes sense. Thanks!

Jacquie, I didn't have any particular code sample in mind. But even given Sun's Planet example, I could see the class getting confusing through adding "one more thing." Or further down on the page, the Operation example. For complex operations, it would get confusing keeping it in the enum class.

I guess it;s just a matter of refactoring once the class gets too involved. Or maybe having another class handle the logic.

[edited because my post got cut off]
[ July 12, 2005: Message edited by: Jeanne Boyarsky ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Jeanne Boyarsky:
I guess it's just a matter of refactoring once the class gets too involved.


That's my guess, too...
Daslan Govender
Greenhorn

Joined: Jan 14, 2005
Posts: 19
Hi Jackie

Just wanted to know how do your tackle the concept of pointers in your book? Do you refer to them as pointers or references or anything else?


Tks
D
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
Originally posted by Daslan Govender:
Hi Jackie

Just wanted to know how do your tackle the concept of pointers in your book? Do you refer to them as pointers or references or anything else?


Tks
D


I generally refer to them as references, but do have a sidebar discussion about the fact that folks familiar with pointers will discover that references are essentially pointers that cannot be "fiddled with" mathematically. I also include some basic "compiler/symbol table 101" discussions to help folks understand what happens when a variable of a simple type, then a reference type, is declared, assigned a value, etc.

J.
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
When I started this topic, I promised to cover enum(eration)s and generics; so, here's a bit on generics ...

=== BEGIN COPYRIGHTED MATERIAL (from Beginning Java Objects by J. Barker)

Prior to Java 5.0, we couldn�t constrain the type of element that a non�Array collection was to hold when we first declared it; all collection types other than Arrays were designed to hold references to generic Objects:

We thus were able to mix references of literally any type of object within a particular collection instance, and the compiler didn�t object:

This led to numerous complications when iterating through a collection, which we�ll discuss in a moment.

Note that the compiler did object if we attempted to insert a primitive type into a non-Array collection prior to Java 5.0:

Error:

Iterating through non�Array collections prior to Java 5.0 required us to cast object references as we retrieved them from the collection. For example, to iterate through an ArrayList of Student object references to compute final grades for the semester, we might use a conventional for loop, with the size of the collection serving as our stopping condition; this is illustrated in the code below:

The expression enrollment.get(i) is considered by the compiler to be an expression of type Object because the get(int) method of the ArrayList class is declared to have a return type of Object. Thus, even though we know that we�ve inserted Student objects into the collection, we must convince the compiler of this by casting each element as we retrieve it; otherwise, we�d not be able to invoke the computeFinalGrade method on the objects.

If we were to omit the cast, as illustrated by the following alternative version of the for loop code:

we�d get the following compilation error:

Alternatively, if we tried to invoke the computeFinalGrade method on the object reference directly, as follows:

we�d get the following compilation error:

Thus, the only way to take advantage of the �Studentness� of a Student object when retrieving it from a pre�5.0 collection was to cast it as a Student.

Let�s return to our example of disparate object references from earlier in this Appendix:

If we were to erroneously attempt to cast all of the objects in x into Pineapples:

the compiler wouldn�t object, because the whole point of a cast is to effectively say to the compiler �Trust me; I know what I am doing!�; specifically to this example, we�re saying �Trust me; at run time, this collection will contain only Pineapples.� So, the compiler trusts us�after all, the collection does contain Objects, so it is conceivable that they are all Pineapples from the compiler�s point of view. However, at run time, we�d get a ClassCastException on the line:

as soon as we encountered the first non-Pineapple reference in x.

With a collection of disparate object types such as x above, our only choice when iterating through the collection was to retrieve and command these objects based on their common identity � that is, we�d have to treat them all as generic Objects, which dramatically limits what we can do with the objects inside of our loop:

We could use the instanceof operator, which we learned in Chapter 13 allows us to check the run-time identity of an object:

This is an inelegant approach, however, because if we add a fourth, or a fifth, or a sixth type of Object to collection x, we�d have to find all cases of �if else� logic in all of our iterations through x to add additional instanceof tests, which is not practical.

The bottom line is that prior to Java 5.0, we had to exercise discipline with regard to putting objects into collections, because the compiler would not restrict us when putting items in, but the compiler and JVM were both liable to complain when pulling items back out!

=== END COPYRIGHTED MATERIAL (from Beginning Java Objects by J. Barker)

I'll post another note in a bit that illlustrates the new, greatly improved way of declaring/using collections made available as of Java 5 ... stay tuned!

Jacquie
Jacquie Barker
author
Ranch Hand

Joined: Dec 20, 2000
Posts: 201
As promised, here's some additiona information regarding Java 5, collections, and generics ...

=== BEGIN COPYRIGHTED MATERIAL ===

In contrast with Java versions 1.4 and earlier, where manipulating collections of objects could be tricky/tedious, as of Java 5.0, several improvements have been made.

First of all, we can now constrain the type of object a collection holds thanks to generics. Simply put, Sun designed the predefined Java collection classes to operate generically on object references of any type, but then provided a syntactic means of constraining the type of element that a particular collection is to manage. Now, whenever we want to instantiate a collection such as an ArrayList, we can indicate the type of element that the collection is intended to hold by enclosing the type name in angle brackets <...> immediately after the class name:

and so forth. In essence, ArrayList<xxx> becomes the type of the collection that we�re instantiating.

Another addition as of Java 5 is an enhanced for loop syntax which, when combined with our ability to constrain the type of reference that a collection is to hold when we declare it, makes for much simpler iteration logic, as illustrated below:

Recall that as of Java 1.4 and earlier, we have to retrieve an element from a collection as a generic Object and CAST it to be whatever it really is at run time.

And, as of Java 5.0, if we were to attempt to insert a non�Student object into our enrollment collection:

the compiler would prevent us from doing so with the following error message:

Thus, as of version 5.0, Java provides [B}compile-time[/B] type checking with respect to collections, thus greatly lessening the risk of run-time ClassCastExceptions when retrieving from a collection.

=== END COPYRIGHTED MATERIAL ===

There's more coming ... stay tuned!

J.
 
Don't get me started about those stupid light bulbs.
 
subject: Key Advantages of Java 5