SARAVANAN SIVAJI

Dedicated to JAVA Technologies

Confusion in JAVA version numbers?

Posted by SARAVANAN SIVAJI on September 13, 2009

Sun has changed the naming convention not once but TWICE.

Okay — try to follow along, because this is CRAZY.

It all started with Java 1.0 and Java 1.1.

Then Java underwent a major overhaul. This was referred to Java 2, Standard Edition. It also had the version number Java v. 1.2.

Java 2 (aka J2SE) is basically every version from Java v. 1.2 through Java 1.5. However, when Java went to Java v. 1.5, they changed the version scheme so that Java v. 1.5 is actually the same as Java v. 5.0!!

Still with me? OK! Then, instead of going to Java v. 5.1, they changed schemes AGAIN. They dropped the “.0″ and changed J2SE to just “Java SE”. This is where we are now. Here’s a chart:

Java version | Java family | Also known as
Java v 1.0 | JDK |
Java v 1.1 | JDK |
Java v 1.2 | Java 2 (J2SE) |
Java v 1.3 | Java 2 (J2SE) |
Java v 1.4 | Java 2 (J2SE) |
Java v 5.0 | Java 2 (J2SE) | Java v. 1.5
Java SE 6 | Java SE | Java v. 1.6

You can find more information about JAVA version history from the following link,

http://en.wikipedia.org/wiki/Java_version_history

I found this document on sun’s website it does have an interesting part where you can see where the release number is used.

The upcoming feature release of J2SE is version 5.0. We have changed the version of this release from 1.5.0 to 5.0 to better reflect the level of maturity, stability, scalability and security built into J2SE. (This release is also known as “Tiger”.)

Platform and Product Names Use Version 5.0

Version 5.0 is used in the platform and product names — the leading “1.” was dropped. Where you might have expected to see 1.5.0, it is now 5.0 (and where it was 1.5, it is now 5). The names are now:

Full Name Abbreviation
Platform name JavaTM 2 Platform Standard Edition 5.0 J2SETM 5.0
Products delivered
under the platform
J2SETM Development Kit 5.0 JDKTM 5.0
J2SETM Runtime Environment 5.0 JRE 5.0

Due to significant popularity within the Java developer community, the development kit has reverted back to the name “JDK” from “Java 2 SDK” (or “J2SDK”), and the runtime environment has reverted back to “JRE” from “J2RE”. Notice that “JDK” stands for “J2SE Development Kit”. The name “Java Development Kit” has not been used since 1.1, prior to the advent of J2EE and J2ME.

As before, the “2″ in Java 2 Platform Standard Edition indicates the 2nd generation Java platform, introduced with J2SE 1.2. This generation number is also used with J2EE and J2ME.

Where Is Version 1.5.0 Still Used?

J2SE also keeps the version number 1.5.0 (or 1.5) in some under-the-cover places that are visible only to developers, where the version number is parsed by programs. In these cases, 1.5.0 refers to exactly the same platform and products numbered 5.0. Version numbers 1.5.0 and 1.5 are used at:

  • java -version (among other info, returns java version "1.5.0")
  • java -fullversion (returns java full version "1.5.0-b64")
  • javac -source 1.5 (javac -source 5 also works)
  • java.version system property
  • java.vm.version system property
  • @since 1.5 tag values
  • jdk1.5.0 installation directory
  • jre1.5.0 installation directory
  • http://java.sun.com/j2se/1.5.0 website (http://java.sun.com/j2se/5.0 also works)

Posted in com.saravananmtech.java | Leave a Comment »

Java Applets

Posted by SARAVANAN SIVAJI on June 2, 2009

Introducing applets

Java applets are not standalone programs like applications. Instead, they run within another application – usually a web browser.

You can run applets by embedding a reference to them in an HTML page and then running the page in a Java-compatible browser. Or you can run them using an applet viewer such as the one included in the Java Development Kit (JDK).

When a user accesses a web page containing an applet, the browser downloads the applet and runs it. For example, an applet cannot open a file or execute a program on its host computer (the computer executing it).

But many browsers place restrictions on what applets can do to ensure that they are safe to download. These restrictions are termed the “sandbox security model.”

An applet can open a network connection to the computer from which it was loaded, but it cannot open connections to any other computers. An applet can also play sound files, show animations, and process user input.

Applets are part of the Abstract Windowing Toolkit (AWT) class hierarchy. JApplet inherits from Applet, which inherits from Panel, which inherits from Container, which inherits from Component.

java.lang.Object extended by java.awt.Component extended by java.awt.Container extended by java.awt.Panel extended by java.applet.Applet extended by javax.swing.JApplet

Both the Container and Component classes have large amounts of functionality that can be used in applets. For example, the Component class passes down a number of event-handling methods to applets.

And because an Applet is also a Container, it can contain graphical elements, such as images, text boxes, buttons, and menus.

The Java applet life-cycle

Before loading an applet, a browser needs to reserve onscreen space for it. Then the browser locates the applet’s class file and transfers it over the network to the client computer.

Finally, the browser creates an instance of the Applet class.

If two identical applets are included in a web page, the browser will load the applet’s class file just once and create two instances of it, both of which will execute independently.

An applet stops running if the user navigates to another page, minimizes the window in which the applet is displayed, or closes the application in which the applet is running. The applet will start running again when the user returns to the page or maximizes the window.

Applets can be reloaded, just like web pages. When you reload them, applets stop running and then perform a final cleanup to release the system resources they have been using. The browser then unloads and reloads the applet.

Applets also stop and perform a cleanup when you close the browser or application in which they have been running.

The Applet class provides methods that are called automatically at each applet milestone. You can, optionally, override the base methods to provide suitable functionality for each milestone. The methods are

  • init
  • start
  • stop
  • destroy
init
The init method initializes an applet each time it is loaded. It contains the initialization code normally found in a class’s constructor. Applets don’t need constructors because, unlike applications, they don’t have a full environment in which to run until they are initialized.

Along with the start and paint methods, the init method also replaces the main method in applications.

start
The start method is called each time an applet starts executing. The start method is the most common method you override, and it is where you place most of the applet’s functionality, other than event handling.
stop
When an applet is stopped for some reason, such as a user exiting the web page, then the stop method is called by the browser. You can put code in the stop method to temporarily halt threads, or to release valuable resources. The start and stop methods operate in tandem.
destroy
The destroy method is called just before an applet is unloaded. It can be useful to release resources or shut down independent threads before unloading.

Although simple applets can use the default implementations of the applet milestone methods, more complex applets must override the default methods in order to produce custom behavior.

For example, the default implementations of the init and start methods do nothing. So, if you want an applet to perform a task when it starts – such as loading graphics – you must write code for the init or start methods.

If you override an applet’s start method, you generally also need to override its stop method.

Consider the code that illustrates the life-cycle of a typical applet.

You have to import the Applet class from the java.applet package, and import graphics-handling capability from the java.awt package.

import java.awt.* ;
import java.applet.Applet ;

public class LifeCycle extends Applet {

  TextArea t ;

  public void init() {
    t = new TextArea (30, 10) ;
    this.add (t ) ;
    t.append ("init\n") ;
  }
  public void start() {
    t.append ("start\n") ;
  }
  public void stop() {
    t.append ("stop\n") ;
  }
  public void paint (Graphics g) {
    t.append ("paint\n") ;
  }
  public void destroy() {
  }

}

You then extend the Applet class to create a custom applet.

Each of the milestone methods – init, start, stop, and destroy – are overridden. Each method must be declared as public, to be available to the browser, and return void. They do not take any arguments.

The paint method - inherited from Component – is responsible for refreshing the applet’s physical appearance after it is hidden or otherwise covered.

import java.awt.* ;
import java.applet.Applet ;

public class LifeCycle extends Applet {

  TextArea t ;

  public void init() {
    t = new TextArea (30, 10) ;
    this.add (t ) ;
    t.append ("init\n") ;
  }
  public void start() {
    t.append ("start\n") ;
  }
  public void stop() {
    t.append ("stop\n") ;
  }
  public void paint (Graphics g) {
    t.append ("paint\n") ;
  }
  public void destroy() {
  }

}

On all platforms, applets can play sound files, show pictures, get mouse clicks and keystrokes from the user, and send the information the user has entered to its source computer.

This is sufficient to display information, or to get information from the user – to complete an order form, for example.

Applets are restricted in what they can do to ensure user security. When a user goes to a web page that contains an applet, the web browser automatically downloads and executes the applet – the user has no control in the matter.

So applets must operate within a restricted environment to prevent applet code that has been badly written, or that is malicious, from being downloaded. This restricted environment is known as the sandbox. Applets operating within the sandbox are unable to spy on or change the user’s system in any way.

The sandbox security model is made up of the

  • Applet security manager
  • Applet class loader
  • Bytecode verifier
Applet security manager
Whenever a dangerous operation is about to be carried out, code in the Java library checks with the security manager. The security manager takes into account which class loader is loading the requesting class. Built-in classes are considered to be more trustworthy than classes that have been loaded over the Internet. If an applet tries to breach one of the access rules, the security manager throws a SecurityException.
Applet class loader
The applet class loader decides whether an applet can add classes to a running Java environment. It prevents applets from overwriting important parts of the Java runtime environment.
Bytecode verifier
Before the applet is loaded, the bytecode verifier checks that the format of a bytecode fragment is correct. It also checks that bytecode doesn’t give incorrect type information or attempt to use pointer arithmetic.

The sandbox security model restricts the operations applets can carry out. Applets cannot

  • load programs on to the client computer
  • connect to a computer other than its source
  • read, rename, write, or delete files on the client machine
  • run a program from the client’s hard drive
  • open a window that looks like an application

Suppose that an applet attempts to delete a file from the client’s machine. Before that can occur, the Java API code informs the security manager, which uses the checkDelete method to check whether that operation is permissible.

If it is not, then the security manager throws a SecurityException to the Java program.

If the operation is permissible, the security manager call returns without throwing an exception. The Java API then performs the requested operation.

The sandbox security model can prevent an applet from carrying out its full functionality, even if it is not malicious. For example, it might be necessary for an applet on a company’s intranet to be able to read, rename, and delete files on the network.

A signed applet has a certificate that identifies the signer. You can give the applets of trusted signers additional rights. There are various levels of trust that can be assigned to signed applets, from allowing them to carry out just certain operations, to complete trust, which gives them the same access to the client machine as a local application.

1. The APPLET tag

Once you’ve created and compiled an applet, you can run it in a web page. To do this, you need to add the HTML tag <APPLET> to the page. This tag tells the browser to prepare to place an applet into the page, and then the browser uses information within the tag to determine where to find the applet’s class file.

Note

Many browsers now expect the <OBJECT> or <EMBED> tags. These more general tags have the same form and syntax as <APPLET>.

In its simplest form, the <APPLET> tag has just three attributes. The CODE attribute specifies the name of an applet’s class file.

The WIDTH attribute determines the width of the area in which the applet is displayed in the browser.

The HEIGHT attribute determines the height of the area in which the applet is displayed in the browser.

<HTML>
<HEAD>
<TITLE>HTML used to run an applet</TITLE>
</HEAD>
  <BODY>
  This HTML code runs an applet.
    <APPLET CODE = "SampleApplet.class"
    WIDTH = 150  HEIGHT = 50>
    </APPLET>
  </BODY>
</HTML>

You can use the simple version of the <APPLET> tag’s CODE attribute only when the class file of the applet you want to run is in the same directory as the HTML page that references it.

<HTML>
<HEAD>
<TITLE>HTML used to run an applet</TITLE>
</HEAD>
  <BODY>
  This HTML code runs an applet.
    <APPLET CODE = "SampleApplet.class"
    WIDTH = 150  HEIGHT = 50>
    </APPLET>
  </BODY>
</HTML>

If the applet’s code is in a different directory, it will have a different URL to the HTML page. If this is the case, you specify the URL of the applet using the <APPLET> tag’s CODEBASE attribute.

<BODY>
This HTML code runs an applet.
  <APPLET CODE = "SampleApplet.class"
  WIDTH = 150 HEIGHT = 50
  CODEBASE = "http://www.brocadero.com/
  samples/SampleApplet.class">
  </APPLET>
</BODY>

You can use both absolute and relative URLs for the CODEBASE attribute.

If you use a relative URL, browsers interpret it relative to the URL of the HTML document that contains the <APPLET> tag.

Using an absolute URL, on the other hand, enables you to load an applet from any location – even from a different HTTP server.

<BODY>
  <APPLET CODE = "AppletOne.class"
  WIDTH = 150 HEIGHT = 50
  CODEBASE = "samples/AppletOne.class">
  </APPLET>

  <APPLET CODE = "AppletTwo.class"
  WIDTH = 150 HEIGHT = 50
  CODEBASE =
  "http://www.brocadero.com/samples/AppletTwo.class">
  </APPLET>
</BODY>

The <APPLET> tag has other optional attributes in addition to the CODEBASE attribute. For example, you can use the NAME attribute to specify the applet’s name. This enables applets on the same page to communicate.

And you can use the ALIGN attribute to specify the on-screen position of the applet.

<BODY>
There are two applets on the page and the
NAME attribute allows them to communicate.
  <APPLET CODE = "AppletOne.class" WIDTH = 150
  HEIGHT = 50 NAME = "Applet1" ALIGN = top>
  </APPLET>

  <APPLET CODE = "AppletTwo.class" WIDTH = 150
  HEIGHT = 50 NAME = "Applet2">
  </APPLET>
</BODY>

Some browsers cannot run applets or cannot interpret the <APPLET> tag. You use HTML code between the <APPLET> and </APPLET> tags to display explanatory text in browsers that are not Java-compliant. Java-compliant browsers will ignore this HTML code.

But if you want to display text in Java-compliant browsers that can’t run applets, you use the ALT attribute.

<BODY>
  <APPLET CODE = "SampleApplet.class"
  WIDTH = 150 HEIGHT = 50
  ALT = "Your browser is unable to run applets.
  This may be because of your security settings.">
  Because your browser is not Java enabled,
  it cannot run this applet.
  </APPLET>
</BODY>

The PARAM tag

You can add an applet to more than one web page and alter some of its characteristics. This allows you to create a few general-purpose applets and then customize them for particular purposes.

You can customize an applet at design time by altering its code, or you can customize it at runtime using the HTML <PARAM> tag.

Parameters are like properties, and come in name-value pairs. The <PARAM> tag has two attributes – NAME and VALUE.

The NAME attribute specifies the name of the parameter you are passing.

The VALUE attribute specifies the parameter’s value. In the example, the HTML code sets the value of the DisplayString parameter.

<APPLET CODE="ClickHere.class"
WIDTH=350 HEIGHT=250>
  <PARAM NAME = "DisplayString"
  VALUE = "This is a parameter string.">
  </PARAM>
</APPLET>

<PARAM NAME = appletParameter VALUE = value>

To ensure that the applet to which you pass parameters is able to deal with them, you use the Applet class’s getParameter method in your code.

Consider the code in which the getParameter method retrieves the value the user has specified for the ParameterString parameter. That value is displayed on screen when the applet runs.

import java.applet.Applet ;
import java.awt.Graphics ;
public class ParamApplet extends Applet {

  String param = "This is the default string" ;
  public void init () {
    String temp = getParameter ("ParameterString") ;
    if (temp != null) {
      param = temp ;
    }
   }
  public void paint(Graphics g) {
    g.drawRect (0, 0, 200, 100) ;
    g.drawString (param, 35, 50) ;
  }

}

getParameter(String name)

The getParameter method always returns a string when the parameter exists, so you sometimes need to use methods from the java.lang package to convert its return value into another datatype.

Calls to getParameter for non-existent parameters in the HTML file result in a null return value.

Your code should check for null values as a matter of course.

import java.applet.Applet ;
import java.awt.Graphics ;
public class ParamApplet extends Applet {

  String param = "This is the default string" ;
  public void init () {
    String temp = getParameter ("ParameterString") ;
    if (temp != null) {
      param = temp ;
    }
   }
  public void paint(Graphics g) {
    g.drawRect (0, 0, 200, 100) ;
    g.drawString (param, 35, 50) ;
  }

}

It’s a good idea to specify default values in code for any parameters that must be set by the user. This ensures that an applet runs even if a user fails to specify a value for a parameter.

import java.applet.Applet ;
import java.awt.Graphics ;
public class ParamApplet extends Applet {

  String param = "This is the default string" ;
  public void init () {
    String temp = getParameter ("ParameterString") ;
    if (temp != null) {
      param = temp ;
    }
   }
  public void paint(Graphics g) {
    g.drawRect (0, 0, 200, 100) ;
    g.drawString (param, 35, 50) ;
  }

}

Using the Java Plug-In

Every time Sun Microsystems updates its Java technology, it releases a new version of Java through the Java Development Kit. Browser vendors support the update by including the latest version of the runtime component in their next release of the browser.

So there is a period of time between the Java release and the browser release in which developers cannot make use of Java’s latest features and bug fixes.

The Java Plug-In solves this problem by bypassing the browser vendors, and connecting the browser directly to an external Java Runtime Environment (JRE).

The browser won’t know that it should be using the JRE unless the web page tells it to. By using the <OBJECT> and <EMBED> tags instead of the regular <APPLET> tag, the web page forces the browser to launch the Java Plug-In, which runs the applet using the JRE.

Internet Explorer uses the <OBJECT> tag, and Netscape recognizes the <EMBED> tag on the Windows and Solaris platforms. The tags tell the browser which plug-in is required and where to get it.

The HTML Converter is a tool that converts <APPLET> tags in an HTML file to <OBJECT> and <EMBED> tags. It is part of the Java 2 SDK1.4.2 download. By default, HTML Converter creates a backup of the file in a separate folder.

Suppose that you want to convert the LifeCycle.html file, which has <APPLET> tags, to a file that is supported by the Netscape and Internet Explorer browsers on the Windows and Solaris operating systems.

You navigate to the folder containing HTML Converter, in this case C:\j2sdk1.4.2_04\bin, and double click HtmlConverter.exe.

The application launches. You can convert a single file, or multiple files at one time.

You click the “Specify a file or a directory path” Browse button to access the Open dialog box. You browse to the LifeCycle folder and double-click LifeCycle.html.

You return to the HTML Converter window and click the Convert button.

The Progress window states how many files were converted, whether there were any errors, and how many applets were found.

When the applet is launched from the new HTML page, the browser will ask you for permission to run the Java Plug-In.

Here is the new applet HTML file, after conversion.

<OBJECT
classid = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
codebase = "http://java.sun.com/update/1.4.2/
jinstall-1_4-windows-i586.cab#Version=1,4,0,0"
WIDTH = 220 HEIGHT = 110 >
  <PARAM NAME = CODE VALUE = "LifeCycle.class" >
  <PARAM NAME = "type"
  VALUE = "application/x-java-applet;version=1.4">
  <PARAM NAME = "scriptable" VALUE = "false">

  <COMMENT>
  <EMBED
  type = "application/x-java-applet;version=1.4" \
  CODE = "LifeCycle.class" \
  WIDTH = 220 \
  HEIGHT = 110 \
  scriptable = false \
  pluginspage =
  "http://java.sun.com/products/plugin/index.html#download">
    <NOEMBED>

    </NOEMBED>
  </EMBED>
  </COMMENT>
</OBJECT>

Posted in Uncategorized | Leave a Comment »

What’s in Java 6, 5, 4 and <4? What about Java 7.0?

Posted by SARAVANAN SIVAJI on May 30, 2009

The following link will list new features introduced in Java 6 over 5,
http://java.sun.com/javase/6/webnotes/features.html#changes

The following link will list new features introduced in Java 5 over 1.4,
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html

The following link will list new features introduced in Java 1.4.2 over previous releases,
http://java.sun.com/j2se/1.4.2/docs/relnotes/features.html

—————————————————————————

Apart from that, here is the link will give you smart summary of versions

http://en.wikipedia.org/wiki/Java_version_history
&
http://wiki.answers.com/Q/What_is_the_difference_between_java_1.5_and_1.6

———————————————————————————–

Here is the New Java 6 API

http://java.sun.com/javase/6/jcp/beta/apidiffs/index-diffs.html

What’s Next? Java SE7

The Java Platform, Standard Edition 7 Development Kit (JDK 7) has not been officially released. No appropriate release documentation is available at this time.

Posted in Uncategorized | Leave a Comment »

A Bird view on JAVA Utilities

Posted by SARAVANAN SIVAJI on May 30, 2009

The Java Math class

The Math class – located in java.lang.Math – provides a set of methods and two constants for common computations.

The Math class is final, which means that you cannot extend it.

In addition, you cannot create an instance of the Math class because the constructor is private.

All methods and both constants of the Math class are static, so you don’t need to construct a Math object to access them.

Instead, you can simply access them through the class name – Math.

Java wrapper classes

There are eight primitive types in the Java language and each of these has a wrapper class associated with it.

The wrapper classes enable you to treat primitive values as though they were objects. You use the wrapper classes for primitive data types when you need to represent alphanumeric values as objects instead of primitives.

Wrapper methods can

  • parse strings into numeric values
  • transform values back into strings or other primitive types
  • test values

//convert the string to an integer
try{
int i= Integer.parseInt(s) ;
System.out.println(“Converted to int val = ” + i) ;

}catch(numberFormatException nfe){
System.out.println(“Could not convert to int”) ;
}

// convert an integer into a string
int j=537 ;
String myString = Integer.toString(j) ;

// check that each string element is a digit
for (count = 0; count < myString.length(); count ++){

boolean digit = Character.isDigit(myString.charAt(count));

———————————————————————————————————————————-

There are several ways to construct a wrapper object.

One way is to pass the value to be wrapped into the constructor of that wrapper class.

With the exception of the Character wrapper class, you can also construct an instance of each wrapper class by passing a string that represents the value to be wrapped into the constructor.

Byte wrapclassByte = new Byte (“12″) ;

try {
Short wrapclassShort = new Short (“12345″) ;
Integer wrapclassInteger = new Integer (“12345678″) ;
Long wrapclassLong = new Long (“1234567890″) ;
Float wrapclassFloat = new Float (“1.234f”) ;
Double wrapclassDouble = new Double (“1.12345678″) ;

} catch (NumberFormatException e) {
System.out.println (“Invalid number format.”) ;
}

You can also use the valueOf method of each wrapper class with a String argument. This converts the string argument to a wrapper object.

Boolean wrapclassBoolean = Boolean.valueOf(“true”) ;

To construct a Character class instance, you can pass the constructor only a character.

public Character(char value) {}

Apart from Boolean and Character – all the constructors throw a NumberFormatException when they are passed a non-numeric string.

Wrapper objects can wrap boolean values, character values, and numeric values. When you work with wrapper objects you can

  • check contained values for equality
  • extract boolean and char values from them
  • extract numeric types from them
  • use them to add elements to a vector

The equals method returns true or false to indicate whether two values are equal, whereas the compare method tells you which value is greater if they are unequal.

You may need to extract wrapped values from instances of Boolean and Character.

To extract a boolean value from an instance of Boolean, you call the booleanValue method.

Similarly, you call the charValue method to extract a char value from an instance of Character.

Short s = new Short ((short) 145) ;
Integer i = new Integer (635) ;
Long l = new Long (-1827) ;
Float f = new Float (829.65f) ;
Double d = new Double (-1262.006) ;

short sl = d.shortValue() ;
int k = d.intValue() ;
long il = d.longValue() ;
float fl = i.floatValue() ;
double dl = s.doubleValue() ;

—————————————————————————————–

To get integer value from Float object

Float myFloat = new Float (3.14f) ;

myFloat.intValue();

The following static methods of the Character class enable you to test for various properties of a character:

  • isWhitespace
  • isLetter
  • isLowerCase
  • isUpperCase

Java String and StringBuffer classes

1. The String class

Java uses 16-bit Unicode characters to encode string data.

This technique enables Java to encode up to 65,536 different characters. This means Java can store and display the alphabets and characters of a large number of languages.

In Java, you can encapsulate strings with either the String class or the StringBuffer class.

The String class extends the Java Object class and implements the Serializable, Comparable, and CharSequence interfaces.

public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence

There are various types of constructor associated with the String class. These allow you to build an instance from

  • an array of bytes  —  public String(byte[] bytes)
  • a subset of an array of bytes  —   public String(byte[] bytes, int offset, int length)
  • an array of characters — public String(char[] value)
  • a subset of an array of characters — public String(char[] value, int offset, int count)
  • another String object — public String(String original)
  • a StringBuffer object —  public String(StringBuffer buffer)

Strings are immutable – once they are created, their values cannot be changed. They cannot be changed or deleted. They can be garbage-collected when there are no longer any references to them, but even garbage collection is implementation defined.

When you assign a new string literal to a String variable, you are actually creating a new String object rather than changing the value of an existing string.

Because Java uses an instance of the String class to represent every string literal, each application will have a pool of string literals.

When you compile your code, the compiler compares all literal strings it encounters to those already in the pool. The compiler then adds each literal string to the pool, unless it is already represented.

If the literal string is already represented in the pool, the compiler saves memory by using the existing copy. It can do this because the string is immutable.

Using regular expressions with strings

When you write code that deals with input, you often need to process inputted text to ensure it is in a specific format.

To check whether a sequence of characters matches a particular pattern, you use a regular expression.

In Java, you use the Pattern and Matcher classes in the java.util.regex package to create and use regular expressions.

To make use of regular expressions you need to

  • define a regular expression
  • apply it to a sequence of characters

import java.util.regex.* ;
class PattMatch {
public static void main(String args[]) {
Pattern patt = Pattern.compile(“[0-9][0-9][a-z]“) ;
Matcher match = patt.matcher(“lmn89t”) ;
boolean matchFound = match.matches() ;
if (matchFound)
System.out.println(“Match was found.”) ;
else
System.out.println(“No match.”) ;
}
}

Java system operations

Java uses two application programming interfaces (APIs) to access system resources – the System class, which is relatively system independent, and the Runtime class, which is completely system dependent. The System class is adequate for most programming requirements.

All members of System are class members, so you can reference the methods and variables of the System class without instantiating a System object. In fact, you cannot instantiate the System class because all its constructors are private

The System class offers access to externally defined properties, a method to copy parts of an array, and standard input and output streams.

When you are programming for a particular device, one or more of the I/O classes may be redundant. For example, an embedded Java device might have no standard output.

You can use System class methods to reassign the standard I/O streams, using existing streams. You should avoid reassigning standard streams wherever possible, because unexpected results could occur.

Consider the syntax for assigning an input stream to the standard stream.

If you want to test an application using different sets of input which are stored in a file, you might create a new input stream to accept input from a file instead of the keyboard.

System.setIn (InputStream in)

Some Java devices don’t have standard output, so sometimes it is better to create and send output to a file, instead of printing it to a display device.

You use SetOut to assign a new output stream to the standard output stream.

System.setOut (PrintStream out)

You can use SetErr to separate error output from standard, non-error output, by redirecting standard error to a file, rather than defaulting to the display device.

System.setErr (PrintStream err)

Examples of system property values

Some of the system properties along with examples of their values are listed in the table that follows.

System properties table
Key Description Example value
"file.separator" File separator forward slash “/”
"line.separator" Line separator new line “\n”
"path.separator" Path separator colon “:”
"java.class.path" Java class path .:/mydir/classes
"java.class.version" Java class format version number 45.3
"java.home" Java installation directory /java/solaris
"java.vendor" Java Runtime Environment vendor Sun Microsystems Inc
"java.vendor.url" Java vendor URL http://www.sun.com
"java.version" Java Runtime Environment version 1.3.1
"os.arch" Operating system name sparc
"os.name" Operating system architecture Solaris
"os.version" Operating system version 4.0
"user.dir" User’s current working directory /mydir/java
"user.home" User’s home directory /mydir
"user.name" User’s account name ted

To access or modify system properties, you use the getProperty, getProperties, setProperty, and setProperties methods of the System class.

You use the getProperty method to access a single system property. The method uses the key name as a string – for example "java.class.path" – to search for a property.

System.getProperty ("java.class.path") ;

To retrieve all the system properties simultaneously, you can use the getProperties method, which returns a Properties object.

System.getProperties() ;

The getProperty method returns null if the property doesn’t exist. A NullPointerException occurs when the search key argument is null.

You can prevent your program encountering a NullPointerException by supplying two arguments to the getProperty method.

The first argument is the system property, whereas the second argument is the value to be returned if the system property is invalid.

System.getProperty ("Invalid system Property",
 "Property not found!") ;

You can use the setProperties method to modify system properties for the current application.

The setProperties method throws a SecurityException if the checkPropertiesAccess method of an installed SecurityManager doesn’t allow access to the system properties.

The runtime environment is an instance of the Runtime class. It comprises the Java Virtual Machine (JVM), the Java Interpreter, and the operating system.

Your Java program interfaces to the runtime environment through the Runtime class.

The System class provides a number of useful methods, including

  • arraycopy --- public static arraycopy (Object src,int src_pos, Object dst, int dst_pos, int length)
  • currentTimeMillis --- public static long currentTimeMillis()
  • exit --- System.exit (0) ;
  • gc --- System.gc();
You use the arraycopy method to copy a segment of one array to another array. However, arraycopy is a native method, meaning its implementation is system-dependent.

public class CopyElements {
public static void main (String [] args) {
char [] sourceArray = {‘H’, ‘a’, ‘r’,'d’, ‘w’, ‘a’, ‘r’, ‘e’};
char [] destinationArray = {‘a’, ‘n’,'d’, ‘ ‘, ‘S’, ‘o’, ‘f’, ‘t’, ‘x’,'x’, ‘x’, ‘x’} ;
System.arraycopy (sourceArray,4, destinationArray, 8, 4) ;
System.out.println (new String (destinationArray)) ;
}
}

When the gc method has finished, the JVM has made its best effort to reclaim as much memory space as it can from discarded objects. You should always set an object to null to make it eligible for collection.

Collection Framework interfaces

The core collection interfaces are the basis for the Collection Framework. These include

  • Collection
  • Set
  • List
  • Map
  • SortedMap
  • SortedSet

All classes that implement the Collection interface directly are general-purpose collections. Some of these collections allow for duplicate values, like List-based collections, whereas others don’t.

Some collections can impose a natural ordering on their contained objects.

A List - also known as a sequence – can contain duplicate elements which are stored in a specific order. You order elements in a list by using an integer index. Elements can easily be inserted anywhere in a list.

Elements using a list structure can be represented as an ArrayList, a LinkedList, or a Vector.

The List interface extends the Collection interface directly and has extra operations for

  • list Iteration
  • range-view
  • searching
  • positional access

List iteration is the operation that enables you to move through a list in any direction, and to return the current position of the iterator. Unlike iterator, listIterator allows you to change the list during iteration, although any additions may not be reflected by the current iteration.

A Set is a collection that cannot contain duplicate elements. Set extends the Collection interface and inherits all its methods.

The Set interface is a model of the mathematical set abstraction, and elements can be represented as a HashSet if order is not important.

SortedSet extends the Set interface, and keeps its elements in ascending natural order.

A Map is not a true collection because it contains key-value pairs. It can contain no duplicate keys, and each key can map to only one value.

The HashTable is an example of how data can be stored and manipulated using the Map interface.

SortedMap is an extension of the Map interface. A SortedMap is an object that keeps its elements in ascending key order. Elements may also be sorted using a Comparator that you supply when creating a sorted map.

A group of nonordered elements is a Collection. If a group is ordered and allows duplicates, it’s a List. If the collection cannot contain any duplicate elements, it’s a Set. If the collection contains groups of key-value pairs in no specific order, it’s called a Map.

The Map interface acts on ordered as well as unordered maps. The lastKey method is used to quickly navigate to the last, or highest, element in a sorted map.

The SortedMap interface contains the lastKey method. This method requires that the map be ordered so that it can return its highest value.


Posted in Uncategorized | Leave a Comment »

GUI Development Basic using JAVA – Part 1

Posted by SARAVANAN SIVAJI on May 28, 2009

Overview of JFC

JFC – Java Foundation Classes – collection of APIs.  Provides GUI support as part of the Java 2 platform

JFC superset of AWT.

The JFC consists of several APIs,

1. AWT — Java’s original GUI toolkit.  It was designed to enable the development of simple user interfaces (UIs) by providing a limited set of GUI objects, or components, such as buttons, frames, and menus.  The AWT has a peer-based architecture in which native UI components, or peers, are associated with each AWT component to enable them to run on a specific platform.

2. Swing — latest Java GUI component kit.  Written only in Java.  All Swing components conform to the Model-View-Controller (MVC) architecture.

3. Accessibility — The Accessibility API provides an interface that enables assistive technologies to interact with JFC and AWT components. Assistive technologies include screenreaders, Braille displays, and speech recognition devices. For maximum portability across platforms, this API is written in pure Java.

4. Drag-and-Drop — The Drag-and-Drop API improves application interoperability because it provides the ability to drag and drop between a Java application and a native application. You must know which drop formats the native application can accept because the target drop area is handled from within the foreign application.

5. Java 2D — The Java 2D API is a set of classes that enable developers to easily incorporate advanced, high-quality 2D graphics, text, and images into applications and applets.  Using Java 2D, you can create 2-dimensional objects and rotate or bend them to simulate 3-D effects. This API is useful for mathematical and charting applications. A Java 3D API is available but this doesn’t form part of the core API.

AWT provides the foundation on which many JFC classes are built and forms the basis of Swing. For example, Swing components directly extend AWT components such as Window, Dialog, and Frame.

Swing does not replace AWT.   Swing is lightwieght.  All the existing AWT classes can still be used, but they are not recommended due to the superiority of the Swing classes.

Swing is built on top of AWT, it uses some of the AWT utility classes such as Font,  Color and Graphics and extends its component classes.

The JFrame and JDialog swing components directly extend the AWT Frame and Dialog classes.

For instance,

java.lang.Object extended by java.awt.Component extended by java.awt.Container extended by java.awt.Window extended by java.awt.Frame extended by javax.swing.JFrame

public class JFrame extends Frame implements WindowConstants, Accessible, RootPaneContainer

Why Swing Components are lightweight?

Swing components are referred to as lightweight components because they are not based on any platform-specific implementations and are written from scratch without using any native code.  By contrast, the AWT creates a window that is native to its host environment. So Swing is flexible and portable because it doesn’t have the overhead of AWT.

AWT components display slightly differently, depending on the host environment. Swing components offer a more uniform look and feel across platforms.

“The main reason that Swing does not directly use any AWT components is that they contain native code - many Swing components simply provide a 100 percent Java implementation of the heavyweight AWT components.”

Swing provides pluggable look and feel (PLAF) support, which is one of the most valuable capabilities of the Swing toolkit. PLAF is complemented by the MVC model of Swing components.

1. Swing components and containers

Graphical user interface (GUI) applications consist of several user interface objects, including buttons, menus, windows, and panels. In Java, these graphical elements are known as components.

Containers – for example frames, windows, and dialogs – are components that control how other components are arranged onscreen by dividing them into groups. They also control how other components behave.

A component alerts its container whenever its size or position changes, so the container’s layout manager can automatically adjust the components it contains.

Note

A layout manager, if installed, is responsible for automatically laying out components in a container.

A GUI’s onscreen display consists of components organized by at least one top-level container. This is known as a component hierarchy. When creating a Java GUI application, you place each component in a container.

Swing is a Java-based user interface toolkit that contains a library of prewritten components.

Each Swing component inherits from the javax.swing.JComponent class. This class enables Swing to display graphics and access offscreen information in response to user input.

For instance,

//

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.AbstractButton
                  extended by javax.swing.JButton

Swing is based on classes that it inherits from the Abstract Windowing Toolkit (AWT). The JComponent class derives from the Container class, which is a subclass of the Component superclass. AWT’s components derive from this class, which derives from the Object class.

As a result, the Swing and AWT component hierarchies are similar. For example, the top-level Swing containers – JFrame, JWindow, and JDialog – respectively extend the AWT classes Frame, Window, and Dialog. JApplet extends Applet.

The root container for a Swing applet is a JApplet and the root container for a standalone GUI application is a JFrame. Once you’ve created a root container, you can add components and other containers to the root.

For example, you can add windows or dialogs using the top-level containers JWindow or JDialog. You can also use the JComponent class or a JPanel – a generic container – to group components inside other containers.

Note

A JWindow is a window without a border and JFrame, which derives from JWindow, is a window with a border.

Each JFrame, JWindow, and JDialog has several panes:

  • Root pane
  • Layered pane
  • Content pane
  • Glass pane
Root pane
The root pane is an intermediate container that manages the layered pane, content pane, and glass pane, as well as a menu bar if necessary. You can paint multiple components or let the component handle mouse events by changing a container’s root pane settings.
Layered pane
The layered pane holds components arranged in overlapping layers, which enables you to add popup items to applications. It also directly contains the root pane’s content pane and its optional menu bar.
Content pane
To display components, you add them to the container’s content pane. The content pane, which covers the container’s display area, contains and manages all the root pane’s onscreen components except the menu bar. Java automatically creates a content pane for each new JFrame or JWindow.
Glass pane
The glass pane is invisible by default, but you can use it to paint over components or to superimpose an image above other components. Like the root pane, you can also use it to enable components to catch input events.

In addition to the top-level containers, you can use low-level containers – such as JInternalFrames or JPanels – to create Multiple Document Interface (MDI) GUIs. Internal frames and panels subdivide the display area defined by top-level containers.

Usually, you add instances of the JInternalFrame to a desktop pane, JDesktopPane. Internal panes have root panes like regular JFrames, so there is little difference between setting up a GUI using JInternalFrames or setting up one using JFrames.

Once you’ve defined the necessary display areas for an application with containers and panes, you can add interface components such as radio buttons, scrollbars, and menus using Swing’s large collection of prewritten elements.

Question

Match each Swing container to its description.

Options:

  1. JApplet
  2. JComponent
  3. JFrame
  4. JPanel
  5. JWindow

Targets:

  1. A generic low-level container
  2. The root class for all Swing components
  3. The root container for a standalone application

Answer

JPanel is a generic low-level container, JComponent is the root class for all Swing components, and JFrame is the root container for standalone applications.

JApplet is the root container for all Swing applets. Like the other top-level containers, it is based on a top-level AWT container.

All components in the Swing toolbox derive from the JComponent class – javax.swing.JComponent – which derives from AWT’s Container class.

All standalone Swing applications use a JFrame as their root container. You can add components to the content pane of the JFrame.

A JPanel is a generic low-level container used to group components inside other containers by subdividing the display area.

JWindow is a top-level Swing container that you can use to add a window to a Java application. By definition, a JWindow does not have a border.

2. The JComponent services

All Swing components – for example, JLabel, JButton, and JScrollPane – descend from the JComponent class. This class derives from the Container class and enables you to add components to containers.

The functionality for each JComponent is provided by its ComponentUI. How each component displays depends on the installed look and feel.

The JComponent class provides a wide variety of functionality to its instances. For example, you can

  • customize component appearance
  • check component state
  • specify event handling
  • paint components
  • change the containment hierarchy
  • lay out components
  • get and set component size and position
customize component appearance
You can modify the appearance of components by selecting a border, foreground color, background color, font, and a cursor to display when hovering over the component. You can also make the component opaque.
check component state
JComponent lets you check the state of components. For example, you can determine whether a component and its container are visible onscreen and whether a component is enabled to generate events in response to user input. You can also add tooltips and specify component names.
specify event handling
JComponent enables you to customize event listeners for mouse clicks, mouse movements, key presses, or changes to components. You can also check which component contains a specific point or enable data transfer handling.
paint components
You can customize painting for any JComponent or subclass of JComponent. You can also repaint a component, repaint a specific area of a component, and refresh the layout of a component and its containers.
change the containment hierarchy
You can add or remove components from a container. You can also find out how many components are in a container and determine a component’s root pane, direct container, and topmost container.
lay out components
You can add components using an absolute position or a layout manager. You can also get or set a component’s alignment and orientation, as well as the container’s layout manager. When using a layout manager, you can specify a preferred, maximum, or minimum size for each component.
get and set component size and position
You can set a component’s position according to a fixed position or relative to other components. However, some layout managers may ignore absolute positions. You can also retrieve information about a component’s current height, width, size, its position relative to its parent, and the width of its border.

The Swing API includes a vast collection of methods, but there are a number of commonly-used methods that you should be familiar with.

For example, you use the add method to add GUI components directly to containers or to their content panes. To remove a component from a container, you use the remove method.

To set the colors for a component, you use the setForeground and setBackground methods. To refresh a component, you use the repaint method. And you can use the setLayout method to specify a layout manager.

If you do not want to use a layout manager, you call the setSize method to set an absolute size for a frame or window. You can also use the setBounds method to set the width, height, and relative location for a component. However, an installed layout manager will override most manual settings.

Question

Which services does the JComponent class provide to its subclasses?

Options:

  1. Adding event handling
  2. Painting components
  3. Resizing components
  4. Setting the layout

Answer

The JComponent class enables its subclasses to add event handling, paint components, and resize components.

Option 1 is correct. You can add event listeners to handle mouse clicks, mouse movements, key presses, or changes to components.

Option 2 is correct. You can specify a foreground and a background color for components. You can also repaint a component or refresh the layout of a component and its containers.

Option 3 is correct. You can get and set a component’s current height, width, and size. You can also change its position and the width of its border.

Option 4 is incorrect. You set a layout against a container, which defines how contained components are presented on the display surface.

Question

The JComponent class enables you to customize the appearance of components and containers.

Which methods enable you to resize components?

Options:

  1. setBounds
  2. setLayout
  3. setForeground
  4. setSize

Answer

You can resize components using the setBounds and setSize methods.

Option 1 is correct. You use the setBounds method to set the width, height, and relative location for components in a container.

Option 2 is incorrect. You use the setLayout method, which is inherited from java.awt.Container, to specify a layout manager. If you use a layout manager, you resize components using the setBounds method.

Option 3 is incorrect. You use the setForeground and setBackground methods to set a component’s colors.

Option 4 is correct. If you do not want to use a layout manager, you can use the setSize method to specify an absolute size for components.

3. Using containers and components

Each Swing applet and application has a containment hierarchy with a top-level container at its root. For example, you create a dialog within a JFrame by adding a JDialog container to its content pane. You can then add various components and low-level containers, such as JButtons, JScrollBars, JTables, and so on.

Usually, you add components directly to containers using the add method. However, to add components to a JFrame or JWindow, you add the components to the container’s content pane. To do this, you retrieve the content pane for the frame or window using the getContentPane method.

After you’ve added a container, you need to make it visible. To do this, you use the setVisible method. You can use the isVisible method to determine whether or not a component is visible.

Once you’ve added components and containers, you can set

  • size
  • focus
size
You can call the setSize method to set an absolute size for a container. If you want the frame or window to automatically adjust itself to fit all its elements, you can call the pack method. The pack method ensures that the containers are not smaller than their preferred sizes.
focus
Interface items must be able to receive keyboard focus if users are to interact with them using the mouse and keyboard. Most components can receive focus by default, but you can specify this by calling the setFocusable method. You can also request that a component receive focus by using the requestFocus method.

Suppose that you’re building a Swing application that displays a different message each time the user clicks an interface item. The completed application will contain a button, a checkbox, and three radio buttons.

To begin, you import the Swing and AWT packages. Then you declare a button called commonButton, a checkbox, a ButtonGroup called icecreams to contain the radio buttons, and the three radio buttons – radio1, radio2, and radio3.

// Import swing and awt classes
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;

public class UsingButtons {
  JButton commonButton ;
  JCheckBox checkBox ;
  ButtonGroup icecreams ;
  JLabel label ;
  JRadioButton radio1 ;
  JRadioButton radio2 ;
  JRadioButton radio3 ;

Then you create a new JFrame called frame and a JPanel called pane.

  private void buildapp() {
    // Fancy decorations
    JFrame.setDefaultLookAndFeelDecorated(true) ;
    // Create and set up the frame
    JFrame frame = new JFrame("Buttons") ;
    // A JPanel holds the contents
    JPanel pane = new JPanel(new BorderLayout()) ;

You create a blank JLabel, called label, and add it to the JPanel using the add method.

To add the JPanel to the JFrame, you add the JPanel to the frame’s content pane using the getContentPane method.

// Create and add a label
label = new JLabel("    ") ;
pane.add(label, BorderLayout.CENTER) ;

// Add the JPanel to the frame
frame.getContentPane().add(pane, BorderLayout.CENTER) ;

You create a new JPanel, radiopane, which contains the three radio buttons. Then you add the button, checkbox, and the radiopane to the JPanel.

To set the focus on the button, you use the requestFocus method.

You can also set the format of the components, for example, the borders for each component.

// A JPanel will hold the contents
JPanel radiopane = new JPanel(new GridLayout(3,1)) ;
radiopane.add(radio1) ;
radiopane.add(radio2) ;
radiopane.add(radio3) ;

pane.add(commonButton, BorderLayout.NORTH) ;
pane.add(checkBox, BorderLayout.SOUTH) ;
pane.add(radiopane, BorderLayout.EAST) ;
commonButton.requestFocus() ;

To display the frame, you set the setVisible method to true.

You also want to resize the frame so that it has a width of 300 pixels and a height of 200 pixels. To do this, you use the setSize method to specify the frame’s size.

// Display the frame
frame.setSize(300, 200) ;
frame.setVisible(true) ;

The final Buttons application contains the button, the checkbox, and three radio buttons.

Question

You’re building an application that requires the user to type their user name and password. You’ve created a top-level JFrame container called frame.

Complete the code to make the frame visible onscreen.


  JFrame frame = new JFrame("Text") ;

  //Display the frame
  MISSING CODE ;
}

Answer

To make the frame visible, you set the setVisible method to true by typing
frame.setVisible(true)

Question

You’ve created four components – a JTextField, a JPasswordField, a JFormattedTextField, and a JTextArea – and added them to a JPanel called pane.

Complete the code that adds the pane to the frame.


  JPanel pane = new JPanel(new GridLayout(4,1));
  confirm = new JTextField (25) ;
  pass = new JPasswordField(20) ;
  format = new JFormattedTextField(DateFormat.getDateInstance());
  format.setValue(new Date());
  format.setEnabled(false);
  area = new JTextArea(10, 20) ;
  pane.add(confirm);
  pane.add(pass);
  pane.add(format);
  pane.add(area);
  });

  // Add the JPanel to the frame
  MISSING CODE ;

  //Display the frame
  frame.setVisible(true);
}

Answer

You add the pane to the frame’s content pane using the getContentPane method as follows:

frame.getContentPane().add(pane) ;

Question

Which line of code specifies that the JFrame called frame has an absolute width of 450 pixels and an absolute height of 220 pixels?

Options:

  1. frame.pack() ;
  2. frame.setSize(220, 450) ;
  3. frame.setSize(450, 220) ;

Answer

You specify an absolute position for the frame by using the setSize method as follows:

frame.setSize(450, 220) ;

Option 1 is incorrect. You call the pack method if you want the frame or window to automatically adjust itself to fit all its elements. This method ensures that the containers are no smaller than their preferred sizes.

Option 2 is incorrect. When using the setSize method, you specify the component’s width and then its height in pixels.

Option 3 is correct. The setSize method takes two parameters, width and height. Although this sets an absolute size, some layout managers may ignore this setting.

4. Building a basic Swing application

When you create a GUI, you can specify how each window reacts when the user clicks the Close button. You can also determine the default look and feel for windows.

To customize the way that windows and frames are decorated, you can call the JFrame class’s static setDefaultLookAndFeelDecorated method with a true value. For example, you can remove all decorations, specify custom settings, enable full-screen exclusive mode, or set the icon to use for the application. If you do not specify any custom settings, the application’s look and feel determines how windows are decorated.

This setting affects all the JFrames that you create afterwards. However, some layout managers may ignore this setting.

You use the setDefaultCloseOperation to determine what happens when users click the Close button. You can specify one of four actions:

  • HIDE_ON_CLOSE
  • DO_NOTHING_ON_CLOSE
  • EXIT_ON_CLOSE
  • DISPOSE_ON_CLOSE
HIDE_ON_CLOSE
To hide the frame without exiting the window, you use the HIDE_ON_CLOSE parameter. This is the default setting for JFrames and JDialogs.
DO_NOTHING_ON_CLOSE
If you specify the DO_NOTHING_ON_CLOSE operation, the application performs the actions specified in the WindowListener object’s windowClosing method. This is the default setting for internal frames.
EXIT_ON_CLOSE
To ensure that the application exits using the System exit method, you specify the EXIT_ON_CLOSE parameter. This parameter is particularly useful for applications – especially single-frame applications – but it is not recommended for applets.
DISPOSE_ON_CLOSE
If you specify the DISPOSE_ON_CLOSE parameter, the application automatically hides the frame and disposes of it if the user clicks the Close button. This frees up any resources that the window was using.

Suppose that you’re building a single-frame Swing application. To build a basic Swing application, you

  • import the necessary packages
  • ensure thread safety
  • create and customize a top-level container and components

Because many Swing components inherit from AWT classes, you should import both the Swing and the AWT packages. You should also import the AWT classes that support event handling, java.awt.event.*.

// Import swing and awt classes
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;

public class BasicSwingApp implements ActionListener {

Any GUI updates must be performed from within the event-dispatching thread in order to avoid threading issues.

To do this, you need to call the javax.swing.SwingUtilities.invokeLater method when creating or updating the application’s GUI. The invokeLater method requests that supplied code be executed from within the event-dispatching thread.

You pass a Runnable object to the invokeLater method. You then invoke createAndShowGUI from within the run method.

  public static void main(String[] args) {

    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI
    javax.swing.SwingUtilities.invokeLater(
      new Runnable() {
        public void run() {
          BasicSwingApp app = new BasicSwingApp () ;
          app.createAndShowGUI() ;
        }
      }
    );
  }
}

Note

The related SwingUtilities.invokeAndWait method waits for the passed code to execute, whereas invokeLater returns immediately – the supplied code is executed asynchronously.

Since all standalone Swing applications use a JFrame as their top-level container, you create a JFrame.

Once you’ve created the top-level container, you populate it with the appropriate GUI components for this application.

In the code example, you add a JPanel, a JButton, and a blank JLabel. You add the label to the button, add the button to the panel, and add the panel to the frame.

// Create and set up the frame
JFrame frame = new JFrame("A basic Swing application") ;

// A JPanel will hold the contents
JPanel pane = new JPanel(new GridLayout(0, 1)) ;

// Create a button, add an event listener,
// and add it to the JPanel
JButton button = new JButton("JButton") ;
button.addActionListener(this) ;
pane.add(button) ;
button.requestFocus() ;

// Create and add a label
label = new JLabel(buttonClicks + "0") ;
pane.add(label);

// Add the JPanel to the frame
frame.getContentPane().add(pane, BorderLayout.CENTER) ;

Once you’ve added components, you can set the characteristics of the top-level container. In this case, you want the windows to use the program’s default look and feel. And because this is a single-frame application, you want the JFrame to exit when the user closes the window.

To do this, you call the setDefaultCloseOperation method for the JFrame with the EXIT_ON_CLOSE parameter and call the setDefaultLookAndFeelDecorated method with a true value.

private void createAndShowGUI() {
// Fancy decorations
JFrame.setDefaultLookAndFeelDecorated(true) ;

// Create and set up the frame
JFrame frame = new JFrame("A basic Swing application") ;
// Close application when close button clicked
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;

Finally, you ensure that the container is visible onscreen by calling the setVisible method with a true value.

  // Display the frame
  frame.setSize(300, 200) ;
  frame.setVisible(true) ;
}

Question

Suppose you’re creating a single-frame Swing application. You want the windows to use the decorations specified in the program’s default look and feel.

Call the method that enables you to do this.


private void createAndShowGUI() {
// Fancy decorations
JFrame.MISSING CODE(true) ;

Answer

You call the setDefaultLookAndFeelDecorated method with a true value to ensure that the windows are decorated according to the program’s default look and feel.

Question

Because you’re creating a single-frame application, you want the window to exit when the user clicks the Close button.

Complete the method to do this.


private void createAndShowGUI() {
// Fancy decorations
JFrame.setDefaultLookAndFeelDecorated(true) ;
// Create and set up the frame
JFrame frame = new JFrame("A basic Swing application") ;
// Close application when close button clicked
frame.setDefaultCloseOperation(JFrame.MISSING CODE) ;

Answer

To ensure that the window exits when the user clicks the Close button, you call the setDefaultCloseOperation method with the EXIT_ON_CLOSE parameter.

Question

Which method allows thread-safe GUI updates?

Options:

  1. setDefaultCloseOperation
  2. setDefaultLookAndFeelDecorated
  3. invokeLater

Answer

The javax.swing.SwingUtilities.invokeLater method ensures thread safety.

Option 1 is incorrect. The setDefaultCloseOperation method determines what happens when a user closes the main application window.

Option 2 is incorrect. Calling the setDefaultLookAndFeelDecorated with a true value ensures that the application’s look and feel will determine how the windows are decorated.

Option 3 is correct. To ensure thread safety, you call the invokeLater method of the javax.swing.SwingUtilities class. Then you pass a Runnable object and create or update the GUI from within the run method.

Summary

Java graphical user interface (GUI) applications consist of user interface objects known as components. Containers control how components are arranged onscreen by dividing them into groups. Swing is a Java-based toolkit that contains a library of prewritten components, based on classes from the Abstract Windowing Toolkit (AWT).

Swing components descend from the JComponent class, which derives from the Container class. This class enables you to customize the display, check component state, specify event handling, paint components, and change the containment hierarchy.

You can add components to containers using the add method. You add components to a JFrame or JWindow using the getContentPane method. The setVisible method ensures that the container is visible onscreen.

You can customize the way that windows and frames are decorated using the setDefaultLookAndFeelDecorated method. The setDefaultCloseOperation determines what happens when users close windows. To build a basic Swing application, you import the necessary packages, ensure thread-safety, and create and customize a top-level container and components.

The code for a basic Swing application

// Import swing and awt classes
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BasicSwingApp implements ActionListener {
	private static String buttonClicks = "Button clicks: ";
	private int clicks = 0;
	JLabel label;

	// Provides an implementation of ActionListener.actionPerformed
	public void actionPerformed(ActionEvent e) {
		label.setText(buttonClicks + ++clicks);
	}

	private void createAndShowGUI() {
		// Fancy decorations
		JFrame.setDefaultLookAndFeelDecorated(true) ;

		//Create and set up the frame
		JFrame frame = new JFrame("A basic Swing application") ;
		//Close application when close button clicked
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;

		// A JPanel will hold the contents
		JPanel pane = new JPanel(new GridLayout(0, 1));

		// Create a button, add an event listener,
		// and add it to the JPanel
		JButton button = new JButton("JButton");
		button.addActionListener(this);
		pane.add(button);
		button.requestFocus();

		// Create and add a label
		label = new JLabel(buttonClicks + "0");
		pane.add(label);

		// Add the JPanel to the frame
		frame.getContentPane().add(pane, BorderLayout.CENTER) ;

		//Display the frame
		frame.setSize(300, 200);
		frame.setVisible(true);
	}

	public static void main(String[] args) {

		//Schedule a job for the event-dispatching thread:
		//creating and showing this application's GUI
		javax.swing.SwingUtilities.invokeLater(
			new Runnable() {
				public void run() {
					BasicSwingApp app = new BasicSwingApp () ;
					app.createAndShowGUI();
				}
			}
		);
	}
}

Posted in Uncategorized | Leave a Comment »

Difference between Coupling and Cohesion

Posted by SARAVANAN SIVAJI on May 21, 2009

Coupling and Cohesion: The Two Cornerstones of OO Programming

Object-oriented programming has two main objectives: to build highly cohesive classes and to maintain loose coupling between those classes. High-cohesion means well-structured classes and loose coupling means more flexible, extensible software. Applying object-oriented metrics to your design and code can help you determine whether you’ve achieved these goals.

What is Cohesion?

In OO methodology, classes contain certain data and exhibit certain behaviours. This concept may seem fairly obvious, but in practice, creating well-defined and cohesive classes can be tricky. Cohesive means that a certain class performs a set of closely related actions. A lack of cohesion, on the other hand, means that a class is performing several unrelated tasks. Though lack of cohesion may never have an impact on the overall functionality of a particular class—or of the application itself—the application software will eventually become unmanageable as more and more behaviours become scattered and end up in wrong places.

Thus, one of the main goals of OO design is to come up with classes that are highly cohesive. Luckily, there’s a metric to help youverify that you’ve designed a cohesive class.

The LCOM Metric: Lack of Cohesion in Methods

The Lack of Cohesion in Methods metric is available in the following three formats:

LCOM1: Take each pair of methods in the class and determine the set of fields they each access. If they have disjointed sets of field accesses, the count P increases by one. If they share at least one field access, Q increases by one. After considering each pair of methods:


RESULT = (P > Q) ? (P - Q) : 0

A low value indicates high coupling between methods. This also indicates potentially high reusability and good class design. Chidamber and Kemerer provided the definition of this metric in 1993.

LCOM2: This is an improved version of LCOM1. Say you define the following items in a class:


m: number of methods in a class
a: number of attributes in a class.
mA: number of methods that access the attribute a.
sum(mA): sum of all mA over all the attributes in the class.
LCOM2 = 1- sum(mA)/(m*a)

If the number of methods or variables in a class is zero (0), LCOM2 is undefined as displayed as zero (0).

LCOM3: This is another improvement on LCOM1 and LCOM2 and is proposed by Henderson-Sellers. It is defined as follows:


LCOM3 = (m - sum(mA)/a) / (m-1)
where m, a, mA, sum(mA) are as defined in LCOM2.

The following points should be noted about LCOM3:

  • The LCOM3 value varies between 0 and 2. LCOM3>1 indicates lack of cohesion and is considered a kind of alarm.
  • If there is only one method in a class, LCOM 3 is undefined and also if there are no attributes in a class LCOM3 is also undefined and displayed as zero (0).

Each of these different measures of LCOM has a unique way to calculate the value of LCOM.

  • An extreme lack of cohesion such as LCOM3>1 indicates that the particular class should be split into two or more classes.
  • If all the member attributes of a class are only accessed outside of the class and never accessed within the class, LCOM3 will show a high-value.
  • A slightly high value of LCOM means that you can improve the design by either splitting the classes or re-arranging certain methods within a set of classes.

A Concrete Example

Listing 1 defines an Order class to which you can apply the LCOM metrics. Figure 1 displays a high-level UML model of an imaginary Order Processing system.


Figure 1:
This shows a UML class diagram for an Order Processing Sytem.

Note: The example UML diagram and the source code below is just an example and present a very much rough code sample. Please do not try to reuse this class for any real project.

To apply the LCOM3 metric to the Order class, define the metric variables as follows:


m(number of methods in the class) = 4
a(number of attributes in the class)=5

m[prod] = number of methods accessing the attribute prod = 3

m[orderNumber] = number of methods accessing the attribute orderNumber= 2

m[totalAmount] = number of methods accessing the attribute totalAmount = 4

m[deliveryType] = number of methods accessing the attribute deliveryType = 2

m[underPromotion] =number of methods accessing the attribute underPromotion=3

Therefore:


LCOM3 = ( m - sum(mA)/a ) / (m - 1)

             = ( 4 - 14/5 ) / (4-1)

             = 0.73

Remember to also count the constructor as a method of the class in this calculation.

The LCOM analysis on the Order class revealed that it had a reasonably high level of non-cohesiveness. Although, it is not “alarming” (as values >1 would be alarming according to LCOM3), you would be wise to improve its design.

A little inspection of all the methods in the class will immediately reveal that the method checkIfProductExists() is not a good fit for this class. The Order class must encapsulate the behaviours that an Order will need to exhibit. Basically, assume that when an instance of Order is created, the product within it is a valid and existing product. The responsibility of assigning a valid product to the Order object is better placed as part of the OrderManager class.

After removing the checkIfProductExists() method from the Order class, recalculate the value of LCOM3:


m(number of methods in the class) = 3
a(number of attributes in the class)=5

Therefore:


LCOM3 = ( m - sum(mA)/a ) / (m - 1)

             = ( 3 - 13/5 ) / (3-1) ***Note: sum(mA) is now reduced by one.

             = .20

This class is now more cohesive, with an LCOM value of 0.20—compared to the previous value of 0.73. That simple change made a world of difference in peace of mind.

Measuring Coupling

Coupling is a word that’s usually used in a derogatory manner in design review meetings. Even so, it’s not possible to design a functional OO application without coupling. Whenever one object interacts with another object, that is a coupling. In reality, what you need to try to minimise is coupling factors. Strong coupling means that one object is strongly coupled with the implementation details of another object. Strong coupling is discouraged because it results in less flexible, less scalable application software. However, coupling can be used so that it enables objects to talk to each other while also preserving the scalability and flexibility.

Though this seems like a difficult task, OO metrics can help you to measure the right level of coupling.

  • Coupling Between Objects (CBO): CBO is defined as the number of non-inherited classes associated with the target class. It is counted as the number of types that are used in attributes, parameters, return types, throws clauses, etc. Primitive types and system types (e.g. java.lang.*) are not counted.
  • Data Abstraction Coupling (DAC): DAC is defined as the total number of referred types in attribute declarations. Primitive types, system types, and types inherited from the super classes are not counted.
  • Method Invocation Coupling (MIC): MIC is defined as the relative number of classes that receive messages from a particular class.
    
    MIC = nMIC / (N -1 )
    
    Where N = total number of classes defined within the project.
    nMIC = total number of classes that receive a message from the target class.
    

Demeter’s Law

Ian Hollaand first proposed the Law of Demeter. The class form of Demeter’s Law has two versions: a strict version and a minimization version. The strict form of the law states that every supplier class of a method must be a preferred supplier. The minimization form is more permissive than the first version and requires only minimizing the number of acquaintance classes of each method.

  • Definition 1 (Client): Method M is a client of method f attached to class C, if inside M message f is sent to an object of class C, or to C. If f is specialized in one or more subclasses, then M is only a client of f attached to the highest class in the hierarchy. Method M is a client of some method attached to C.In Listing 1, the constructor of the Order class is a client to the Product class because it calls the getPrice() method of the Product class.
  • Definition 2 (Supplier): If M is a client of class C then C is a supplier to M. In other words, a supplier class to a method is a class whose methods are called in the method. In Listing 1, the Product class is a supplier class to the client class Order.
  • Definition 3 (Acquaintance Class): A class C1 is an acquaintance class of method M attached to class C2, if C1 is a supplier to M and C1 is not one of the following:
    • The same as C2;
    • A class used in the declaration of an argument of M
    • A class used in the declaration of an instance variable of C2

    In Listing 1, Product is an acquaintance class of the Order class, because Product is declared as an instance variable of the Order class and also passed as an argument to the constructor.

  • Definition 4 (Preferred-supplier class): Class B is called a preferred-supplier to method M (attached to class C) if B is a supplier to M and one of the following conditions holds:
    • B is used in the declaration of an instance variable of C
    • B is used in the declaration of an argument of M, including C and its superclasses
    • B is a preferred acquaintance class of M.

In Figure 1, the OrderLine, Order class is a preferred supplier class to the OrderManager class as they are used as instance variables inside the OrderManager class.

A Concrete Example

In the imaginary Order Processing example, imagine you’ve got the following form of code in the OrderManager class.


Class OrderManager {

 Private Order order;

public void getOrderByCustomer() {

     int productPrice = order.prod.price

}

You can see that the Product class becomes a supplier to the OrderManager class. This is not allowed according to the strict form of Demeter law because Product is not a preferred supplier to the OrderManager class.

Try the following:


Class OrderManager {

  Private Order order;

public void getOrderByCustomer() {

     int productPrice = order.getProductPrice();
}

Note that the above code makes the assumption that OrderManager will deal with only one Order at one time and also that one Order can have only one Product.

In the modified code, the client OrderManager class does not need to know how the object model is between Order and Product. Also, you never used or initialised the Product class within the OrderManager class. Having to reference to the Product class indirectly to get the price is a violation of Demeter Law.

Figure 2 presents a corrected UML diagram with all the changes that have been made so far.
Figure 2:
The corrected UML diagram.

What It All Adds Up To

All these coupling metrics really serve the same function: to reduce dependencies between several classes. The less dependency, the better the chance of a more flexible solution. But in OO programming, coupling is unavoidable. Therefore, the goal is to reduce unnecessary dependencies and make necessary dependencies coherent. In this article’s example, the OrderManager class is still coupled to the OrderLine and Order classes, but its unnecessary coupling with the Product class has been eliminated.

Make no mistake, these metrics are vital to measuring the quality of an application.

SUMMARY

Cohesion means that the whole of a class sticks together (well, roughly). A class should be responsible for itself, should do one thing and as far as possible do everything for that one thing. A Car class should remember its make, colour, speed. It is responsible for changing speed; the speedUp() and slowDown() methods should be in the Car class; no other class should make your Car go faster or slower.

Cohesion is (to quote Sellars and Yeatman) A Good Thing.

Coupling means that one class gets at the implementation of another class.

  1. Driver campbell = new Driver();
  2. Car ford = new Car(“Ford”, “red”);
  3. . . .
  4. public class Driver
  5. {
  6. Car myCar;
  7. . . .
  8. public void goFaster(int speed)
  9. {
  10. myCar.speed += speed;
  11. }
  12. . . .
  13. }

Driver campbell = new Driver(); Car ford = new Car(“Ford”, “red”); . . . public class Driver { Car myCar; . . . public void goFaster(int speed) { myCar.speed += speed; } . . . }The Car class has allowed access to its speed field and the Driver class changes its value directly. This means other classes gain access to the implementation of the Car class; any changes to that implementation will “break” the Driver class. This is “tight coupling” and tight coupling is A Bad Thing, because any changes to one class can mean that other classes would have to be altered too.
To avoid tight coupling

  • All classes should have as small a public interface as possible.
  • All non-constant fields should have private access.
  • Any alterations to the values of fields should be via method calls.
  • Posted in Uncategorized | Leave a Comment »

    Basic Networking FAQ

    Posted by SARAVANAN SIVAJI on May 10, 2009

    Posted in Uncategorized | Leave a Comment »

    Some SCJP Questions

    Posted by SARAVANAN SIVAJI on April 30, 2009

    1.  Can an abstract method be overridden?

    Answer:   Yes.  Because an abstract method has no choice.  It must be overridden.

    2. TRUE or FALSE – during arithmetic, when the operands are of different types, the resulting type is ALWAYS the widest of the two types.

    Answer:  FALSE.  The result of an arithmetic operation on any two primitive integer operands will be at least an int — even if the operands are byte and short.

    3. Which of these operators would cause the bit pattern 00111100 to become 11000011?    – (or) ~ (0r) !

    Answer: The ~ operator performs a bitwise inversion (flips the bits)

    4. Given x=y–;   Which of these will be true AFTER execution?

    a. x > y   b. x == y    c. x < y.

    Answer:  a (x > y).  Because y is assigned to x and then y is decremented.

    5.  Can you automatically/implicitly covert a char to a short?

    Answer:  No.  They’re the same bit-depth, bust since chars are unsigned, they might have a higher positive value than a short can accept.

    6.  TRUE or FALSE:   If an exception is not caught, the finally block will run and the rest of the method is skipped.

    Answer: TRUE.   The finally block will always run if an exception is thrown, and then the exception is immediately passed to the calling method.

    7.  What happens when you bit shift by a number greater than or equal to the number of bits in the result?  (Eg: int c=270, c>>33)

    Answer: you get 270>>1.   Shift bits by a number greater than or equal to the number of bits in the result (eg: 32 bits for an int) will cause the value to be shifted by the number modulo the number of bits in the value (you shift by 33%32 which is 1).

    8.  What happens when you have this in your code: double x; x=24.0/0;

    Answer: Compiles and runs.  Floating point numbers don’t produce a divide-by-zero Arithmetic Exception.  They will give a result which is a Not a Number value.

    9.  Does a final variable have to be initialized at the time it’s declared?

    Answer: No.  Although early versions of the JDK enforced this, current version let you initialize a final variable in the constructor, but no later.

    10.  Can you automatically convert a long to an int if the long value is small enough to fit into an int?

    Answer: No.  A long has 64 bits while an int has 32.  You can’t implicitly squish a *potentially* big thing into a little thing.  The compiler doesn’t care if the long variable is holding a  tiny value.  It just looks for the possibility of trouble.

    Posted in com.saravananmtech.java | Leave a Comment »

    Code: Filtering in Servlet

    Posted by SARAVANAN SIVAJI on April 24, 2009

    AccessLogFilter.java

    package filters;
    
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    
    /**
    * A basic filter that updates the log file
    * whenever an associated servlet or JSP is accessed.
    */
    
    public class AccessLogFilter implements Filter {
    
    	private FilterConfig config;
    
    	public void init(FilterConfig config)
    				throws ServletException {
    		this.config = config;
    	}
    
    	public void doFilter(ServletRequest request,
    		ServletResponse response,
    		FilterChain chain)
    			throws ServletException, IOException {
    
    		String filterName = config.getFilterName();
    		HttpServletRequest req = (HttpServletRequest)request;
    		ServletContext context = config.getServletContext();
    
    		context.log(new Date() + ": " + "Access to: " +
    				req.getRequestURL() +
    				" requested by: " +
    				req.getRemoteHost() +
    		". (Reported by " + filterName + ".)");
    
    		chain.doFilter(request,response);
    	}
    
    	public void destroy() {
    		this.config = null;
    	}
    }

    Posted in Uncategorized | Leave a Comment »

    RequestDispatcher Code in Servlet

    Posted by SARAVANAN SIVAJI on April 24, 2009

    <!–

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    /**
    * Front-controller servlet for an online travel agency.
    * Directs booking requests to the appropriate JSP.
    */
    
    public class TravelInfo extends HttpServlet {
    
    	public void init() {
    	}
    
    	public void doPost(HttpServletRequest request,
    		HttpServletResponse response)
    	throws ServletException, IOException {
    
    	String userName = request.getParameter("userName");
    	String password = request.getParameter("password");
    
    	HttpSession session = request.getSession(true);
    	session.setAttribute("userName", userName);
    
    	if (request.getParameter("flights") != null) {
    		gotoPage("/travel-info/Flights.jsp",
    			request, response);
    	} else if (request.getParameter("cars") != null) {
    		gotoPage("/travel-info/Cars.jsp",
    			request, response);
    	} else if (request.getParameter("hotels") != null) {
    		gotoPage("/travel-info/Hotels.jsp",
    			request, response);
    	} else if (request.getParameter("account") != null) {
    		gotoPage("/travel-info/UserInfo.jsp",
    			request, response);
    	} else {
    		gotoPage("/travel-info/Error.jsp",
    			request, response);
    	}
    	}
    
    	private void gotoPage(String address,
    		HttpServletRequest request,
    		HttpServletResponse response)
    	throws ServletException, IOException {
    	RequestDispatcher dispatcher =
    	getServletContext().getRequestDispatcher(address);
    	dispatcher.forward(request, response);
    	}
    }

    Posted in com.saravananmtech.java | Leave a Comment »