Friday, 6 June 2008

Core Java 8th Edition Volume-i By CAY S. HORSTMANN and GARY CORNELL

Just now i completed reading and practicing examples from Core Java 8th Edition Volume-i By CAY S. HORSTMANN and GARY CORNELL.

This book is Winner of the 2003 Jolt/Software Development Productivity Award!

Please read reviews and interviews of the author of this great book @book site

I safely skipped 3 chapters related to Swings as currently i am not that interested to program in swing applications.

Below are the points i wanted to share with readers from this book.

1) Java has the distinction of being the first and only programming language that had a ten-minute story on National Public Radio.

2) Below are The Java "White Paper" Buzzwords

Simple
Portable
Object Oriented
Interpreted
Network-Savvy
High Performance
Robust
Multithreaded
Secure
Dynamic
Architecture Neutral

3) The single biggest difference between Java and C/C++ is that Java has a pointer model that eliminates the possibility of overwriting memory and corrupting data.

4) Bytecodes are translated into machine code by the just-in-time compiler.Today, however, the just-in-time compilers have become so good that they are competitive with traditional compilers and, in some cases,even outperform them because they have more information available. For example, a just-in-time compiler can monitor which code is executed frequently and optimize just that code for speed. A more sophisticated optimization is the elimination (or “inlining”) of function calls. The just-in-time compiler knows which classes have been loaded. It can use inlining when, based upon the currently loaded collection of classes, a particular function is never overridden, and it can undo that optimization later if necessary.

5) In 1994, most people were using Mosaic, a noncommercial web browser that came out of the supercomputing center at the University of Illinois in 1993. (Mosaic was partially written by Marc Andreessen for $6.85 an hour as an undergraduate student on a work-study project. He moved on to fame and fortune as one of the cofounders and the chief of technology at Netscape.)

6) In the SunWorld interview, Gosling says that in mid-1994, the language developers realized that “We could build a real cool browser. It was one of the few things in the client/server mainstream that needed some of the weird things we’d done: architecture neutral,real-time, reliable, secure—issues that weren’t terribly important in the workstation world. So we built a browser.”

The actual browser was built by Patrick Naughton and Jonathan Payne and evolved into the HotJava browser. The HotJava browser was written in Java to show off the power of Java. But the builders also had in mind the power of what are now called applets, so they made the browser capable of executing code inside web pages. This "proof of technology" was shown at SunWorld ‘95 on May 23, 1995, and inspired the Java craze that continues today.

7) Below table gives an description of Evolution of java language










VersionyearNew Language FeaturesNumber of Classes and Interfaces
1.01996The language itself211
1.11997Inner classes477
1.21998None1,524
1.32000None1,840
1.42004Assertions2,723
5.02004Generic classes, “for each” loop,varargs, autoboxing, metadata,enumerations,static import3,279
62006None3,777


8) C# took many good ideas from Java, such as a clean programming language, a virtual machine, and garbage collection. But for whatever reasons, C# also left some good stuff behind, in particular security and platform independence. If you are tied to Windows,C# makes a lot of sense. But judging by the job ads, Java is still the language of choice for a majority of developers.

9) In the early days of Java, there were some well-publicized reports of failures in the Java security system. Most failures were in the implementation of Java in a specific browser.Researchers viewed it as a challenge to try to find chinks in the Java armor and to defy the strength and sophistication of the applet security model. The technical failures that they found have all been quickly corrected, and to our knowledge, no actual systems were ever compromised. To keep this in perspective, consider the literally millions of virus attacks in Windows executable files and Word macros that cause real grief but surprisingly little criticism of the weaknesses of the attacked platform. Also, the ActiveX mechanism in Internet Explorer would be a fertile ground for abuse, but it is so boringly obvious how to circumvent it that few researchers have bothered to publicize their findings.Some system administrators have even deactivated Java in company browsers, while continuing to permit their users to download executable files, ActiveX controls, and
Word documents. That is pretty ridiculous—currently, the risk of being attacked by hostile Java applets is perhaps comparable to the risk of dying from a plane crash; the risk of being infected by opening Word documents is comparable to the risk of dying while crossing a busy freeway on foot.

10) Floating-point numbers are not suitable for financial calculation in which roundoff errors cannot be tolerated. For example, the command System.out.println(2.0 -1.1) prints 0.8999999999999999, not 0.9 as you would expect. Such roundoff errors are caused by the fact that floating-point numbers are represented in the binary number system. There is no precise binary representation of the fraction 1/10, just as there is no accurate representation of the fraction 1/3 in the decimal system. If you need precise numerical computations without roundoff errors, use the BigDecimal class.

11) The right-hand side argument of the shift operators is reduced modulo 32 (unless the left-hand side is a long, in which case the right-hand side is reduced modulo 64).For example, the value of 1 << 35 is the same as 1 << 3 or 8.

12) In jdk1.5 String class introduced one method called codePointAt() which Returns the character (Unicode code point) at the specified index.

13) Relationships between Classes

The most common relationships between classes are

• Dependence (“uses–a”)
• Aggregation (“has–a”)
• Inheritance (“is–a”)

14) All Java objects live on the heap.The just-in-time compiler watches for calls to methods that are short, commonly called, and not overridden, and optimizes them away.

15) The Java programming language always uses call by value.

16) Here is a summary of what you can and cannot do with method parameters in the Java programming language:

• A method cannot modify a parameter of primitive type (that is, numbers or boolean values).
• A method can change the state of an object parameter.
• A method cannot make an object parameter refer to a new object.

17) The return type is not part of the method signature. That is, you cannot have two methods with the same names and parameter types but different return types.

18) In practice, do not rely on the finalize method for recycling any resources that are in short supply—you simply cannot know when this method will be called.

19) Class Design Hints

a. Always keep data private.
b. Always initialize data.
c. Don’t use too many basic types in a class.

The idea is to replace multiple related uses of basic types with other classes. This keeps your classes easier to understand and to change. For example, replace the following
instance fields in a Customer class

private String street;
private String city;
private String state;
private int zip;


with a new class called Address. This way, you can easily cope with changes to addresses, such as the need to deal with international addresses.

d. Not all fields need individual field accessors and mutators.

e. Use a standard form for class definitions.

Probably list the contents of classes in the following order:

public features
package scope features
private features

Within each section, we list:
instance methods
static methods
instance fields
static fields

f. Break up classes that have too many responsibilities.

g. Make the names of your classes and methods reflect their responsibilities.

20) If the superclass has no default constructor and the subclass constructor does not call another superclass constructor explicitly, then the Java compiler reports an error

21) When you override a method, the subclass method must be at least as visible as the superclass method. In particular, if the superclass method is public, then the subclass method must also be declared as public. It is a common error to accidentally omit the public specifier for the subclass method. The compiler then complains that you try to supply a weaker access privilege.

22) In the early days of Java, some programmers used the final keyword in the hope of avoiding the overhead of dynamic binding. If a method is not overridden, and it is short, then a compiler can optimize the method call away—a process called inlining. For example, inlining the call e.getName() replaces it with the field access e.name. This is a worthwhile improvement—CPUs hate branching because it interferes with their strategy of prefetching instructions while processing the current one. However, if getName can be overridden in another class, then the compiler cannot inline it because it has no way of knowing what the overriding code may do.Fortunately, the just-in-time compiler in the virtual machine can do a better job than a traditional compiler. It knows exactly which classes extend a given class, and it can check whether any class actually overrides a given method. If a method is short, frequently called, and not actually overridden, the just-in-time compiler can inline the method. What happens if the virtual machine loads another subclass that overrides an inlined method? Then the optimizer must undo the inlining. That’s slow, but it happens rarely.

23) Here is a summary of the four access modifiers in Java that control visibility:

a. Visible to the class only (private).
b. Visible to the world (public).
c. Visible to the package and all subclasses (protected).
d. Visible to the package—the (unfortunate) default. No modifiers are needed.

24) The Java Language Specification requires that the equals method has the following properties:

a. It is reflexive: For any non-null reference x, x.equals(x) should return true.

b. It is symmetric: For any references x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

c. It is transitive: For any references x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

d. It is consistent: If the objects to which x and y refer haven’t changed, then repeated calls to x.equals(y) return the same value.

e. For any non-null reference x, x.equals(null) should return false.

25) Here is a common mistake when implementing the equals method. Can you spot the problem?


public class Employee
{
public boolean equals(Employee other)
{
return name.equals(other.name)
&& salary == other.salary
&& hireDay.equals(other.hireDay);
}
...
}


This method declares the explicit parameter type as Employee. As a result, it does not override the equals method of the Object class but defines a completely unrelated method.Starting with Java SE 5.0, you can protect yourself against this type of error by tagging methods that are intended to override superclass methods with @Override:

@Override public boolean equals(Object other)

If you made a mistake and you are defining a new method, the compiler reports an error. For example, suppose you add the following declaration to the Employee class:

@Override public boolean equals(Employee other)

An error is reported because this method doesn’t override any method from the Object
superclass.

26) If subclasses have different notions of comparison, then you should outlaw comparison of objects that belong to different classes. Each compareTo method should start out with the test if (getClass() != other.getClass()) throw new ClassCastException();

27) Local classes are never declared with an access specifier (that is, public or private). Their scope is always restricted to the block in which they are declared.

28) Proxies are only necessary when you don’t yet know at compile time which interfaces you need to implement.Suppose you want to construct an object of a class that implements one or more interfaces whose exact nature you may not know at compile time. This is a difficult problem.To construct an actual class, you can simply use the newInstance method or use reflection to find a constructor. But you can’t instantiate an interface. You need to define a new class in a running program.The proxy class can create brand-new classes at runtime.Whenever a method is called on the proxy object, the invoke method of the invocation handler gets called, with the Method object and parameters of the original call. The invocation
handler must then figure out how to handle the call.

29) In the Java programming language, an exception object is always an instance of a class derived from Throwable.The Error hierarchy describes internal errors and resource exhaustion inside the Java runtime system. You should not throw an object of this type. There is little you can do if such an internal error occurs, beyond notifying the user and trying to terminate the program gracefully. These situations are quite rare.The general rule is this: A RuntimeException happens because you made a programming error.Throwing an exception is the same in C++ and in Java, with one small exception.In Java, you can throw only objects of subclasses of Throwable. In C++, you can throw values of any type.

30)
a) Use exceptions for exceptional circumstances only.
b) Do not micromanage exceptions.
c) Make good use of the exception hierarchy.Don’t just throw a RuntimeException.
d) Do not squelch exceptions.
e) Propagating exceptions is not a sign of shame.

31) Generics are—at least on the surface—similar to templates in C++.

32) It would be illegal to have two methods with the same parameter types—here, no parameters. However, in the virtual machine, the parameter types and the return type specify a method. Therefore, the compiler can produce bytecodes for two methods that differ only in their return type, and the virtual machine will handle this situation correctly.

33) Restrictions and Limitations Of Generic Programming

a) Type Parameters Cannot Be Instantiated with Primitive Types
You cannot substitute a primitive type for a type parameter. Thus, there is no Pair,only Pair. The reason is, of course, type erasure. After erasure, the Pair class has fields of type Object, and you can’t use them to store double values.This is an annoyance, to be sure, but it is consistent with the separate status of primitive types in the Java language. It is not a fatal flaw—there are only eight primitive types,and you can always handle them with separate classes and methods when wrapper types are not an acceptable substitute.

b) Runtime Type Inquiry Only Works with Raw Types

Objects in the virtual machine always have a specific nongeneric type. Therefore, all
type inquiries yield only the raw type. For example,

if (a instanceof Pair) // same as a instanceof Pair
really only tests whether a is a Pair of any type.

The same is true for the test
if (a instanceof Pair) // T is ignored

or the cast
Pair p = (Pair) a; // WARNING--can only test that a is a Pair

To remind you of the risk, you will get a compiler warning whenever you use instanceof or cast expressions that involve generic types.In the same spirit, the getClass method always returns the raw type. For example:
Pair stringPair = . . .;
Pair employeePair = . . .;
if (stringPair.getClass() == employeePair.getClass()) // they are equal

The comparison yields true because both calls to getClass return Pair.class.

c) You Cannot Throw or Catch Instances of a Generic Class However, it is ok to use type variables in exception specifications.

The following method is legal:


public static <T extends Throwable> void doWork(T t) throws T // OK
{
try
{
do work
}
catch (Throwable realCause)
{
t.initCause(realCause);
throw t;
}
}


d) Arrays of Parameterized Types Are Not Legal

You cannot declare arrays of parameterized types, such as

Pair[] table = new Pair[10]; // ERROR

What’s wrong with that? After erasure, the type of table is Pair[]. You can convert it to Object[]:

Object[] objarray = table;

An array remembers its component type and throws an ArrayStoreException if you try to
store an element of the wrong type:

objarray[0] = "Hello"; // ERROR--component type is Pair

But erasure renders this mechanism ineffective for generic types. The assignment

objarray[0] = new Pair();

would pass the array store check but still result in a type error. For this reason, arrays of parameterized types are outlawed.

e) You Cannot Instantiate Type Variables

f) Type Variables Are Not Valid in Static Contexts of Generic Classes

You cannot reference type variables in static fields or methods. For example, the following clever idea won’t work:


public class Singleton<T>
{
public static T getSingleInstance() // ERROR
{
if (singleInstance == null) construct new instance of T
return singleInstance;
}
private static T singleInstance; // ERROR
}


If this could be done, then a program could declare a Singleton to share a random number generator and a Singleton to share a file chooser dialog. But it can’t work. After type erasure there is only one Singleton class, and only one singleInstance field.For that reason, static fields and methods with type variables are simply outlawed.

g) Beware of Clashes After Erasure

It is illegal to create conditions that cause clashes when generic types are erased. Here is an example. Suppose we add an equals method to the Pair class, like this:

public class Pair
{
public boolean equals(T value) { return first.equals(value) && second.equals(value); }
. . .
}

Consider a Pair. Conceptually, it has two equals methods:

boolean equals(String) // defined in Pair
boolean equals(Object) // inherited from Object

But the intuition leads us astray. The erasure of the method

boolean equals(T)
is
boolean equals(Object)

which clashes with the Object.equals method.The remedy is, of course, to rename the offending method.The generics specification cites another rule: “To support translation by erasure, we impose the restriction that a class or type variable may not at the same time be a subtype of two interface types which are different parameterizations of the same interface.” For example, the following is illegal:

class Calendar implements Comparable { . . . }

class GregorianCalendar extends Calendar implements Comparable
{ . . . } // ERROR

h) Inheritance Rules for Generic Types

When you work with generic classes, you need to learn a few rules about inheritance and subtypes. Let’s start with a situation that many programmers find unintuitive. Consider a class and a subclass, such as Employee and Manager. Is Pair a subclass of Pair? Perhaps surprisingly, the answer is “no.”

For example, the following code will not compile:

Manager[] topHonchos = . . .;
Pair result = ArrayAlg.minmax(topHonchos); // ERROR

The minmax method returns a Pair, not a Pair, and it is illegal to assign one to the other.

About the Authors
Cay S. Horstmann has written many books on C++, Java and object-oriented development, is the series editor for Core Books at Prentice-Hall and a frequent speaker at computer industry conferences. For four years, Cay was VP and CTO of an Internet startup that went from 3 people in a tiny office to a public company. He is now a computer science professor at San Jose State University .

Gary Cornell has authored or co-authored 14 popular computer books and articles for many developer magazines. Gary is a professor at the University of Connecticut and one of the founders of the Apress publishing company.

Hope you enjoy reading this book.

No comments: