JAVA-MANI.BLOGSPOT.COM
Monday, June 30, 2008
Java programming language was intended to serve as a novel way to manage software complexity. Many consider Java technology to deliver reasonably well on this promise. However, Java is not without flaws, and it does not universally accommodate all programming styles, environments, or requirements.

Class path

Running a Java program requires all third party supporting libraries to be in the class path. This can be an obstacle to portability, because its syntax is platform-specific: Windows-based systems use backslashes to mark subdirectories and semicolons to separate entries, whereas all other platforms use forward slashes to mark subdirectories and colons to separate entries.

It is also necessary for each .jar or .zip archive required to be explicitly named in the class path. Java provides a way around this by allowing directories listed in the class path to end in an asterisk (*), which will be expanded to the names of all files ending in .jar or .JAR within the directory. However, such an entry does not match .zip or .class files within that directory.

License

Sun Java's proprietary nature gave it a controversial position in the free software community. Because Sun's implementation of Java was not free software, it could not be included in projects that require a free software or GPL-compatible license, such as Debian main, the $100 laptop, and Fedora Core. Sun announced in JavaOne 2006 that Java will become open source software. The statement was issued by Sun Software Executive Vice President Rich Green: "It's not a question of whether, it's a question of how, and so we'll go do this."

In July 2006, Sun's CTO Robert Brewin commented that Java will be partially open source by June 2007 but the entire platform will take more time to be fully open source. On November 13, 2006, Sun announced that its standard edition Java runtime environment will be released under the GPL by March of 2007. Its source code will be available under the GPL. According to Richard Stallman, this will mean an end to the Java trap. Mark Shuttleworth called the initial press announcement "a real milestone for the free software community."

Resource management

While Java does manage memory, it does not manage all resources, such as JDBC database connections; these must be released just as memory would need to be in C++.

Memory management

Java takes care of memory management. This was done as it makes it harder (but not impossible) for the programmer to create problems such as memory leaks. Java always allocates objects on the heap (unless optimized to the stack or registers by the JIT compiler) and local variables on the stack or in registers. This makes Java less flexible than C++, which allows programmers to choose where objects are allocated.

The garbage collector controls when objects are deleted from memory. Java does not allow programmers to guarantee when garbage collection happens (even with System.gc()), they cannot hold off garbage collection, and they cannot delete one particular object. While this makes programming much simpler and reduces memory leaks, it lacks the flexibility that can, in some cases, result in a more efficient handling of memory. Lower-level languages such as C or assembly language provide this flexibility.

While many programs, such as those written in C++, tend to fall prey to memory leaks, this is not the whole story. Other resource leaks such as file handles, database and network connections are still likely, especially when exceptions are thrown. However, where C++ has the RAII idiom to address both cases, Java programmers need to remember to release resources in finally clauses and must have a good understanding of which resources Java will release and which they must release.

Primitives vs. objects / Autoboxing

Java designers decided not to implement certain features present in other languages (including multiple inheritance, operator overloading, and tuples).

When generics were added to Java 5.0, there was already a large framework of classes (many of which were already deprecated), so generics were chosen to be implemented using erasure to allow backwards compatibility and preservation of these existing classes. This limited the features that could be provided by this addition as compared to other languages.

Java's primitive types are not objects. Primitive types hold their values in the stack rather than being references to values. This was done for performance reasons. Because of this, Java is not considered to be a pure object-oriented programming language and this makes reflection more complicated. However, Java 5.0 supports automatic conversion (autoboxing) of primitive data types to corresponding object form wherever required, during compilation. When autounboxing, a null pointer exception may be thrown. Since this operation occurs implicitly (without a cast or method call), this unchecked exception may not be obvious by inspection of the line of code.

Non-Virtual methods

Java provides no way to make methods non-virtual (although they can be "sealed" by using the final modifier to disallow overriding). This means that there is no way to let derived classes define a new, unrelated method with the same name. This can be a problem when a base class is designed by a different person, and a new version introduces a method with the same name and signature as some method already present in the derived class. This means that the method in the derived class will implicitly override the method in the base class, even though that was not the intent of the designers of either class. To partially accommodate for these versioning problems, Java 5.0 introduced the @Override annotation, but to preserve backwards compatibility it could not be made compulsory by default.

Single paradigm

Java is predominantly a single-paradigm language. The addition of static imports in Java 5.0 accommodates the procedural paradigm better than earlier versions of Java.

Exception handling

Java embraced the concept of exception specifications from C++ where they were optional, but made throws clauses mandatory for any checked exception. While this can be a benefit for small systems, there is not universal agreement that using checked exceptions is a benefit for larger systems. In particular, "higher level" code is often not interested in errors thrown by "lower level" code (eg: NamingException). The coder of the naming classes must make a choice: either force higher level code to deal with naming exceptions as checked exceptions, or allow them to "bubble up" through his own low-level code without compile-time checks.

Closure

Finally, while anonymous inner classes provide a basic form of closures, they are not complete and require referenced variables to either be class fields or declared "final". The rationale behind this is that it allows JVM implementors to choose a stack model for variable lifetimes, so that a variable scope is removed when exited, thus preventing real closures. In addition, when using - for instance - "Runnable" as a closure, one has to declare the "run" method and put the code in that: you cannot simply put some code in braces and pass it around.

Floating point arithmetic

While Java's floating point arithmetic is largely based on IEEE 754 (Standard for Binary Floating-Point Arithmetic), certain features are not supported even when using the "strictfp" modifier, such as Exception Flags and Directed Roundings — capabilities mandated by IEEE Standard 754. Many so-called "Java gotchas" are not problems with Java per se, but problems that are inevitable whenever using floating point arithmetic.

Look and feel

The look and feel of GUI applications written in Java using the Swing platform is often different from native applications. While programmers can choose to use the AWT toolkit that displays native widgets (and thus look like the operating platform), the AWT toolkit is unable to meet advanced GUI programming needs by wrapping around advanced widgets and not sacrificing portability across the various supported platforms, each of which have vastly different APIs especially for higher-level widgets.

The Swing toolkit--written completely in Java--both creates the problem of having a different look and feel from native applications, and avoids the problem of being limited by native toolkit capabilities because it reimplements widgets using only the most basic drawing mechanisms that are guaranteed available on all platforms. Unfortunately, the default installations of the JRE (as of August 2006) do not use the system's "native" look and feel, instead defaulting to the built-in Metal Look and Feel. If the programmer doesn't take care to set the native look and feel, users will have applications whose appearance is vastly different from that of their native applications. Apple Computer's own optimized version of the Java Runtime, which is included within the Mac OS X distribution, by default does set the default and implements its "Aqua" look-and-feel, giving Swing applications on the Macintosh a similar appearance to native software. Even in this environment, the programmer must still do some extra work to ensure that that application looks like an Aqua one (for example, they must set system properties to ensure the menubar is rendered in the OS X menubar and not in the application window as it would be on other platforms).

Performance

It is impossible to make any generalization about the performance of Java programs, because runtime performance is affected much more by the quality of the compiler or JVM than by any intrinsic properties of the language itself. Java bytecode can either be interpreted at run time by a virtual machine, or it can be compiled at load time or runtime into machine code which runs directly on the computer's hardware. Interpretation is slower than native execution, and compilation at load time or runtime has an initial performance penalty for the compilation.

Lack of language features

There are a few language requirements which incur an unavoidable time penalty, although these features are not unique to Java. Among these are array bounds checking, run-time type checking, and virtual function indirection (although each of these can in some situations be avoided by an optimizing compiler). Also the lack of features can affect performance. For example, Java does not have arrays of structures or a true multi-dimensional array, but only an array of references to objects or further arrays. Nor does Java allow returning more than one value from a function without using an object. The net result is that Java code makes more heap allocations than well-written code in some other languages.

Garbage collection

The use of a garbage collector to automatically delete objects adds overhead compared to manual deallocation and can have a positive or negative impact, or no discernible impact at all, on performance depending upon the garbage collector implementation and the characteristics of the application's use of objects. With the modern generational garbage collectors used in many JVMs, many applications actually experience greater performance because of faster allocation and deallocation algorithms.

Byte code vs. native compilation

Relative performance of JIT compilers as compared to native compilers can be quite close, and is often a subject of debate. The JIT compilation stage may be time consuming, which is inconvenient for applications that are short-lived and/or contain large amounts of code. Once compiled to native code, however, the performance of the program can be comparable to that achieved by a native compiler, even on numerical tasks. Although Java does not support manual inlining of method calls, many JIT compilers perform this optimization at load time and can exploit information from the runtime environment to guide more effective transformations, such as profile-directed inlining. Dynamic recompilation, as provided by Sun's HotSpot JVM, can exceed the performance of the static compilation available in most other languages by exploiting information that is only available at runtime.

Hardware interfacing

Because Java was designed with an emphasis on security and portability, it does not support direct access to the machine architecture and address space. This means working directly with a specific piece of hardware such as a scanner, digital camera, audio recorder, video capture, or virtually any hardware that requires direct memory space control (typically those pieces or hardware installed with drivers), cannot easily be accomplished with Java. An illustration of this issue is seen in version 1.0 of Java as it was not possible to access a printer because the interface code to the various printer drivers was not included in this first JVM.

Interfacing with native code

Clients side or server systems that need to "talk" to the hardware must implement a hybrid solution using Java and C/C++ or assembly language via the Java Native Interface (JNI) libraries to link native code to the Java libraries. An alternate solution is to code the hardware software component in its native C/C++/assembler language and then pass the data via files, databases or a shared memory interface, although this is not an ideal solution.

Using the JNI technique introduces many possible inconsistencies such as: machine dependency, potential deadlock situations, memory allocation leaks, and possibly poor application performance, not to mention code complexity of needing to maintain two different code bases. However, it must be noted that it is a common case for other Virtual machine languages, as for example the .NET Framework Common Language Runtime (see Platform Invocation Services).

Inconsistent JVM implementations

Java is a bytecode language that runs on top of the JVM; ultimately the compatibility of the language and the ability to have it run across different platforms is dependent on the stability and version of the JVM. While Java is touted as running on a large variety of systems, the most up to date JVM (and JRE) are only those actively updated for Windows, Linux and Solaris. HP (such as Java for HP-UX) and IBM (for MVS, AIX, OS/400) provide their own implementations for their family of platforms but do not always mirror the latest Sun releases. Other JVM implementations usually follow, but sometimes lag in months or years with the more common implementations and therefore introduce compatibility issues.
Saturday, June 28, 2008

Labels, Icons and Buttons

Labels are non-interactive text objects most commonly used as prompts. They are created using the JLabel() constructor with the required text as the first parameter. Another parameter can be added using a SwingConstant value to set horizontal alignment. Vertical alignment is through the setVerticalAlignment() method. The contents of a label can be changed with the setText() method.

Icons can be easily added to labels or other controls either to brand, dress up, or aid accessibility. Icons are constructed from the ImageIcon class and then added as a parameter to the label (or other) control. An extra parameter can be used to control the position of the text relative to the icon. It must use one of the SwingConstants values.

ImageIcon icon = new ImageIcon("smile.gif");
JLabel label = new JLabel("hello",icon,SwingConstants.RIGHT);
pane.add(label);

Simple buttons are used to start operations. They are created with the JButton() constructor. They can be deactivated with the setEnabled(false) method and tested with the isEnabled() method. One useful button method is setMnemonic(char) which allows a hot key to be associated with the button. Simple buttons require an ActionEvent event listener that reacts to the button click.

Toggle buttons are a visual push on - push off mechanism. They are created with the JToggleButton() constructor. The isSelected() method returns the state of the button. And in addition to ActionEvent, the ChangeEvent is triggered.

Basic Event Listeners

GUIs are event-based. That is they respond to buttons, keyboard input or mouse activities. Java uses event listeners to monitor activity on specified objects and react to specific conditions. For a listing of useful event listeners . For techniques on organizing many different events in larger projects,

The first step in adding a basic button push event handler to the above example is to import awt.event.* which contains all of the event classes. Next add the phrase implements ActionListener to the class header. Register event listeners for each button widget using the addActionListener(this) method. The reserved word this indicates that the required (by implements ActionListener) handler method called actionPerformed() will be included in the current class. For example:

Bounded-Range Components

Bounded-Range components are components that have a single integer value within fixed integer boundaries. Examples of bounded range control classes are JScrollBar, JSlider and JProgressBar. Each bounded-range component has the following methods: setExtent(), setMaximum(), setMinimum(), setValue(), getValueIsAdjusting() and setOrientation(). Bounded-range components use ChangeEvent to update.

Sliders can be dressed up with ticks and labels. The methods setPaintTicks(true) and setPaintLabels(true) turn them on. setMajorTickSpacing(int) and setMinorTickSpacing(int) set the intervals used for marker ticks. setSnapToTicks(true) forces the slider to the closest tick. setInverted(true) reverses the low and high marks. labelTable is a dictionary of slider values and label objects for painting.

Progress bars indicate status for time consuming jobs. The basic JProgressBar class offers a subtle control but if you want dialog for canceling an operation the classes ProgressMonitor and ProgressMonitorInputStream are better choices. ProgressMonitorInputStream is a stream filter in addition to a progress monitor.

Friday, June 27, 2008
A Graphical User Interface (GUI) is a visual paradigm which allows a user to communicate with a program in an intuitive way. Its main features are widgets (aka controls) and event driven activities. Clients expect a graphical interface in an application. The next few tutorials will introduce Java's GUI packages as well as some layout design consideraions.

Java has two GUI packages, the original Abstract Windows Toolkit (AWT) and the newer Swing. AWT uses the native operating system's window routines and therefore the visual effect is dependent on the run-time system platform. But this is contrary to the concept of having a virtual model. Swing allows three modes: a unified 'Java' look and feel [the default], the native platform look, or a specific platform's look. Swing is built on the original objects and framework of AWT. Swing components have the prefix J to distinguish them from the original AWT ones (eg JFrame instead of Frame). To include Swing components and methods in your project you must import the java.awt.*, java.awt.event.*, and javax.swing.* packages.

Containers, Frames and Content Panes

Containers are widgets (GUI controls) that are used to hold and group other widgets such as text fields and checkboxes. Displayable frames are top-level containers which interface to the operating system's window manager. Non-displaying content panes are intermediate containers which organize the layout structure when multiple controls are being used.

JWindow is an unadorned container that has been superceded for the most part by JDialog. However it does provide a useful container for a splash screen.

Methods common to many different containers or widgets include: add(), requestFocus(), setToolTipText().

JFrame and JPanel

JFrame is the most commonly used top-level container. It adds basic functionality such as minimize, maximize, close, title and border to basic frames and windows. Some important JFrame methods are: setBounds(x,y,w,h), setLocation(x,y), setSize(w,h), setResizable(bool), setTitle(str), setVisible(bool), isResizable() and getTitle(). The setDefaultCloseOperation(constant) method controls the action that occurs when the close icon is clicked. Normally the constant used is JFrame.EXIT_ON_CLOSE.

JPanel is the most commonly used content pane. An instance of the pane is created and then added to a frame. The add() method allows widgets (GUI components) to be added to the pane. The way they are added is controlled by the current layout manager.

The following is a simple template that creates a JFrame container class using inheritance. The created subclass then adds a JPanel. This custom class will form the basis of many of our GUI examples.

Simple Dialog Boxes

Dialogs are short messages or information screens, confirmation boxes, and input prompts for simple string information which appear in a popup windows. Swing uses the JOptionPane class to provide predefined methods for each type of dialog. The JDialog class can be used to create customized dialog boxes. It provides a simple unadorned window.

Each JOptionPane method has a first parameter that points to a parent (ie. window that it appears in) or null (default to the current window). The second parameter is the message or prompt to be displayed. New instances of JOptionPane are not normally generated.

showMessageDialog() has two more optional parameters to set a dialog title and to select the dialog's icon. The dialog has a single 'ok' button for completion and no data is returned by this method.

JOptionPane.showMessageDialog(null,"This is just a message",
"Message Dialog",JOptionPane.PLAIN_MESSAGE);

showConfirmDialog() has three more optional parameters to set a dialog title, alter the button display, and select the dialogs icon. By default there are three buttons 'Yes', 'No' and Cancel for dialog completion. The returned value is one of JOptionPane.YES_OPTION, JOptionPane.NO_OPTION or JOptionPane.CANCEL_OPTION.

pressed = JOptionPane.showConfirmBox(null,"Everything aok");
if (pressed==JOptionPane.YES_OPTION)
{
// do the action for confirmation
}

showInputDialog() has two more optional parameters to set a dialog title and to select the dialog's icon. There is both an 'ok' button and a 'cancel' button for dialog completion. Any information typed into the entry box is returned as a string.

user_data = JOptionPane.showInputDialog(null,"What's your name");

The list of icon types that can be displayed (by predefined constant) contains ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, and WARNING_MESSAGE.

NOTE: Current versions of swing do not allow button selection by first letter (eg. n for no) which is enabled in all windows type GUI's. This is a major pain for user clients who must either use the tab key or reach for their mouse... Blaah!


Thursday, June 26, 2008

Life Cycle of an Applet


Each Java applet goes through a sequence of stages. They are created (initialized), displayed (painted), paused while off screen (stopped,started) and finally removed (destroyed) when over.

Initialization occurs when the applet is first loaded. Tasks performed here are creating objects,setting initial state, loading images, fonts, etc. and setting parameters. The method used is init()

Display is how things are drawn on screen whether it is text, graphics or background. Redisplay occurs many time through the life of an applet. The method used is paint().

Stopping occurs when one leaves a page that contains a running applet. Threads normally continue running but can be manually stopped. The method used is stop().

Starting occurs after initialization and after stops occur. Tasks include starting threads, sending messages to helper objects, or to tell the applet to start running. The method used is start().

Destruction cleans up an applet before the browser exits. Tasks include thread stopping. Normally the method destroy() is not overridden.



Cautions About Applet Use


The greatest problem with using applets is the nonstandard way browsers cope with them. Some browsers support Java natively (ie. self contained). However this leads to version compatibility issues. Other browsers allow applets to be passed through to the Java engine of the viewer's operating system. But this requires that the viewer download and install Java. Are your website visitors this sophisticated? And finally there are ancient browsers like MSIE6 which really makes you jump through the hoops to hook up an installed Java environment. Most browsers also open a box that will overwrite any text that the box is scrolled to (ie a hign z-index value). At this point Java Script looks like a more consistent method of utility delivery!

For security purposes, Java applets allow NO access to user resources! Local files can not be accessed. Printers can't be used. Only the current website server can be communicated with. If your project can live with those restrictions then an applet may be more appropriate than an application.

Wednesday, June 25, 2008

Applets are intended to be viewed from within XHTML documents. In XHTML the applet or object element is placed where desired in the body element of the document. Note: The applet element has been deprecated and may only be used in Transitional documents. To use a Strict doctype you must convert any applet element to an object element. An applet skeleton is as follows:

Browser does not allow Java!

code points to the previously compiled applet class that is in a separate file. codebase points to the folder that the class file is in. A good choice is place the class folder under the html document. Be sure to explicitly point at the codebase starting at the html document. If you need to start at the root, use file:///C:/. Anything else fails in FireFox! height and width are also required parameters and cannot be moved into style rules. Nested param element(s) are optional and can be used to feed data to the applet from the XHTML document. Always include a message for non-java browsers between the applet element tags. The resulting display is:

Browser does not allow Java!

The equivalent object element skeleton syntax is:

Browser does not allow Java in object elements!

And it would appear as:

Browser does not support Java in object element!

Note 1: Remember that filenames are case sensitive in Java. Some browsers may allow helloworld.class but Opera obeys the rule! Always test any applet on as many browsers as you can.

Note 2: Although styling attributes such as align, hspace and vspace are mentioned in many texts, they are archaic and should be replaced by CSS style rules. And of course all XHTML documents should have a doctype and validate to current w3.org recommendations.

Tuesday, June 24, 2008
A Java applet produces object code which can be interpreted within the user's browser. This means that naive users do not have to fuss with program installation. Applets also provide security by restricting local user resource access. Applets can be useful, user friendly programs

Here is the explanation of the basic structure of a Java applet using the one that you wrote to test your working environment. Applets are placed in XHTML documents and are executed from within a Java aware browser.

Line three uses the reserved word import which indicates that objects from external libraries awt and applet are going to be used. Line four uses the reserved word extends to indicate that the class being created is a subclass of the Applet class. This demonstrates how Java code is reused and extended.
Note: The JApplet class is used instead of Applet whenever Swing GUI is used.

Line six starts the override (change) of the java.applet.Applet class init() method. Line eleven invokes the resize() method of the Applet object and sets the window dimensions. Note the all important statement ending semicolon.

Line 12 is another method override declaration. This time it is the paint() method of the Applet object. It is being passed an object of the Graphics class called g. Line 14 tells the Graphics object g to invoke its method drawString() using the string "Hello World! and position it at point (50,25) in the previously assigned window. A later tutorial gives details on graphics programming within applets.


Monday, June 23, 2008

A Java applet is an applet delivered in the form of Java bytecode. Java applets can run in a Web browser using a Java Virtual Machine (JVM), or in Sun's AppletViewer, a stand alone tool to test applets. Java applets were introduced in the first version of the Java language in 1995. Java applets are usually written in the Java programming language but they can also be written in other languages that compile to Java bytecode such as Jython.

Applets are used to provide interactive features to web applications that cannot be provided by HTML. Since Java's bytecode is platform independent, Java applets can be executed by browsers for many platforms, including Windows, Unix, Mac OS and Linux. There are open source tools like applet2app which can be used to convert an applet to a stand alone Java application/windows executable. This has the advantage of running a Java applet in offline mode without the need for internet browser software.

A Java Servlet is sometimes informally compared to be "like" a server-side applet, but it is different in its language, functions, and in each of the characteristics described here about applets.

Technical information

Java applets are executed in a sandbox by most web browsers, preventing them from accessing local data. The code of the applet is downloaded from a web server and the browser either embeds the applet into a web page or opens a new window showing the applet's user interface. The applet can be displayed on the web page by making use of the deprecated applet HTML element or the recommended object element. This specifies the applet's source and the applet's location statistics.

A Java applet extends the class java.applet.Applet, or in the case of a Swing applet, javax.swing.JApplet. The class must override methods from the applet class to set up a user interface inside itself (Applet is a descendant of Panel which is a descendant of Container).

Advantages of applets

A Java applet can have any or all of the following advantages:

* it is simple to make it work on Windows, Mac OS and Linux, i.e. to make it cross platform
* the same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of the JRE the client will be forced wait during the large download.
* it runs in a sandbox, so the user does not need to trust the code, so it can work without security approval
* it is supported by most web browsers
* it will cache in most web browsers, so will be quick to load when returning to a web page
* it can have full access to the machine it is running on if the user agrees
* it can improve with use: after a first applet is run, the JVM is already running and starts quickly, benefiting regular users of Java
* it can run at a comparable (but generally slower) speed to other compiled languages such as C++
* it can be a real time application
* it can move the work from the server to the client, making a web solution more scalable with the number of users/clients

Disadvantages of applets

A Java applet is open to any of the following disadvantages:

* it requires the Java plug-in, which isn't available by default on all web browsers
* it can't start up until the Java Virtual Machine is running, and this may have significant startup time the first time it is used
* if it is uncached, it must be downloaded (usually over the internet), and this takes time
* it is considered more difficult to build and design a good user interface with applets than with HTML-based technologies
* if untrusted, it has severely limited access to the user's system - in particular having no direct access to the client's disc or clipboard
* some organizations only allow software installed by the administrators. As a result, many users cannot view applets by default.
* applets may require a specific JRE.

Compatibility issues

Sun has made a considerable effort to ensure compatibility is maintained between Java versions as they evolve. For example, Microsoft's Internet Explorer, the most popular web browser since the late 1990s, used to ship with Microsoft's own JVM as the default. The MSJVM had some extra non-Java features added which, if used, would prevent MSJVM applets from running on Sun's Java (but not the other way round). Sun sued for breach of trademark, as the point of Java was that there should be no proprietary extensions and that code should work everywhere. Development of MSJVM was frozen by a legal settlement, leaving many users with an extremely outdated Java virtual machine. Later, in October 2001, MS stopped including Java with Windows, and for some years it has been left to the computer manufacturers to ship Java independently of the OS. Most new machines now ship with official Sun Java.

Some browsers (notably Firefox) do not do a good job of handling height=100% on applets which makes it difficult to make an applet fill most of the browser window (Javascript can, with difficulty, be used for this). Having the applet create its own main window is not a good solution either, as this leads to a large chance of the applet getting terminated unintentionally and leaves the browser window as a largely useless extra window.

Alternatives

Alternative technologies exist (for example, DHTML and Flash) that satisfy some of the scope of what is possible with an applet.

Another alternative to applets for client side Java is Java Web Start, which runs outside the browser. In addition to the features available to applets, a simple permissions box can give Java Web Start programs read and/or write access to specified files stored on the client, and to the client's clipboard.


Sunday, June 22, 2008
Java Virtual Machine (JVM), originally developed by Sun Microsystems, is a virtual machine that executes Java bytecode. This code is most often generated by Java language compilers, although the JVM has also been targeted by compilers of other languages. The JVM is a crucial component of the Java Platform. The availability of JVMs on many types of hardware and software platforms enables Java to function both as middleware and a platform in its own right. Hence the expression "Write once, run anywhere." Starting with J2SE 5.0, changes to the JVM specification have been developed under the Java Community Process as JSR 924. As of 2006, changes to specification to support changes proposed to the class file format (JSR 202) are being done as a maintenance release of JSR 924. The specification for the JVM is published in book form, known as "blue book". The preface states:

Execution environment

Programs intended to run on a JVM must be compiled into a standardized portable binary format, which typically comes in the form of .class files. A program may consist of many classes, in which case every class will be in a different file. For easier distribution of large programs, multiple class files may be packaged together in a .jar file. This binary is then executed by the JVM runtime which carries out emulation of the JVM instruction set by interpreting it or by applying a just-in-time compiler (JIT) such as Sun's HotSpot. The Java byte code is stack based. Therefore interpreter JVMs usually use a stack architecture. In contrast, JIT compilers usually compile the byte code into register based machine code. Each thread has its own stack and program counter.

Bytecode verifier

The JVM verifies all bytecode before it is executed. This means that only a limited amount of bytecode sequences form valid programs, e.g. a JUMP (branch) instruction can only target an instruction within the same function. Because of this, the fact that JVM is a stack architecture does not imply a speed penalty for emulation on register based architectures when using a JIT compiler: in the face of the code-verified JVM architecture, it makes no difference to a JIT compiler whether it gets named imaginary registers or imaginary stack positions that need to be allocated to the target architecture's registers. In fact, code verification makes the JVM different from a classic stack architecture whose efficient emulation with a JIT compiler is more complicated and typically carried out by a slower interpreter. Code verification also ensures that arbitrary bit patterns cannot get used as an address. Memory protection is achieved without the need for an MMU. Thus, JVM is an efficient way of getting memory protection on simple silicon that has no MMU.

Bytecodes

The JVM has instructions for the following groups of tasks * Load and store * Arithmetic * Type conversion * Object creation and manipulation * Operand stack management (push / pop) * Control transfer (branching) * Method invocation and return * Throwing exceptions The aim is binary compatibility. Each particular host operating system needs its own implementation of the JVM and runtime. These JVMs interpret the byte code semantically the same way, but the actual implementation may be different. More complicated than just the emulation of bytecode is compatible and efficient implementation of the Java core API which has to be mapped to each host operating system.

Secure execution of remote code

A virtual machine architecture allows very fine-grained control over the actions that code within the machine is permitted to take. This is designed to allow safe execution of untrusted code from remote sources, a model used most famously by Java Applets. Applets run within a VM incorporated into a user's browser, executing code downloaded from a remote HTTP server. The remote code runs in a highly restricted "sandbox", which is designed to protect the user from misbehaving or malicious code. Publishers with sufficient financial resources can apply for a certificate with which to digitally sign applets as "safe", giving them permission to break out of the sandbox and access the local file system and network, presumably under user control.
Tuesday, June 17, 2008

JAVA String Utility

( This program Demonstrates the proper use of Number Formats in common java programming scenarios )

String Utility

/*
* NumberUtility.java
*
* Source: http://www.freejavaguide.com
*/

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

/**
* Class provides common functions on number formats.
*/

public class NumberUtility {

/**
* Method takes Object as parameter and returns decimal number.
* if argument is float or double and contains tailing zeros
* it removes them. If argument is float or double then no change in return type.
* Change the Format of the Number by changing the String Pattern
*/
public static String changeToDecimalFormat(Object number) {

BigDecimal bdNumber = new BigDecimal(number.toString());
bdNumber = bdNumber.stripTrailingZeros(); //Returns a BigDecimal with any trailing zero's removed
String pattern = "###,##0.0###########"; //To apply formatting when the number of digits in input equals the pattern
DecimalFormat newFormat = new DecimalFormat(pattern, new DecimalFormatSymbols(Locale.US));
return newFormat.format(bdNumber);

}

/* Method takes Object as parameter and removes commas from the parameter */
public static double removeCommasFromNumber(Object number) {
try {
StringBuffer inputNo = new StringBuffer(number.toString());
if (inputNo.length() > 0) {
while (inputNo.indexOf(",") != -1) {
inputNo.deleteCharAt(inputNo.indexOf(","));
}
} else {
return 0.0;
}
return Double.parseDouble(inputNo.toString());

} catch (NumberFormatException e) {
return 0.0;
}
}

/* Some times its required to have a fixed set of decimal places for a
* number. We can set that by changing the precision number for a particular
* input BigDecimal Input String
*/
public static String changeToRequiredDecimals(String bigDecimalString,
int precision) {
String newFormattedString = null;
String afterDecimal = null;
if (bigDecimalString == null || bigDecimalString.length() == 0) {
return "0.0";
}
if (bigDecimalString.contains(".")) {
afterDecimal = bigDecimalString.substring(bigDecimalString
.indexOf(".") + 1);
int length = Math.abs((afterDecimal.length() - precision));
if (afterDecimal.length() < precision) {
newFormattedString = bigDecimalString;
for (int i = 0; i < length; i++) {
newFormattedString = newFormattedString + "0";
}
} else if (afterDecimal.length() > precision) {
newFormattedString = bigDecimalString.substring(0,
bigDecimalString.length() - length);
if (precision == 0) {
newFormattedString = newFormattedString.substring(0,
newFormattedString.indexOf("."));
} else {
newFormattedString = bigDecimalString;
}

} else {
if (precision > 0)
newFormattedString = bigDecimalString + ".";
else
newFormattedString = bigDecimalString;
for (int i = 0; i < precision; i++) {
newFormattedString = newFormattedString + "0";
}
}
}
return newFormattedString;
}

public static void main(String args[]){
int intVar = 10;
double doubleVar = 10.504000;
float floatVar = 343534534348.5687654F;
String commaString = "343,534,535,000.0";
BigDecimal bdNumber = new BigDecimal("1234.8765");


System.out.println(NumberUtility.changeToDecimalFormat(new Integer(intVar)));
System.out.println(NumberUtility.changeToDecimalFormat(new Double(doubleVar)));
System.out.println(NumberUtility.changeToDecimalFormat(new Float(floatVar)));

System.out.println(NumberUtility.removeCommasFromNumber(commaString));

System.out.println(NumberUtility.changeToRequiredDecimals(bdNumber.toString(), 8));

}
}

Monday, June 16, 2008

JAVA Date Utility

( This program Demonstrates the proper use of Date functionality in common java programming scenarios )

Date and Time

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtility {

/* Add Day/Month/Year to a Date
add() is used to add values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
*/

public static void addToDate(){
System.out.println("In the ADD Operation");
// String DATE_FORMAT = "yyyy-MM-dd";
String DATE_FORMAT = "dd-MM-yyyy"; //Refer Java DOCS for formats
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
Date d1 = new Date();
System.out.println("Todays date in Calendar Format : "+c1);
System.out.println("c1.getTime() : "+c1.getTime());
System.out.println("c1.get(Calendar.YEAR): " + c1.get(Calendar.YEAR));
System.out.println("Todays date in Date Format : "+d1);
c1.set(1999,0 ,20); //(year,month,date)
System.out.println("c1.set(1999,0 ,20) : "+c1.getTime());
c1.add(Calendar.DATE,40);
System.out.println("Date + 20 days is : " + sdf.format(c1.getTime()));
System.out.println();
System.out.println();
}


/*Substract Day/Month/Year to a Date
roll() is used to substract values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

Note: To substract, simply use a negative argument.
roll() does the same thing except you specify if you want to roll up (add 1)
or roll down (substract 1) to the specified Calendar field. The operation only
affects the specified field while add() adjusts other Calendar fields.
See the following example, roll() makes january rolls to december in the same
year while add() substract the YEAR field for the correct result

*/


public static void subToDate(){
System.out.println("In the SUB Operation");
String DATE_FORMAT = "dd-MM-yyyy";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0 , 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));

// roll down, substract 1 month
c1.roll(Calendar.MONTH, false);
System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime()));

c1.set(1999, 0 , 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1);
// substract 1 month
System.out.println("Date minus 1 month : " + sdf.format(c1.getTime()));
System.out.println();
System.out.println();
}

public static void daysBetween2Dates(){
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
Calendar c2 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 0 , 20);
c2.set(1999, 0 , 22);
System.out.println("Days Between "+c1.getTime()+"\t"+ c2.getTime()+" is");
System.out.println((c2.getTime().getTime() - c1.getTime().getTime())/(24*3600*1000));
System.out.println();
System.out.println();
}

public static void daysInMonth() {
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 6 , 20);
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
// int days = c1.get(Calendar.DATE);
int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
System.out.println("Days in "+month+"th month for year "+year+" is "+ daysInMonths[c1.get(Calendar.MONTH)]);
System.out.println();
System.out.println();
}

public static void getDayofTheDate() {
Date d1 = new Date();
String day = null;
DateFormat f = new SimpleDateFormat("EEEE");
try {
day = f.format(d1);
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("The dat for "+d1+" is "+day);
System.out.println();
System.out.println();
}

public static void validateAGivenDate() {
String dt = "20011223";
String invalidDt = "20031315";
String dateformat = "yyyyMMdd";
Date dt1=null , dt2=null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
sdf.setLenient(false);
dt1 = sdf.parse(dt);
dt2 = sdf.parse(invalidDt);
System.out.println("Date is ok = " + dt1 + "(" + dt + ")");
}
catch (ParseException e) {
System.out.println(e.getMessage());
}
catch (IllegalArgumentException e) {
System.out.println("Invalid date");
}
System.out.println();
System.out.println();
}

public static void compare2Dates(){
SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();

c1.set(2000, 02, 15);
c2.set(2001, 02, 15);

System.out.print(fm.format(c1.getTime())+" is ");
if(c1.before(c2)){
System.out.println("less than "+c2.getTime());
}else if(c1.after(c2)){
System.out.println("greater than "+c2.getTime());
}else if(c1.equals(c2)){
System.out.println("is equal to "+fm.format(c2.getTime()));
}
System.out.println();
System.out.println();
}

public static boolean isLeapYear(int year){
if((year%100 != 0) || (year%400 == 0)){
return true;
}
return false;
}

public static void main(String args[]){
addToDate();
subToDate();
daysBetween2Dates(); //The "right" way would be to compute the julian day number of both dates and then do the substraction.
daysInMonth();
validateAGivenDate();
compare2Dates();
getDayofTheDate();
}

}
Saturday, June 14, 2008

Some Java programs which help lot of java beginners to understand the basic fundamentals in Java programming. Most of these programs take input from the command line. Ex - int num = Integer.parseInt(args[0]);

Program 20

/* switch case demo

Example :

Input - 124

Output - One Two Four */

class SwitchCaseDemo{

public static void main(String args[]){

try{

int num = Integer.parseInt(args[0]);

int n = num; //used at last time check

int reverse=0,remainder;

while(num > 0){

remainder = num % 10;

reverse = reverse * 10 + remainder;

num = num / 10;

}

String result=""; //contains the actual output

while(reverse > 0){

remainder = reverse % 10;

reverse = reverse / 10;

switch(remainder){

case 0 :

result = result + "Zero ";

break;

case 1 :

result = result + "One ";

break;

case 2 :

result = result + "Two ";

break;

case 3 :

result = result + "Three ";

break;

case 4 :

result = result + "Four ";

break;

case 5 :

result = result + "Five ";

break;

case 6 :

result = result + "Six ";

break;

case 7 :

result = result + "Seven ";

break;

case 8 :

result = result + "Eight ";

break;

case 9 :

result = result + "Nine ";

break;

default:

result="";

}

}

System.out.println(result);

}catch(Exception e){

System.out.println("Invalid Number Format");

}

}

}


Program 21

/* Write a program to generate Harmonic Series.

Example :

Input - 5

Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */

class HarmonicSeries{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

double result = 0.0;

while(num > 0){

result = result + (double) 1 / num;

num--;

}

System.out.println("Output of Harmonic Series is "+result);

}

}


Program 22

/*Write a program to find average of consecutive N Odd no. and Even no. */

class EvenOdd_Avg{

public static void main(String args[]){

int n = Integer.parseInt(args[0]);

int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;

while(n > 0){

if(n%2==0){

cntEven++;

sumEven = sumEven + n;

}

else{

cntOdd++;

sumOdd = sumOdd + n;

}

n--;

}

int evenAvg,oddAvg;

evenAvg = sumEven/cntEven;

oddAvg = sumOdd/cntOdd;

System.out.println("Average of first N Even no is "+evenAvg);

System.out.println("Average of first N Odd no is "+oddAvg);

}

}


Program 23

/* Display Triangle as follow : BREAK DEMO.

1

2 3

4 5 6

7 8 9 10 ... N */

class Output1{

public static void main(String args[]){

int c=0;

int n = Integer.parseInt(args[0]);

loop1: for(int i=1;i<=n;i++){

loop2: for(int j=1;j<=i;j++){

if(c!=n){

c++;

System.out.print(c+" ");

}

else

break loop1;

}

System.out.print("\n");

}

}

}


Program 24

/* Display Triangle as follow

0

1 0

1 0 1

0 1 0 1 */

class Output2{

public static void main(String args[]){

for(int i=1;i<=4;i++){

for(int j=1;j<=i;j++){

System.out.print(((i+j)%2)+" ");

}

System.out.print("\n");

}

}

}


Program 25

/* Display Triangle as follow

1

2 4

3 6 9

4 8 12 16 ... N (indicates no. of Rows) */

class Output3{

public static void main(String args[]){

int n = Integer.parseInt(args[0]);

for(int i=1;i<=n;i++){

for(int j=1;j<=i;j++){

System.out.print((i*j)+" ");

}

System.out.print("\n");

}

}
Thursday, June 12, 2008

Program 11

/* Write a program to Concatenate string using for Loop

Example:

Input - 5

Output - 1 2 3 4 5 */

class Join{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

String result = " ";

for(int i=1;i<=num;i++){

result = result + i + " ";

}

System.out.println(result);

}

}


Program 12

/* Program to Display Multiplication Table */

class MultiplicationTable{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

System.out.println("*****MULTIPLICATION TABLE*****");

for(int i=1;i<=num;i++){

for(int j=1;j<=num;j++){

System.out.print(" "+i*j+" ");

}

System.out.print("\n");

}

}

}


Program 13

/* Write a program to Swap the values */

class Swap{

public static void main(String args[]){

int num1 = Integer.parseInt(args[0]);

int num2 = Integer.parseInt(args[1]);

System.out.println("\n***Before Swapping***");

System.out.println("Number 1 : "+num1);

System.out.println("Number 2 : "+num2);

//Swap logic

num1 = num1 + num2;

num2 = num1 - num2;

num1 = num1 - num2;

System.out.println("\n***After Swapping***");

System.out.println("Number 1 : "+num1);

System.out.println("Number 2 : "+num2);

}

}


Program 14

/* Write a program to convert given no. of days into months and days.

(Assume that each month is of 30 days)

Example :

Input - 69

Output - 69 days = 2 Month and 9 days */

class DayMonthDemo{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

int days = num%30;

int month = num/30;

System.out.println(num+" days = "+month+" Month and "+days+" days");

}

}


Program 15

/*Write a program to generate a Triangle.

eg:

1

2 2

3 3 3

4 4 4 4 and so on as per user given number */

class Triangle{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

for(int i=1;i<=num;i++){

for(int j=1;j<=i;j++){

System.out.print(" "+i+" ");

}

System.out.print("\n");

}

}

}


Program 16

/* Write a program to Display Invert Triangle.

Example:

Input - 5

Output :

5 5 5 5 5

4 4 4 4

3 3 3

2 2

1

*/

class InvertTriangle{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

while(num > 0){

for(int j=1;j<=num;j++){

System.out.print(" "+num+" ");

}

System.out.print("\n");

num--;

}

}

}


Program 17

/*Write a program to find whether given no. is Armstrong or not.

Example :

Input - 153

Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */

class Armstrong{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

int n = num; //use to check at last time

int check=0,remainder;

while(num > 0){

remainder = num % 10;

check = check + (int)Math.pow(remainder,3);

num = num / 10;

}

if(check == n)

System.out.println(n+" is an Armstrong Number");

else

System.out.println(n+" is not a Armstrong Number");

}

}


Program 18

/* Write a program to Find whether number is Prime or Not. */

class PrimeNo{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

int flag=0;

for(int i=2;i

if(num%i==0)

{

System.out.println(num+" is not a Prime Number");

flag = 1;

break;

}

}

if(flag==0)

System.out.println(num+" is a Prime Number");

}

}


Program 19

/* Write a program to find whether no. is palindrome or not.

Example :

Input - 12521 is a palindrome no.

Input - 12345 is not a palindrome no. */

class Palindrome{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

int n = num; //used at last time check

int reverse=0,remainder;

while(num > 0){

remainder = num % 10;

reverse = reverse * 10 + remainder;

num = num / 10;

}

if(reverse == n)

System.out.println(n+" is a Palindrome Number");

else

System.out.println(n+" is not a Palindrome Number");

}

}

Tuesday, June 10, 2008

Program 1

//Find Maximum of 2 nos.

class Maxof2{

public static void main(String args[]){

//taking value as command line argument.

//Converting String format to Integer value

int i = Integer.parseInt(args[0]);

int j = Integer.parseInt(args[1]);

if(i > j)

System.out.println(i+" is greater than "+j);

else

System.out.println(j+" is greater than "+i);

}

}


Program 2

//Find Minimum of 2 nos. using conditional operator

class Minof2{

public static void main(String args[]){

//taking value as command line argument.

//Converting String format to Integer value

int i = Integer.parseInt(args[0]);

int j = Integer.parseInt(args[1]);

int result = (i

System.out.println(result+" is a minimum value");

}

}


Program 3

/* Write a program that will read a float type value from the keyboard and print the following output.

->Small Integer not less than the number.

->Given Number.

->Largest Integer not greater than the number.

*/

class ValueFormat{

public static void main(String args[]){

double i = 34.32; //given number

System.out.println("Small Integer not greater than the number : "+Math.ceil(i));

System.out.println("Given Number : "+i);

System.out.println("Largest Integer not greater than the number : "+Math.floor(i));

}


Program 4

/*Write a program to generate 5 Random nos. between 1 to 100, and it

should not follow with decimal point.

*/

class RandomDemo{

public static void main(String args[]){

for(int i=1;i<=5;i++){

System.out.println((int)(Math.random()*100));

}

}

}


Program 5

/* Write a program to display a greet message according to

Marks obtained by student.

*/

class SwitchDemo{

public static void main(String args[]){

int marks = Integer.parseInt(args[0]); //take marks as command line argument.

switch(marks/10){

case 10:

case 9:

case 8:

System.out.println("Excellent");

break;

case 7:

System.out.println("Very Good");

break;

case 6:

System.out.println("Good");

break;

case 5:

System.out.println("Work Hard");

break;

case 4:

System.out.println("Poor");

break;

case 3:

case 2:

case 1:

case 0:

System.out.println("Very Poor");

break;

default:

System.out.println("Invalid value Entered");

}

}

}


Program 6

/*Write a program to find SUM AND PRODUCT of a given Digit. */

class Sum_Product_ofDigit{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //taking value as command line argument.

int temp = num,result=0;

//Logic for sum of digit

while(temp>0){

result = result + temp;

temp--;

}

System.out.println("Sum of Digit for "+num+" is : "+result);

//Logic for product of digit

temp = num;

result = 1;

while(temp > 0){

result = result * temp;

temp--;

}

System.out.println("Product of Digit for "+num+" is : "+result);

}

}


Program 7

/*Write a program to Find Factorial of Given no. */

class Factorial{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //take argument as command line

int result = 1;

while(num>0){

result = result * num;

num--;

}

System.out.println("Factorial of Given no. is : "+result);

}

}


Program 8

/*Write a program to Reverse a given no. */

class Reverse{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //take argument as command line

int remainder, result=0;

while(num>0){

remainder = num%10;

result = result * 10 + remainder;

num = num/10;

}

System.out.println("Reverse number is : "+result);

}

}


Program 9

/*Write a program to find Fibonacci series of a given no.

Example :

Input - 8

Output - 1 1 2 3 5 8 13 21

*/

class Fibonacci{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //taking no. as command line argument.

System.out.println("*****Fibonacci Series*****");

int f1, f2=0, f3=1;

for(int i=1;i<=num;i++){

System.out.print(" "+f3+" ");

f1 = f2;

f2 = f3;

f3 = f1 + f2;

}

}

}


Program 10

/* Write a program to find sum of all integers greater than 100 and

less than 200 that are divisible by 7 */

class SumOfDigit{

public static void main(String args[]){

int result=0;

for(int i=100;i<=200;i++){

if(i%7==0)

result+=i;

}

System.out.println("Output of Program is : "+result);

}

}

Monday, June 9, 2008
Instructions for creating an Executable .jar file

Make or modify the Manifest.MF to YourManifest.MF.

1) YourClassNameWithMain is the class name (case sensitive) without .class extension
2) No extra spaces following the YourClassName withMain.

Manifest-Version:1.0
Main-Class: YourClassNameWithMain
Created-by:1.2(Sun Microsystems Inc.)
On Command line : type the following
jar cvfm YourJarFileName.jar YourManifest.MF*

or

jar cvfm YourJarFileName.jar YourManifest.MF -C classes yourClassPath
Drag-drop the YourJarFileName.jar to your desktop double click it, it runs
If your program only has System.out.println ("whatever"); statements, it will
display nothing. The same will happen when you run it useing java at command line

You need some windows code to see it run

Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file similar to zip utility, and more Java.

You can use it on any machine installed JDK

Create a folder name it anything
Make that folder your current directory
put all your files for turning in (do not put any extra) in that directory.

Be sure to put your html file, if there is one
At your dos prompt, while you are in the directory that you created , type in:
jar cvf Prj02.jar*

This will take ALL the files in the directory including subdirectories and place them in a .jar file Prj02 that can be replaced by any of your desired jar file name.

To test it, you can extract the contents of jar file by typing:
jar xvf Prj02.jar
Sunday, June 8, 2008
You can write data to a file instead of the computer screen. You can write certain data to a file while still putting other data on the screen. Or you may need access to multiple files simultaneously. Or you may want to query the user for input rather than accepting it all on the command line. Or maybe you want to read data out of a file that's in a particular format. In Java all these methods take place as streams. < > Using File I/O streams. The System.out.println() statement we've been using all along is an implementation of Streams.

A program that writes a string to a file

In order to use the Java file classes, we must import the Java input/output package (java.io) in the following manner

import java.io.*;

Inside the main method of our program, we must declare a FileOutputStream object. In this case, we wish to write a string to the file, and so we create a new PrintStream object that takes as its constructor the existing FileOutputStream. Any data we send from PrintStream will now be passed to the FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it a string, and then close the connection.

Source Code

/*
* FileOutput
* Demonstration of FileOutputStream and PrintStream classes
*/

import java.io.*;

class FileOutput
{

public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
// Create a new file output stream connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream
p = new PrintStream( out );

p.println ("This is written to a file myFile.txt");

p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to the file myFile.txt");
}
}
}

Interactively communicating with the user
Program asking the user for their name and then prints a personalized greeting.

Source Code

import java.io.*;

class PersonalHello {

public static void main (String args[])
{

byte name[] = new byte[100];
int nr_read = 0;

System.out.println("Your name Please?");
try {
nr_read = System.in.read(name);
System.out.print("Hello ");
System.out.write(name,0,nr_read);
}
catch (IOException e) {
System.out.print("I did not get your name.");
}

}

}
In code that does any significant input or output you'll want to begin by importing all the various java.io classes. import.java.io.*; Most of the reading and writing you do in Java will be done with bytes. Here we've started with an array of bytes that will hold the user's name.

First we print a query requesting the user's name. Then we read the user's name using the System.in.read() method. This method takes a byte array as an argument, and places whatever the user types in that byte array. Then, like before, we print "Hello." Finally we print the user's name.

The program doesn't actually see what the user types until he or she types a carriage return. This gives the user the chance to backspace over and delete any mistakes. Once the return key is pressed, everything in the line is placed in the array.

Reading Numbers
Often strings aren't enough. A lot of times you'll want to ask the user for a number as input. All user input comes in as strings so we need to convert the string into a number.

The getNextInteger() method that will accept an integer from the user. Here it is:

static int getNextInteger() {

String line;

DataInputStream in = new DataInputStream(System.in);
try {
line = in.readLine();
int i = Integer.valueOf(line).intValue();
return i;
}
catch (Exception e) {
return -1;
}

} // getNextInteger ends here

Reading Formatted Data
It's often the case that you want to read not just one number but multiple numbers. Sometimes you may need to read text and numbers on the same line. For this purpose Java provides the StreamTokenizer class.

Writing a text file
Sometimes you want to save your output in a file. To do this we'll need to learn how to write data to a file.

Source Code

// Write the Fahrenheit to Celsius table in a file

import java.io.*;

class FahrToCelsius {

public static void main (String args[]) {

double fahr, celsius;
double lower, upper, step;

lower = 0.0; // lower limit of temperature table
upper = 300.0; // upper limit of temperature table
step = 20.0; // step size

fahr = lower;

try {

FileOutputStream fout = new FileOutputStream("test.out");

// now to the FileOutputStream into a PrintStream
PrintStream myOutput = new PrintStream(fout);

while (fahr <= upper) { // while loop begins here
celsius = 5.0 * (fahr-32.0) / 9.0;
myOutput.println(fahr + " " + celsius);
fahr = fahr + step;
} // while loop ends here

} // try ends here
catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}

} // main ends here

}
There are only three things necessary to write formatted output to a file rather than to the standard output:

1. Open a FileOutputStream using a line like

FileOutputStream fout = new FileOutputStream("test.out");
This line initializes the FileOutputStream with the name of the file you want to write into.
2. Convert the FileOutputStream into a PrintStream using a statement like

PrintStream myOutput = new PrintStream(fout);

The PrintStream is passed the FileOutputStream from step 1.
3. Instead of using System.out.println() use myOutput.println(). System.out and myOutput are just different instances of the PrintStream class. To print to a different PrintStream we keep the syntax the same but change the name of the PrintStream.

Reading a text file
Now that we know how to write a text file, let's try reading one. The following code accepts a series of file names on the command line and then prints those filenames to the standard output in the order they were listed.

// Imitate the Unix cat utility

import java.io.*;

class cat {

public static void main (String args[]) {

String thisLine;

//Loop across the arguments
for (int i=0; i < args.length; i++) {

//Open the file for reading
try {
FileInputStream fin = new FileInputStream(args[i]);

// now turn the FileInputStream into a DataInputStream
try {
DataInputStream myInput = new DataInputStream(fin);

try {
while ((thisLine = myInput.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // while loop ends here
}
catch (Exception e) {
System.out.println("Error: " + e);
}
} // end try
catch (Exception e) {
System.out.println("Error: " + e);
}

} // end try
catch (Exception e) {
System.out.println("failed to open file " + args[i]);
System.out.println("Error: " + e);
}
} // for end here

} // main ends here

}

SUBSCRIBE VIA eMAIL

Enter your email address:

Delivered by FeedBurner

Recent Posts

Firefox 3

Counter

internet companies

Live Traffic Map

Subscribe Now