Wednesday, 2 July 2008

Java™ 2 Primer Plus By Steven Haines, Steve Potts

Just now i finished reading Java™ 2 Primer Plus Book By Steven Haines, Steve Potts.

Nice book written by Steven Haines and Steve Potts.

While for freshers new to java programmers this can be useful but for experience programmers this book will be like McDonald's Kids Meal :-)

I wanted to share few important points i found from this book.

1) The following is a short history of the Java programming language and the reasons for its inception. In 1991, a research group working as part of Sun Microsystems's "Green" project, was developing software to control consumer electronic devices. The goal was to develop a programming language that could be used to control and network "smart" devices, such as televisions, toasters, and even buildings. These devices would all coexist and communicate with one another.

The first prototype that Sun came out with was a device called the Star7—a device, similar to a remote control, that could communicate with other Star7 devices. The initial intent was to use C++ to control the Star7, but as a result of frustration with that language, Green project member James Gosling developed a new language called Oak to control the Star7. The title Oak came from a tree that Gosling could see from his office window while developing the language. Sun later replaced the name with Java because Oak was already being used.

As a result of Oak, or Java, being designed to run on small appliances, the language had the following inherent benefits:

It was small, so it could run on the limited memory of small appliances.

It was efficient and reliable, so it could function as a small appliance—we are all used to computer crashes, but a microwave oven crash is not acceptable.

It was portable, so it could run on different pieces of hardware.

In 1994, the members of the Green project developed a World Wide Web (WWW) browser completely in Java that could run Java applets to demonstrate the power of the language. The browser was originally called WebRunner, but is now known as HotJava. Java came alive in 1995, however, when Netscape licensed the Java programming language and included support for it in its Navigator product.

In 1997, Sun released the Servlet API, which revolutionized server-side Web development and moved it away from monolithic CGI scripts or proprietary solutions. In 1999, Sun released the first version of the Java 2, Enterprise Edition (J2EE) specification that included JavaServer Pages (JSP) and Enterprise JavaBeans (EJB) in a highly distributed enterprise middleware. Since then the J2EE specification, along with the JSP, Servlet, and EJB specifications, have evolved into a very powerful programming paradigm.

2) All mathematical operations in Java are performed by promoting each operand in the operation to a specific data type, following these rules in this order:

If any of the operands is of type double, the other one will by converted to a double.

If any of the operands is of type float, the other one will be converted to a float.

If any of the operands is of type long, the other one will be converted to a long.

Otherwise all operands will be converted in ints

3) The rule for conversion between primitive numeric types is that a type can be assigned to a wider type (one with more bytes), but not a narrower type (one with less bytes). So, the following conversions are permissible by the compiler:

byte—short, int, long, float, double

short—int, long, float, double

int—long, float, double

long—float, double

float—double

char—int

4) The primary use for bit-wise operations originated in the data compression and communication applications.

5) A final note about method signatures is that although the return value is part of the signature, it cannot be the differentiating factor that results in overloaded methods. The following two methods cannot be defined in the same Java class:

6) If Java is managing your memory, can you do anything to cleanup your objects before they are deleted from memory? This question is derived from my C++ background, and a C++ programming practice known as smart objects. The general concept is that you create a smart object that wraps any resource you are using, for example a handle to file; you open the file in the constructor, and then close the file in the destructor (the C++ class method that is called when an object is deleted). This programming paradigm ensures that resources are never lost; a file that is opened is always closed.

Java does not have destructors, per se, but it does have a similar construct known as a finalizer. Classes can define a finalize method that can be called when an object is deleted from memory. Finalization must be explicitly enabled by calling the System class's runFinalization() method. This method call only suggests that the garbage collector call the finalize method on objects that are targeted for garbage collection before reclaiming memory.

7) Inner classes defined inside a method have some limitations:

They cannot be declared with an access modifier

They cannot be declared static

Inner classes with local scope can only access variables of the enclosing method that are declared final, referring to a local variable of the method or an argument passed into the enclosing method

8) Static Inner Classes
Inner classes, such as class variables and methods, can be declared to be static. Because they are static, they are not associated with an instance of an outer class. This means that you can create an instance of the inner class without having to create an instance of the outer class. Static inner classes have some limitations regarding accessing the outer class's methods:

Methods of a static inner class cannot access instance variables of the outer class

Methods of a static inner class can only access static variables of the outer class

9) Java supports single inheritance (one super class), and then works around the problem by allowing you to implement as many interfaces as you need. Because interfaces cannot provide any implementation, there is no ambiguity in which implementation of a method to execute. In some situations you might have to write more code because of this restriction, but it does solve a lot of problems.

10) The wrapper classes have a very unique characteristic in that they are immutable

11) Java provides a series of what Filter Streams that help you work with streams; specifically, they provide extra functionality to preprocess output before actually writing the data to an output stream or postprocess input after data has been read. To define in more practical terms what this means, consider System.out in light of java.io.OutputStream. Writing text-readable characters to an output stream involves writing a collection of bytes, not a collection of characters, so the PrintStream class is provided that enables you to write characters to it and it writes bytes to the destination.

The way that filtered streams work is that you pass an output stream to the constructor of a filtered stream, and then you can use the filtered stream instead of the output stream. This enables you to use the filtered stream's methods instead of the original stream's methods; if you choose the correct filtered stream, it will be easier for you to write your data out to the stream.

12) A thread is a type of subprocess that is managed by the main process, not by the operating system. Threads contain their own copies of local variables, their own program counter, and their own life cycle. They do not have nearly the overhead in creation and destruction that full processes do.

The reasons that we want to run more than one thread in the same program are

Some tasks can't be performed without threads. For example, if you press play to run an animation in a window, you need a stop button to halt it. If the only thread is busy running the animation, there is no thread available to notice that the stop button was pressed.

Some tasks can be done in the background, enabling the user to perform other tasks. In old-fashioned word processors, you couldn't do any work while a document was printing. Modern word processors normally perform this task in the background.

Some tasks are naturally multithreaded. Video with sound requires one thread to play the video and another to play the sound.

Some simulations and game programs attempt to imitate the real world by having a lot of action taking place at the same time. Real-time strategy games such as Microsoft's "Age of Empires" or Blizzard's "WarCraft III" are the most popular games of this genre.

Some tasks can be subdivided and processed in parallel. Selecting all the rows in a database that have the word "Smith" in the last name field is an example of this. If the database has one million rows, four threads could each process a portion of the data and combine the results at the end. This could result in a significant reduction in the amount of wall-clock time needed to complete a query

13) Interrupting a Thread

Sometimes logic of a program dictates that a sleeping thread be interrupted. For example, you might put a thread to sleep when a queue is empty. When another process observes that the queue has new items in it, it could interrupt the sleeping thread and cause the thread to resume its processing.

14) Prior to JDK 1.2, it was permissible to stop a thread at any time by issuing the stop() command. This approach was deemed unreliable because it led to corrupted objects in some circumstances. As a result of these problems, the stop() method was deprecated in JDK 1.2 and later.

This doesn't mean that you cannot stop a thread from running; it just means that you need to find a way to allow the program to terminate gracefully.


public class TestStop extends Thread
{
private volatile boolean stopping;
private Thread secondThread;

/** Creates a new instance of TestStop */
public TestStop()
{
}

public void run()
{
secondThread = Thread.currentThread();
stopping = false;

int counter = 0;

while( !stopping)
{
System.out.println("counter = " + counter);
counter++;

try
{
Thread.sleep(1000);
}catch (InterruptedException ie)
{
System.out.println("Sleep interrupted in run()");
}

}
}

public void stopIt()
{
this.stopping = true;
}

public static void main(String[] args)
{
TestStop ts = new TestStop();
Thread t = new Thread(ts);
t.start();

//Delay for a few seconds to let the other thread get going
try
{
Thread.sleep(2500);
}catch (InterruptedException ie)
{
System.out.println("Sleep interrupted in main()");
}

System.out.println("About to stop the other thread");
ts.stopIt();
System.out.println("Exiting from Main");

}
}



15) There are four different types of JDBC drivers to choose from; some offering better performance than the others:

Type 1— This driver connects to the DBMS by using a datasource that has been defined in a MS Windows ODBC manager. In the early days of JDBC, there were not many drivers available, so it was common to piggyback on existing ODBC drivers to access the data. Now that more advanced drivers are widely available, this driver is mostly used in examples and simple systems. It suffers from additional overhead introduced by having the extra ODBC layer in the solution.

Type 2— These drivers make method calls in other languages to networking software installed on the client machine. The performance of this driver is better, but the distribution of your application is more complex because you must ensure that the network software is installed on every client machine.

Type 3— These drivers are written in 100% Java on the client side. On the server side, there is a component that the client communicates with. This removes the requirement that every client have an extra piece of software and moves that requirement to the server.

Type 4— This is the easiest type of driver to install and use. It is written in Java and contains networking code right inside its classes. No additional installation is necessary on either the client or server.

16) Sometimes we think of TCP/IP as a protocol, but it is really a suite of protocols. Combinations of these protocols work together to transfer data from one computer to another. The name, TCP/IP, comes from two of the most frequently used protocols in the suite, the Transmission Control Protocol(TCP) and the Internet Protocol(IP).

To understand how TCP/IP works, you can think of the different protocols as separate APIs, or more commonly, layers. The layered diagrams sometimes confuse programmers. If you think of them as different level APIs, you will come closer to understanding them. Each layer, except the Network Access Layer, makes calls to the services provided by the layer below it. (The Network Access Layer makes calls to the hardware.) Each layer, except the application layer, returns data to the layer above it.

Another point of confusion comes by thinking that the Network Access Layer is made up of a single product or protocol. In reality, many different technologies are combined to perform the duties of this layer. Network cards have drivers that are called by routing software, and so forth.

The Application Layer can also be very complicated. Some application layers contain hundreds of servlets, JSPs, EJBs, and just about every other technology on the market

The layers in this model are

Application layer— This layer can be as simple as a file transfer program, or it can as complex as an B2B application.

Transport layer— This layer sends a set of data from one machine to another with data integrity and high reliability.

Internetwork layer— This layer makes calls to pass "buckets" of data called datagrams from one computer to another and another and another until the final destination computer is reached.

Network Access layer— This layer exchanges frames of data with other computers or routing devices on the same network.

17) The top layer in the model is called the Application layer. This layer normally provides services such as encryption, compression, decryption, and decompression.

18) The Transport Layer
The primary responsibility of the Transport layer is to make sure that all the data gets to the other computer. This is done by numbering each packet sequentially before sending it. The Transport software on the other computer takes an inventory of the packets as they arrive. If any of them get lost in transit, it requests that the missing packet be resent.

The Application layer hands the data to the Transport layer as a stream. The Transport layer subdivides the data into packets and its counterpart on the other machine turns it back into a stream.

19) The Internetwork Layer
The Internetwork (IP) layer is responsible for the delivery of the packets to the computer whose address they contain. It does this by talking to its IP layer counterparts on every computer that the data passes through on the way. The addressing scheme in the form 121.14.27.1 tells each computer what computer to send the data to next. At each hop along the way, the IP layer has to decide whether the packet was intended for this computer. If not, it has to decide which other computer that it is directly connected to will provide the best route to the packet's final destination.

The packet is broken into datagrams, which are a kind of minipacket. Each datagram contains part of the packet. When all the datagrams for one packet arrive at the destination computer, they are reassembled into a packet and handed to the transport layer.

A datagram is a string of characters that is made up of a header, the data, and a trailer. The header contains the IP addresses of both the source and the destination along with some security information. The trailer normally contains a checksum that is used to verify that accidental corruption has not occurred.

This layer has no concept of a session. To the IP layer, a datagram is forgotten once it is sent. If a broken datagram arrives, it is discarded and the packet that it belongs to will be broken, too. The Transport layer will notice the broken packet and request a resend.

20) Whether more than one instance of a single servlet is in memory depends on whether it is declared to be thread-safe. A servlet is assumed to be thread-safe unless it implements the SingleThreadModel interface. If it implements this interface, a new instance will be created for each simultaneous access. This has serious performance penalties associated with it, so it should only be done if absolutely necessary.

21) Advantage of JSP Compared to Servlets

JSP is simpler to read and understand. The JSP syntax is a small subset of the Java language that you find in most Java programs.

JSP removes the presentation logic from the communication logic. Servlets contain logic to manage the communication as well as that of the presentation. Normally, JSP contains only presentation logic.

JSP can separate the presentation from the business logic if component-based techniques are used.

JSP supports a division of labor between the presentation person and the Web server programmer. An HTML programmer can become proficient in JSP in less than half the time that it would take to learn how to program servlets. This enables the team to be separated into the presentation programmers using JSP, and the business-layer programmers who write components in Java to be used by the JSP programmers.

22) A protocol is simply a published agreement between clients and servers that specifies what data will be passed from one party to the other and what syntax it will be in.


Hope you enjoy reading the book.

About the Authors

Steve Haines has worked in the enterprise software industry for the past eight years and has been focusing on Java since 1997. He has been filling key architectural roles in the areas of B2B e-commerce, high-speed Internet marketing, application monitoring and diagnosis, and robust client and server-side image layout and management over the past few years. He is currently the J2EE Domain Architect for Quest Software and is responsible for defining the expert rules for tuning and monitoring Enterprise Java applications and application servers.

He is the author of Que Publishing's Java 2 from Scratch and has numerous articles on InformIT.com in the areas of Java Swing and Enterprise Java. He shares author credits on Java Web Services Unleashed, C++ Unleashed, Sams Teach Yourself C++ in 21 Days, and Sams Teach Yourself Java in 21 Days. He has also worked as a technical editor for Pearson Education in areas of Java, Enterprise Java, Network Communications, C++, and video-game programming. Steve has taught all aspects of Java programming from basic certification training through Database, Web Development, and Enterprise JavaBeans at Learning Tree University (LTU). Steve recently enrolled in a Bachelor's of Biblical Studies at Calvary Chapel Bible College.

Steve Potts is an independent consultant, author, and Java instructor in Atlanta, Georgia. Steve received his Computer Science degree in 1982 from Georgia Tech. He has worked in a number of disciplines during his 20-year career, with manufacturing being his deepest experience. Steve has consulted for such companies as Home Depot, Disney, and IBM. His previous books include Java Unleashed and Java 1.2 How-To. He can be reached via email at stevepotts@mindspring.com.

No comments: