Wednesday, April 30, 2008

Use globally defined constants

You can use globally defined constants by defining them inside a class and referencing themwithout instantiation.

public class CONSTANT {

public static final integer SUCCESS = 1;
public static final integer FAILURE = -1;
public static final integer NOTFOUND = 0;

}

Since the members of the class are defined as "static", there is no need to instantiate the class. To use a constant, simply use CONSTANT.[constant name]

if (myMethod()==CONSTANT.SUCCESS) {
...;
}
else {
...;
}

For details: Java Tips

Set the memory available to the JVM

By default, the JVM will use up to 16Mb of RAM. If your program allocates a lot of memory, you may need to increase this value to give more room to the garbage collector.

When starting the JVM, two parameters can be adjusted to suit your memory needs:

-mx n Sets the maximum size of the memory allocation pool where n is in bytes, appending "m" to n will specified the number in megabytes, for example to set the maximum at 20Mb:

   java -mx 20m myApp

. -ms n Sets the startup size of the memory allocation pool, where n is in bytes, appending "m" to n will specified the number in megabytes. The default is 1Mb.

With JDK1.2, that syntax have changed, no space between ms/mx and the value:

   java -mx20m myApp

For Details: Java Tips

Pass an integer by reference

Sometimes you may need to pass an integer to be able to change its value. "integer" are always passed by value in Java. An easy way to pass by reference is to use a single element array.

int[] a = new int[1];
a[0] = 1;
add2(a);
// a[0] now = 3
...

void add2(int[] a) {
a[0] = a[0] + 2;
}


For details: Java Tips

Make a JAR executable

In the manifest file of a JAR, it is possible to specify the class to be used when the JVM is lauched with the JAR as parameter. The class must have a main().

Try with this simple class:

import java.awt.*;
import java.awt.event.*;

public class MyClass {
public static void main(String[] args) {
Frame f = new Frame();
f.addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
f.add(new Label("Hello world"));
f.setSize(200,200);
f.setVisible(true);
}
}

Then create this manifest file (manifest.mft) with any text editor.

   Manifest-Version: 1.0
Main-Class: MyClass
Classpath: .\MyJar.jar

Next, you include the manifest file in the JAR (MyJar.jar) with the MyClass class.

   jar cvfm MyJar.jar manifest.mft MyClass.class

Then you are able to start the MyClass.class by double-clicking on the MyJar.jar file (if the JRE is correctly installed) or by typing

   java -jar MyJar.jar

On NT, you can also make JARs run from the command-line by setting the PATHEXT environment variable, for example

   set PATHEXT=.EXE;.BAT;.CMD;.JAR

Then if you have the jar file MyJar.jar accessible via the PATH environment variable, typing "MyJar" on the DOS command line will invoke "java -jar MyJar.jar" .

For Details: Java Tips

Introduction to Autoboxing

This Tech Tip reprinted with permission by java.sun.com

Although the Java programming language is an object-oriented language, it's often the case that when using the language you need to work with primitive types. Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive types and the wrapper classes. In this tip, you will see how the new autoboxing feature in J2SE 5.0 handles conversions -- for example, between values of type int and values of type Integer. The tip also discusses some autoboxing-related considerations in determining when two numerical values are equal.

The October 5, 2004 Tech Tip, Formatting Output with the New Formatter discussed a new way to format output that is similar to that of the C language's printf. An example in that tip used the printf() method to print an integral value. Here is a simple example that uses the printf() method:

public class FormatPrint {
public static void main(String[] args) {
System.out.printf("There is only %d thing.", 1);
}
}

The signature of the printf() method in the FormatPrint example is:

   printf(String format, Object... args)

The number 1 is a primitive and not an object, so you might think that the line:

   System.out.printf("There is only %d thing.", 1);

should not compile. However autoboxing takes care of the situation by automatically wrapping the integer value in the appropriate wrapper object. In J2SE 1.4 you would have needed to manually wrap the primitive value using something like new Integer(1).

Another example of where automatically converting from a primitive might be useful is when you use the Collections APIs. The collections classes are designed to store objects. Consider the following simple example of storing int values from 0 to 9 in an ArrayList:

import java.util.ArrayList;

public class Autoboxing {
public static void main(String[] args) {
ArrayList list = new ArrayList();
for(int i = 0; i < 10; i++){
list.add(i);
}
}
}

The comparable program for J2SE 1.4.2 would be the following:

import java.util.ArrayList;

public class ManualBoxing {
public static void main(String[] args) {
ArrayList list = new ArrayList();
for(int i = 0; i < 10; i++){
list.add(new Integer(i));
}
}
}

With ManualBoxing you need to explicitly create the Integer object using list.add(new Integer(i)). Contrast that with Autoboxing, where the int i is autoboxed to an Integer object in the line list.add(i).

Autoboxing works well with other new J2SE 5.0 features. For example, the autoboxing feature allows seamless integration between generic types and primitive types. In the ManualBoxing example, the elements of the ArrayList are of type Object. By comparison, in the Autoboxing example, the elements of list are of type Integer.

Let's extend the Autoboxing example to iterate through the elements in the ArrayList and calculate their sum. Notice that this new version also uses the new J2SE 5.0 enhanced for loop to iterate through the elements.

import java.util.ArrayList;

public class Autoboxing {
public static void main(String[] args) {
ArrayList list = new ArrayList();
for(int i = 0; i < 10; i++){
list.add(i);
}
int sum = 0;
for ( Integer j : list){
sum += j;
}
System.out.printf("The sum is %d.", sum );
}
}

Autoboxing is used in a number of places in the updated Autoboxing example. First, ints are boxed to Integers as they are added to the ArrayList. Then Integers are unboxed to ints to be used in calculating the sum. Finally, the int representing the sum is boxed for use in the printf() statement.

The transparency of the boxing and unboxing makes autoboxing easy to use. However using the autoboxing feature requires some care. In particular, testing for the equality of objects created by autoboxing is not the same as testing for the equality of objects that are not created by autoboxing. To see this, look at the following BoxingEquality class:

import java.util.ArrayList;

public class BoxingEquality {
public static void main(String[] args) {
int i = 2;
int j = 2;
ArrayList list = new ArrayList();
list.add(i);
list.add(j);
System.out.printf("It is %b that i ==j.\n",
(i==j)); //(1)
System.out.printf("It is %b that " +
"list.get(0) == list.get(1).\n",
list.get(0)==list.get(1)); //(2)
System.out.printf("It is %b that " +
"list.get(0).equals(list.get(1)).",
list.get(0).equals(list.get(1))); //(3)
}
}

The first print statement in BoxingEquality compares the equality of the primitives i and j. The second print statement compares the equality of the objects created by autoboxing i and j. The third print statement compares the value of the objects created by autoboxing i and j. You would expect the first and the third print statements to return true, but what about the second? The output from running the BoxingEquality program is:

   It is true that i ==j.
It is true that list.get(0) == list.get(1).
It is true that list.get(0).equals(list.get(1)).

Now change the values of i and j to 2000.

import java.util.ArrayList;

public class BoxingEquality {
public static void main(String[] args) {
int i = 2000;
int j = 2000;
// . . .
}

Save, recompile, and rerun BoxingEquality. This time the results are different:

   It is true that i ==j.
It is false that list.get(0) == list.get(1).
It is true that list.get(0).equals(list.get(1)).

The primitives are equal and the values of the boxed ints are equal. But this time the ints point to different objects. What you have discovered is that for small integral values, the objects are cached in a pool much like Strings. When i and j are 2, a single object is referenced from two different locations. When i and j are 2000, two separate objects are referenced. Autoboxing is guaranteed to return the same object for integral values in the range [-128, 127], but an implementation may, at its discretion, cache values outside of that range. It would be bad style to rely on this caching in your code.

In fact, testing for object equality using == is, of course, not what you normally intend to do. This cautionary example is included in this tip because it is easy to lose track of whether you are dealing with objects or primitives when the compiler makes it so easy for you to move back and forth between them.

For more information on autoboxing, see Autoboxing.

Copyright (c) 2004-2005 Sun Microsystems, Inc.
All Rights Reserved.



For details: Java Tips

How to write a Java Application without a main method

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

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

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

}
}

Fore details: Java Tips

Array, List and Map Differences...

The measured times show that for random operations within a list, it's preferable to use the array or the ArrayList. There's no real difference in performance between the array and the ArrayList, so if you need the extra features of an ArrayList, then it's the obvious choice. You should only consider using LinkedList when your operations work on the ends of the list. Another option to consider might be the new Queue class-- when only the top element of a list is of interest.

When the index or key to the list is not an integer, HashMap is the only choice, and as you've seen, its performance is quite good.

For details: Java Boutique



How to use getenv() in Java SE 5.0

Since getenv() method is no more deprecated in Java SE 5.0, we can start using this to get the System Environment variables. This method has two forms:

  • getenv() -> returns the Map contains the System Environment. NULL is returned if there are no System Environment varibales.

    Ex: Map sysEnvMap = System.getenv();

  • String getenv(String key) -> returns the value of passed environment key. NULL is returned if the key does not exist.

    Ex: String sysEnvStr = System.getenv("JAVA_HOME");

for more details: Java Tips

How to use Jar Tool

You can package your classes in a jar file and that Jar file can be used in class path.

Following commands needs to be executed for various purposes in managing Jar files.

  1. jar cf jar-file inputfiles: It is used to create new JAR.
  2. jar tf jar-file: It is used to view all the files of the JAR.
  3. jar xf jar-file: It is used to extract the JAR.
  4. java -jar app.jar: It is used to run a JAR if the manifest file is present in the JAR. This manifest file contains the information of the file having main method. Content of the manifest is:
    Main-Class: classname
for more details: Java Tips

Tuesday, April 29, 2008

How to use generics

The 5.0 release of J2SE includes the first set of significant language-level changes to the Java platform in some time. In addition to new constructs for things such as the enhance for loop and variable argument lists, J2SE 5.0 provides compile-time type safety with the Java Collections framework through generics in accordance with JSR-14: Add Generic Types To The Java Programming Language.

One of the primary uses of generics is to abstract data types when working with collections. Prior to the JDK 5.0 release, when you created a Collection, you could put anything in it, for example:

List myList = new ArrayList(10);
myList.add(new Integer(10));
myList.add("Hello, World");

If you wanted to restrict your Collection to a specific type, it was difficult at best. Getting items out of the collection required you to use a casting operation:

Integer myInt = (Integer)myList.iterator().next();

If you accidently cast the wrong type, the program would successfully compile, but an exception would be thrown at runtime. Unless you dealt specifically with everything in the Collection as an Object, casting typically happened blindly -- or by doing an instanceof check before calling the casted operation.

Iterator listItor = myList.iterator();
Object myObject = listItor.next();
Integer myInt = null;
if (myObject instanceof Integer) {
myInt = (Integer)myObject;
}

That situation underscores the beauty of generics. Generics allows you to specify, at compile-time, the types of objects you want to store in a Collection. Then when you add and get items from the list, the list already knows what types of objects are supposed to be acted on. So you don't need to cast anything. The "<>" characters are used to designate what type is to be stored. If the wrong type of data is provided, a compile-time exception is thrown. For example, if you try to compile the following class:

import java.util.*;

public class First {
public static void main(String args[]) {
List myList = new ArrayList(10);
myList.add(10);
myList.add("Hello, World");
}
}

you get an error like this:

   First.java:7: cannot find symbol
symbol : method add(java.lang.String)
location: interface java.util.List
myList.add("Hello, World");
^
1 error


Here's the old way of looping through a List of String objects, that is, without generics and an enhanced for loop:

import java.util.*;

public class Old {
public static void main(String args[]) {
List list = Arrays.asList(args);
Iterator itor = list.iterator();
while (itor.hasNext()) {
String element = (String)itor.next();
System.out.println(element + " / " + element.length());
}
}
}

If you compile and run the Old class and then run it with a string, like this:

   java Old Hello

you get:

   Hello / 5

With JDK 5.0, you can combine the new enhanced for loop construct with generics to create a program that is type-safe at compile-time, and is more readable and more maintainable. Here's what looping through a List of String objects looks like if you use generics and an enhanced for loop:

import java.util.*;

public class New {
public static void main(String args[]) {
List list = Arrays.asList(args);
for (String element : list) {
System.out.println(element + " / " + element.length());
}
}
}
   java New Hello
Hello / 5

As demonstrated here, generics and the enhanced for loop work well together.

For more information on generics, see:

  1. Tutorial: Generics in the Java Programming Language (pdf)
  2. JSR-14: Add Generic Types To The Java Programming Language
  3. Generics

Copyright (c) 2004-2005 Sun Microsystems, Inc.
All Rights Reserved.



For more details: Java Tips

How to use For Each loop

JDK 5.0 provides a special kind of for loop for access through all the elements of it.

Syntax

For(vaiable : collection){ Statements; }

Example:

int[] a={1,2,3,4,5,6,7,8,9,0};
for(int i : a){
System.out.println(i);
}

For more details: Java Tips

How to pass unspecified number of arguments to a method

JDK 5.0 provides a feature to pass unspecified number of argument to a method. Java treats the variable-length argument list as an array. This is represented by argument type followed by three dots in the declaration of the Method.

The method int sum(int…numbers) can take any number of parameters of type integer.

public int sum(int...numbers) {

int sum=0;
for (int d : numbers )
sum =sum + d;
return sum;
}

public static void main(String[] args) {
int i=3;
int j=6;
int k=9;
System.out.println("Sum of two numbers"+sum(i,j));
System.out.println("Sum of three number"+sum(i,j,k));
}
}

For more details: Java Tips

How to launch a Unix script with Java

You can use folowing code snippet to launch a Unix script with Java.

String[] cmd = {"/bin/sh", "-c", "ls > hello"};
Runtime.getRuntime().exec(cmd);

For more details: Java Tips

How to get free available memory in Java program

This sample code will print the total and free memory at runtime to the console.

public class MemoryExp {

public static void main(String[] args) {

System.out.println("Total Memory"+Runtime.getRuntime().totalMemory());
System.out.println("Free Memory"+Runtime.getRuntime().freeMemory());

}
}

For more details: Java Tips

How to execute a command from code

This Java tip illustrates a method of executing a command from the code. This is very helpful in cases when developer wants to execute some file (for ex. an exe) or run some command in a command prompt but without the interruption of the user.

try {
// Execute a command without arguments
String command = "ls";
Process child = Runtime.getRuntime().exec(command);

// Execute a command with an argument
command = "ls /tmp";
child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
}

// In case developer wants to execute a command with more than
// one argument, it is necessary to use the overload that requires
// the command and its arguments to be supplied in an array:

try {
// Execute a command with an argument that contains a space
String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};

commands = new String[]{"grep", "hello world",
"c:\\Documents and Settings\\f.txt"};

Process child = Runtime.getRuntime().exec(commands);

} catch (IOException e) {
}

For more details: Java Tips

How to copy an array into another

If the array only contains primitive types or if you want to copy only the object references, not duplicate the objects, then you can use the following method

java.lang.System.arraycopy(Object src, int src_position,
Object dst, int dst_position, int length);

Otherwise, if you want to duplicate the objects, you have to initialize your new array and write a loop that duplicates each object in the old array into the new one.

For more details: Java Tips



How do I find the list of all system properties

You can use the following code snippet to obtain a list of all system properties:

Enumeration list = System.getProperties().propertyNames();

while(list.hasMoreElements()){
System.out.println((String) list.nextElement());
}

For more details: Java Tips

Create a Java source dynamically, compile and call

The following wxample shows how to create a Java source code dynamically and then compile and run it.

import java.io.*;
import java.util.*;
import java.lang.reflect.*;

public class MakeTodayClass {
Date today = new Date();
String todayMillis = Long.toString(today.getTime());
String todayClass = "z_" + todayMillis;
String todaySource = todayClass + ".java";

public static void main (String args[]){
MakeTodayClass mtc = new MakeTodayClass();
mtc.createIt();
if (mtc.compileIt()) {
System.out.println("Running " + mtc.todayClass + ":\n\n");
mtc.runIt();
}
else
System.out.println(mtc.todaySource + " is bad.");
}

public void createIt() {
try {
FileWriter aWriter = new FileWriter(todaySource, true);
aWriter.write("public class "+ todayClass + "{");
aWriter.write(" public void doit() {");
aWriter.write(" System.out.println(\""+todayMillis+"\");");
aWriter.write(" }}\n");
aWriter.flush();
aWriter.close();
}
catch(Exception e){
e.printStackTrace();
}
}

public boolean compileIt() {
String [] source = { new String(todaySource)};
ByteArrayOutputStream baos= new ByteArrayOutputStream();

new sun.tools.javac.Main(baos,source[0]).compile(source);
// if using JDK >= 1.3 then use
// public static int com.sun.tools.javac.Main.compile(source);
return (baos.toString().indexOf("error")==-1);
}

public void runIt() {
try {
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(todayClass);
Object iClass = thisClass.newInstance();
Method thisMethod = thisClass.getDeclaredMethod("doit", params);
thisMethod.invoke(iClass, paramsObj);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

For more details: Java Tips

Creating Application Specific Exceptions

When a program encounters an exceptional condition, it throws the exception like IOException, IllegalArgumentException etc.

Sometimes no standard class adequately represents the exceptional condition. In this condition programmer can choose to create his own exception class.

To create our own Exception existing type of exception are inherited, preferably one that is close in meaning to your new exception.

This code shows the use of user defined exception. In this code ApplicationException is user defined Exception.



public class
ApplicationException extends Exception {

private int intError;

ApplicationException(int intErrNo){
intError = intErrNo;
}

ApplicationException(String strMessage){
super(strMessage);
}

public String toString(){
return "ApplicationException["+intError+"]";
}
}

class ExceptionDemo{

static void compute(int a) throws ApplicationException{

System.out.println("called compute(" +a +" )");

if(a>10){
throw new ApplicationException(a);
}

System.out.println("NORMAL EXIT");
}

public static void main(String[] args) {

try{
compute(1);
compute(20);

}catch(ApplicationException e){
System.out.println("caught " + e);
}
}
}

For more details: Java Tips

How can I force garbage collection to take place

You can't force it but you call System.gc(), which is a "hint" to the

runtime engine that now might be a good time to run the GC. But garbage collection using this method is not guaranteed to be done immediately.

For more details: Java Tips



Tools to convert a program writen in C to Java

There are tools which provides opportunity to translate C-code sources into Java classes. Some of them are listed below:

  • Jazillian: Jazillian is a tool that translates from C source code to Java source code. The Java code that it produces is highly maintainable: it looks like hand-written code.
  • C to Java converter: Some time ago I needed to convert one C program to Java. It is tedious and not interesting job to do. So I developed C to Java converter. I can not say, that it is fully functional or have no bugs. But you may find it useful to use this tool first, before making changes by hand.
  • C2J converter: C2J converter provides opportunity to translate C-code sources into Java classes.
for more details: Java Tips

Difference between String, StringBuffer and StringBuilder

String is immutable whereas StringBuffer and StringBuilder can change their values.

The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among String, StringBuffer and StringBuilder

1. If your text is not going to change use a string Class because a String object is immutable.
2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

For details: Java Tips