Posted by: javawebworld | April 30, 2009

Technorati

Technorati Profile

Posted by: javawebworld | December 11, 2008

Overview of JAVA

Java or formally known as Oak is now considered as one of the top programming methodologies to come about in the programming world. It is an object-oriented programming language was developed by Sun Microsystems in the early 1990s. The language derives most of its syntax from other objected oriented languages like C and C++ but has a simpler object model and fewer low-level facilities.
It was started as a small project which was called “Oak” by James Gosling in 1991. The first public implementation was done in the year 1995 which was called Java 1.0. At that moment of time it offered the following new attributes to the programming world.
• WORA: Ability to “Write Once, Run Anywhere” providing no cost runtimes on popular platforms.
• Security: It was configurable, allowing network and file access to be restricted.
The original compliers virtual machines and class libraries were developed by Sun from 1995.But as of May 2007, in compliance with the specifications of the Java Community Process, most of their Java technologies as free software under the GNU General Public License. Some organizations have also developed alternative implementations of these technologies, like the GNU Compiler for Java and GNU Classpath etc.

Posted by: javawebworld | December 11, 2008

Working of Java

All the applications developed are first complied into a JVM (Java virtual machine) irrespective of the computer architecture. This complied code is referred as byte code.

Posted by: javawebworld | December 11, 2008

Primary Goals

There were five primary goals in the creation of the Java language:
1. It should be “simple, object oriented and familiar”.
2. It should be “robust and secure”.
3. It should be “architecture neutral and portable”.
4. It should execute with “high performance”.
5. It should be “interpreted, threaded, and dynamic”.

After its launch, major web browsers soon incorporated the ability to run secure Java applets within web pages, and Java quickly became popular. With the advent of Java 2 the new versions had multiple configurations built for different types of platforms. For example, J2EE targeted enterprise applications and the greatly stripped-down version J2ME for mobile applications.

Posted by: javawebworld | December 11, 2008

Future of Java

It is still the de facto standard that it was, controlled through the Java Community Process.

The latest version of Java currently in the market is the Java Standard Edition 6 (Update 11). Java is a very popular programming language. The newer versions of the java programming language have multiple configurations built for different platforms for example, J2EE for enterprise applications and J2ME for mobile applications etc.

Posted by: javawebworld | November 6, 2008

Java Libraries

Posted by: javawebworld | November 6, 2008

How to write a Java Application without a main method

You can write a runnable Java program which does not have main method at all. This can be done using the static block of the class.

The reason this works is that static initialization blocks get executed as soon as the class is loaded, even before the main method is called. During run time JVM will search for the main method after exiting from this block. If it does not find the main method, it throws an exception. To avoid the exception System.exit(0); statement is used which terminates the program at the end of the static block itself.

class MainMethodNot
{
static
{
System.out.println("This java program have run without the run method");
System.exit(0);

}
}

Posted by: javawebworld | November 6, 2008

Enhanced For-Loop and Preferences API

Welcome to the Core Java Technologies Tech Tips for November 2008. Core Java Technologies Tech Tips provides tips and hints for using core Java technologies and APIs in the Java Platform, Standard Edition 6 (Java SE 6).

Using Enhanced For-Loops with Your Classes

The enhanced for-loop is a popular feature introduced with the Java SE platform in version 5.0. Its simple structure allows one to simplify code by presenting for-loops that visit each element of an array/collection without explicitly expressing how one goes from element to element.

Because the old style of coding didn’t become invalid with the new for-loop syntax, you don’t have to use an enhanced for-loop when visiting each element of an array/collection. However, with the new style, one’s code would typically change from something like the following:

for (int i=0; i<array.length; i++) {
System.out.println("Element: " + array[i]);
}

to the newer form:

for (String element : array) {
System.out.println("Element: " + element);
}

Assuming “array” is defined to be an array of String objects, each element is assigned to the element variable as it loops through the array. These basics of the enhanced for-loop were covered in an earlier Tech Tip: The Enhanced For Loop, from May 5, 2005.

If you have a class called Colony which contains a group of Penguin objects, without doing anything extra to get the enhanced for-loop to work, one way you would loop through each penguin element would be to return an Iterator and iterate through the colony. Unfortunately, the enhanced for-loop does not work with Iterator, so the following won’t even compile:

// Does not compile
import java.util.*;
public class BadColony {
static class Penguin {
String name;
Penguin(String name) {
this.name = name;
}
public String toString() {
return "Penguin{" + name + "}";
}
}

Set<Penguin> set = new HashSet<Penguin>();

public void addPenguin(Penguin p) {
set.add(p);
}

public Iterator<Penguin> getPenguins() {
return set.iterator();
}

public static void main(String args[]) {
Colony colony = new Colony();
Penguin opus = new Penguin("Opus");
Penguin chilly = new Penguin("Chilly Willy");
Penguin mumble = new Penguin("Mumble");
Penguin emperor = new Penguin("Emperor");
colony.addPenguin(opus);
colony.addPenguin(chilly);
colony.addPenguin(mumble);
colony.addPenguin(emperor);
Iterator<Penguin> it = colony.getPenguins();
// The bad line of code:
for (Penguin p : it) {
System.out.println(p);
}
}
}

You cannot just pass an Iterator into the enhanced for-loop. The 2nd line of the following will generate a compilation error:

Iterator<Penguin> it = colony.getPenguins();
for (Penguin p : it) {

The error:

BadColony.java:36: foreach not applicable to expression type
for (Penguin p : it) {
^
1 error

In order to be able to use your class with an enhanced for-loop, it does need an Iterator, but that Iterator must be provided via the Iterable interface:

public interface java.lang.Iterable {
public java.util.Iterator iterator();
}

Actually, to be more correct, you can use a generic T, allowing the enhanced for-loop to avoid casting, returning the designated generic type, instead of just a plain old Object.

public interface java.lang.Iterable<T> {
public java.util.Iterator<T> iterator();
}

It is this Iterable object which is then provided to the enhanced for loop. By making the Colony class implement Iterable, and having its new iterator() method return the Iterator that getPenguins() provides, you’ll be able to loop through the penguins in the colony via an enhanced for-loop.

By adding the proper implements clause:

public class Colony implements Iterable<Colony.Penguin> {

You then get your enhanced or loop for the colony:

for (Penguin p : colony) {

Here’s the updated Colony class with the corrected code:

import java.util.*;

public class Colony implements Iterable<Colony.Penguin> {

static class Penguin {
String name;
Penguin(String name) {
this.name = name;
}
public String toString() {
return "Penguin{" + name + "}";
}
}

Set<Penguin> set = new HashSet<Penguin>();

public void addPenguin(Penguin p) {
set.add(p);
}

public Iterator<Penguin> getPenguins() {
return set.iterator();
}

public Iterator<Penguin> iterator() {
return getPenguins();
}

public static void main(String args[]) {
Colony colony = new Colony();
Penguin opus = new Penguin("Opus");
Penguin chilly = new Penguin("Chilly Willy");
Penguin mumble = new Penguin("Mumble");
Penguin emperor = new Penguin("Emperor");
colony.addPenguin(opus);
colony.addPenguin(chilly);
colony.addPenguin(mumble);
colony.addPenguin(emperor);
for (Penguin p : colony) {
System.out.println(p);
}
}
}

Running the code produces the following output:

> java Colony

Penguin{Chilly Willy}
Penguin{Mumble}
Penguin{Opus}
Penguin{Emperor}

Keep in mind that the individual penguins are internally kept in a Set type collection so the returned order doesn’t necessarily match the insertion order, which in this case it doesn’t.

Remember to genericize the implements clause for the class “implements Iterable<T>” and not just say “implements Iterable“. With the latter, the enhanced for-loop will only return an Object for each element.

For more information on the enhanced for-loop, please see the Java Programming Language guide from JDK 1.5

Beyond Preferences API Basics

The Preferences API was first covered here shortly after it was introduced with the 1.4 version of the standard platform: the July 15, 2003 article, the Preferences API.

That article described how to get and set user specific preferences. There is more to the Preferences API than just getting and setting user specific settings. There are system preferences, import and export preferences, and event notifications associated with preferences. There is even a way to provide your own custom location for storage of preferences. The first three options mentioned will be described here. Creating a custom preferences factory will be left to a later tip.

System Preferences

The Preferences API provides for two separate sets of preferences. The first set is for the individual user, allow multiple users on the same machine to have different settings defined. These are called user preferences. Each user who shares the same machine can have his or her own unique set of values associated with a group of preferences. Something like this could be like a user password or starting directory. You don’t want every person on the same machine to have the same password and home directory. Well, I would hope you don’t want that.

The other form of preferences is the system type. All users of a machine share the same set of system preferences. For instance, the location of an installed printer would typically be a system preference. You wouldn’t necessarily have a different set of printers installed for different users. Everyone running on one machine would know about all printers known by that machine.

Another example of a system preference would be the high score of a game. There should only be one overall high score. That’s what a system preference would be used for. In the previous tip you saw how userNodeForPackge() — and subsequently userRoot() — was used to acquire the user’s preference node, the following example shows how to get the appropriate part of the system preferences tree with systemNodeForPackage() — or systemRoot() for the root. Other than the method call to get the right preference node, the API usage is identical.

The example is a simple game, using the game term loosely here. It picks a random number from 0 to 99. If the number is higher than the previously saved number, it updates the “high score.” The example also shows the current high score. The Preferences API usage is rather simple. The example just gets the saved value with getSavedHighScore(), providing a default of -1 if no high score had been saved yet, and updateHighScore(int value) to store the new high score. The HIGH_SCORE key is a constant shared by the new Preferences API accesses.

private static int getSavedHighScore() {
Preferences systemNode = Preferences.systemNodeForPackage(High.class);
return systemNode.getInt(HIGH_SCORE, -1);
}

private static void updateHighScore(int value) {
Preferences systemNode = Preferences.systemNodeForPackage(High.class);
systemNode.putInt(HIGH_SCORE, value);
}

Here’s what the whole program looks like:

import java.util.*;
import java.util.prefs.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class High {
static JLabel highScore = new JLabel();
static JLabel score = new JLabel();
static Random random = new Random(new Date().getTime());
private static final String HIGH_SCORE = "High.highScore";

public static void main (String args[]) {
/* -- Uncomment these lines to clear saved score
Preferences systemNode = Preferences.systemNodeForPackage(High.class);
systemNode.remove(HIGH_SCORE);
*/

EventQueue.invokeLater(
new Runnable() {
public void run() {
JFrame frame = new JFrame("High Score");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
updateHighScoreLabel(getSavedHighScore());
frame.add(highScore, BorderLayout.NORTH);
frame.add(score, BorderLayout.CENTER);
JButton button = new JButton("Play");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
int next = random.nextInt(100);
score.setText(Integer.toString(next));
int old = getSavedHighScore();
if (next > old) {
Toolkit.getDefaultToolkit().beep();
updateHighScore(next);
updateHighScoreLabel(next);
}
}
};
button.addActionListener(listener);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
);
}

private static void updateHighScoreLabel(int value) {
if (value == -1) {
highScore.setText("");
} else {
highScore.setText(Integer.toString(value));
}
}

private static int getSavedHighScore() {
Preferences systemNode = Preferences.systemNodeForPackage(High.class);
return systemNode.getInt(HIGH_SCORE, -1);
}

private static void updateHighScore(int value) {
Preferences systemNode = Preferences.systemNodeForPackage(High.class);
systemNode.putInt(HIGH_SCORE, value);
}
}

And, here’s what the screen looks like after a few runs. The 61 score is not apt to be your high score, but it certainly could be.

High Score 61

High Score 61

You can try running the application as different users to see that they all share the same high score.

Import and Export

In the event that you wish to transfer preferences from one user to another or from one system to another, you can export the preferences from that one user/system, and then import them to the other side. When preferences are exported, they are exported into an XML formatted document whose DTD is specified by http://java.sun.com/dtd/preferences.dtd, though you don’t really need to know that. You can export either a whole subtree with the exportSubtree() method or just a single node with the exportNode() method. Both methods accept an OutputStream argument to specify where to store things. The XML document will be UTF-8 character encoded. Importing of the data then happens via the importPreferences() method, which takes an InputStream argument. From an API perspective, there is no difference in importing a system node/tree or a user node.

Adding a few lines of code to the previous example will export the newly updated high score to the file high.xml. Much of the added code is responsible for launching a new thread to save the file and for handling exceptions. There are only three lines to export the single node:

Thread runner = new Thread(new Runnable() {
public void run() {
try {
FileOutputStream fis = new FileOutputStream("high.xml");
systemNode.exportNode(fis);
fis.close();
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
Toolkit.getDefaultToolkit().beep();
Toolkit.getDefaultToolkit().beep();
}
}
});
runner.start();

When exported, the file will look something like the following:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="system">
<map/>
<node name="<unnamed>">
<map>
<entry key="High.highScore" value="95"/>
</map>
</node>
</root>
</preferences>

Notice the root element has a type attribute that says “system“. This states the type of node it is. The node also has a name attribute valued at “<unnamed>“. Since the High class was not placed in a package, you get to work in the unnamed system node area. The entry attribute provide the current high score value, 95 in the example here, though your value could differ.

While we won’t include any import code in the example here, the way to import is just a static method call on Preferences, passing in the appropriate input stream:

FileInputStream fis = new FileInputStream("high.xml");
Preferences.importPreferences(fis);
fis.close();

Since the XML file includes information about whether the preferences are system or user type, the import call doesn’t have to explicitly include this bit of information. Besides the typical IOExceptions that can happen, the import call will throw an InvalidPreferencesFormatException if the file format is invalid. Exporting can also throw a BackingStoreException if the data to export can’t be read correctly from the backing store.

Event Notifications

The original version of the High game updated the high score preference, then explicitly made a call to update the label on the screen. A better way to perform this action would be to add a listener to the preferences node, then a value change can automatically trigger the label to update its value. That way, if the high score is ever updated from multiple places, you won’t need to remember to add code to update the label after saving the updated value.

The two lines:

updateHighScore(next);
updateHighScoreLabel(next);

can become one with the addition of the right listeners.

updateHighScore(next);

There is a PreferenceChangeListener and its associated PreferenceChangeEvent for just such a task. The listener will be notified for all changes to the associated node, so you need to check for which key-value pair was modified, as shown here.

PreferenceChangeListener changeListener =
new PreferenceChangeListener() {

public void preferenceChange(PreferenceChangeEvent e) {
if (HIGH_SCORE.equals(e.getKey())) {
String newValue = e.getNewValue();
int value = Integer.valueOf(newValue);
updateHighScoreLabel(value);
}
}
};
systemNode.addPreferenceChangeListener(changeListener);

The PreferenceChangeEvent has three important properties: the key, new new value, and the node itself. The new value doesn’t have all the convenience methods of Preferences though. For example, you can’t retrieve the value as an int. Instead you must manually convert the value yourself. Here’s what the modified High class looks like:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.prefs.*;
import javax.swing.*;

public class High {
static JLabel highScore = new JLabel();
static JLabel score = new JLabel();
static Random random = new Random(new Date().getTime());
private static final String HIGH_SCORE = "High.highScore";
static Preferences systemNode =
Preferences.systemNodeForPackage(High.class);

public static void main (String args[]) {
/* -- Uncomment these lines to clear saved score
systemNode.remove(HIGH_SCORE);
*/

PreferenceChangeListener changeListener =
new PreferenceChangeListener() {

public void preferenceChange(PreferenceChangeEvent e) {
if (HIGH_SCORE.equals(e.getKey())) {
String newValue = e.getNewValue();
int value = Integer.valueOf(newValue);
updateHighScoreLabel(value);
}
}
};
systemNode.addPreferenceChangeListener(changeListener);

EventQueue.invokeLater(
new Runnable() {
public void run() {
JFrame frame = new JFrame("High Score");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
updateHighScoreLabel(getSavedHighScore());
frame.add(highScore, BorderLayout.NORTH);
frame.add(score, BorderLayout.CENTER);
JButton button = new JButton("Play");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
int next = random.nextInt(100);
score.setText(Integer.toString(next));
int old = getSavedHighScore();
if (next > old) {
Toolkit.getDefaultToolkit().beep();
updateHighScore(next);
}
}
};
button.addActionListener(listener);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
);
}

private static void updateHighScoreLabel(int value) {
if (value == -1) {
highScore.setText("");
} else {
highScore.setText(Integer.toString(value));
}
}

private static int getSavedHighScore() {
return systemNode.getInt(HIGH_SCORE, -1);
}

private static void updateHighScore(int value) {
systemNode.putInt(HIGH_SCORE, value);
// Save XML in separate thread
Thread runner = new Thread(new Runnable() {
public void run() {
try {
FileOutputStream fis = new FileOutputStream("high.xml");
systemNode.exportNode(fis);
fis.close();
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
Toolkit.getDefaultToolkit().beep();
Toolkit.getDefaultToolkit().beep();
}
}
});
runner.start();
}
}

Posted by: javawebworld | October 10, 2008

JAVA: A Beginner’s Guide


googlecb2cccaf0c20f8b8.html
Java is an object-oriented programming language developed by Sun Microsystems, a company best known for its high-end Unix workstations. Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level.

The Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devices-television sets, VCRs, toasters, and the other sorts of machines you can buy at any department store. Java’s goals at that time were to be small, fast, efficient, and easily portable to a wide range of hardware devices. It is those same goals that made Java an ideal language for distributing executable programs via the World Wide Web, and also a general-purpose programming language for developing programs that are easily usable and portable across different platforms. This is the major reason why Java is said to be the most successful platform independent language.

Java as a language has significant advantages over other languages and other programming environments that make it suitable for just about any programming task. Some of them are listed below:

Applets
Applets appear in a Web page much in the same way as images do, but unlike images, applets are   dynamic and interactive. Applets can be used to create animations, figures, or areas that can respond to input from the reader, games, or other interactive effects on the same Web pages among the text and graphics. Java enabled browsers can successfully run applets and thus give a truly rich experience at the user end.

Platform Independence
Platform independence is one of the most significant advantages that Java has over other programming languages, particularly for systems that need to work on many different platforms. Java is platform-independent at both the source and the binary level. Platform-independence is a program’s capability of moving easily from one computer system to another. Java binary files called byte-codes are also platform-independent and can run on multiple platforms without the need to recompile the source. Byte-codes are a set of instructions that look a lot like machine code, but are not specific to any one processor. Because of them, compilation happens just once; interpretation occurs each time the program is executed. Java byte-codes help make “write once, run anywhere” possible.

Simplicity
In addition to its portability and object-orientation, one of Java’s initial design goals was to be small and simple, and therefore easier to write, easier to compile, easier to debug, and, best of all, easy to learn. Keeping the language small also makes it more robust because there are fewer chances for programmers to make difficult-to-find mistakes. Despite its size and simple design, however, Java still has a great deal of power and flexibility.

Better Cousin of C, C++
Java is modeled after C and C++, and much of the syntax and object-oriented structure is borrowed from the latter. If you are familiar with C++, learning Java will be particularly easy for you, because you have most of the foundation already. Although Java looks similar to C and C++, most of the more complex parts of those languages have been excluded from Java, making the language simpler without sacrificing much of its power. There are no pointers in Java, nor is there pointer arithmetic. Strings and arrays are real objects in Java. Memory management is automatic. To an experienced programmer, these omissions may be difficult to get used to, but to beginners or programmers who have worked in other languages; they make the Java language far easier to learn.

Object Oriented Programming
Java is object-oriented programming (OOP) technique, which is merely a way of organizing programs for creating flexible, modular programs and reusing code. . Like most object-oriented programming languages, Java includes a set of class libraries that provide basic data types, system input and output capabilities, and other utility functions. Because these class libraries are written in Java, they are portable across platforms as all Java applications are.

Applets and Applications
The most common types of programs written in the Java programming language are applets and applications. If you’ve surfed the Web, you’re probably already familiar with applets. An applet is a program that adheres to certain conventions that allow it to run within a Java-enabled browser.

An application is a standalone program that runs directly on the Java platform. A special kind of application known as a server serves and supports clients on a network. Examples of servers are Web servers, proxy servers, mail servers, and print servers. Another specialized program is a servlet. A servlet can almost be thought of as an applet that runs on the server side. Java Servlets are a popular choice for building interactive web applications, replacing the use of CGI scripts. Servlets are similar to applets in that they are runtime extensions of applications. Instead of working in browsers, though, servlets run within Java Web servers, configuring or tailoring the server.

Full implementation of the Java platform provides the essentials like objects, strings, threads, numbers, input and output, data structures, system properties, date and time. Both, low and high level security, including electronic signatures, public and private key management, access control, and certificates are provided by java platform. Networking management, Java Database Connectivity (JDBC), Remote Method Invocation (RMI) are some of the other features of Java.

Posted by: javawebworld | September 22, 2008

One Liner For JAVA

Java is the most distressing thing to happen to computing since MS-DOS !!

If Java had true garbage collection, most programs would delete themselves upon execution.

I fear the the new object-oriented systems may suffer the fate of LISP, in that they can do many things, but the complexity of the class hierarchies may cause them to collapse under their own weight.

Claiming Java is easier than C++ is like saying that K2 is shorter than Everest.

Java is the SUV of programming tools.

If you learn to program in Java, you’ll never be without a job!

Knowing the syntax of Java does not make someone a software engineer.

Older Posts »

Categories

Follow

Get every new post delivered to your Inbox.