Saturday, February 10, 2007

How do I execute other applications?

Sometimes a pure java implementation doesn't quite cut it. If you need to run other applications from within your app (you won't be able to do this from an applet), then here's what you need to do.

Step One
Obtain a java.lang.Runtime instance. The java.lang.Runtime class allows you to execute other applications, but you'll need an object reference before you can begin.

// Get runtime instance
Runtime r = Runtime.getRuntime();
Step Two
Next, you'll make a call to execute your application. The exec call returns a Process object, which gives you some control over the new process. If you just need to start something running, then you might want to discard the returned process.

// Exec my program
Process p = r.exec ("c:\\myprog\\inc");
Step Three
Now, if you want to do something with your process (perhaps kill it after a certain time period, or wait until its finished), you can use the methods of the java.lang.Process class. Check the Java API documentation for more information - there's plenty of things you can do. Suppose you wanted to wait until its terminated, and then continue with your app. Here's how you'd do it.

// Wait till its finished
p.waitFor();


SOURCE : www.referjava.com

How do I playback multimedia files? I'd like to display .avi, .mpg, and other movie formats.

It'd be a tough task to write routines to playback a wide range of multimedia formats. Then you'd have to keep an eye out for new formats, write new code, and make it all so efficient that it can do real-time playback under a Java Virtual Machine. Fortunately, you don't have to do any of this!

Sun has been working on the Java Media Framework API, which offers an easy API to playback multimedia files. The API has been available for some time now, and implementations are now available from Sun, Intel, and others.


SOURCE : www.referjava.com

How do I create a .JAR file?

Java Archive (JAR) files allow developers to package many classes into a single file. JAR files also use compression, so this can make applets and applications smaller.

Creating a .JAR file is easy. Simple go to the directory your classes are stored in and type :-

jar -cf myfile.jar *.class
If your application or applet uses packages, then you'll need to do things a little differently. Suppose your classes were in the package mycode.games.CoolGame - you'd change to the directory above mycode and type the following :- (Remember to use / on UNIX systems)

jar -cf myfile.jar .\mycode\games\CoolGame\*.class
Now, if you have an existing JAR file, and want to extract it, you'd type the following

jar -xf myfile.jar


SOURCE : www.referjava.com

What causes out of memory exceptions?

The dreaded OutOfMemoryException is something that no Java programmer ever wishes to see. Yet it can happen, particularly if your application involves a large amount of data processing, or is long lived - such as a server that responds to requests and is expected to run indefinitely.

There are several reasons that out of memory exceptions can be thrown. Either the virtual machine your Java program is running on may have a limit to the amount of memory it will give access to, the system on which your program is running may have run out of physical and virtual memory, or your application may just be consuming too much memory. In the first case, you may be able to modify the maximum heap size of the virtual machine, in the second or third you'll need to redesign your application.

Designing applications for minimal memory consumption isn't an easy task, and isn't specific only to Java programming. There are many techniques available, such as buffering data to disk that isn't needed at the moment, to using more efficient algorithms or subdividing tasks into smaller pieces. This is more of a design problem that a Java one - however there are some steps you can take to avoid your program crashing when it runs out of memory.

For a start, in your main method (or those you identify as likely to cause problems), catch OutOfMemoryExceptions. This way your application can terminate gracefully. Also, be sure to clear any data that you know you'll no longer require. The automatic garbage collector looks for objects that contain no references, so be sure to set your objects to null when you're finished. Finally, you can always examine the amount of free memory by calling the freeMemory() method of the system Runtime object. Here's how :

Runtime runtime = Runtime.getRuntime();
System.out.println ("Free memory : " - + runtime.freeMemory() );
If you realize that you're going to be performing large amounts of data processing (and consuming large amounts of memory), it might be a good idea to check before beginning. Here's to no more OutOfMemoryExceptions!


SOURCE : www.referjava.com

How do I convert from a string into a number?

The first thing you have to be sure of is that your string actually contains a number! If not, then you'll generate a NumberFormatException. We can use the Integer class for converting from a string into an integer (or if we're dealing with decimal numbers, we can use the Double class).

The follow example shows how to convert from a string to an integer.

String numberOne = "123";
String numberTwo = "456";

// Convert numberOne and numberTwo to an int with Integer class
Integer myint1 = Integer.valueOf(numberOne);
Integer myint2 = Integer.valueOf(numberTwo);
// Add two numbers together
int number = myint1.intValue() + myint2.intValue();
You'll notice that when we need to use numbers as a data type (int), we need to convert from an Integer to an int. Confused? An Integer acts as a wrapper for our int data type (making conversion from String to number easy). When we want to use the data type, we call the intValue() method, which returns an int.


SOURCE : www.referjava.com

How do I convert from an int to a char?

If you aren't interested in converting from an int to a string (from int 127 to string "127"), and only want to convert to an ASCII value, then you only need to cast from an int to a char.

What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.

public class int_to_char
{
public static void main(String args[])
{
int a = 65;
char myChar = (char) a; // cast from int to char

System.out.println ("Char - " + myChar);
}
}
In this example, we have a number (65), which represents ASCII character A. We cast the number from an integer to a char, converting it to the letter A.


SOURCE : www.referjava.com

How do I create a scrollable container?

The good news is there is already a scrollable container as part of the java.awt package. It's called ScrollPane, and without this, you'd need to create one from scratch, using scrollbars. Phew!

Its easy to create an instance of ScrollPane, and to then add it to your applet or application. Simply create a new instance of ScrollPane, and then add it to your applet's canvas. Whatever size your applet is, the scroll pane will adjust to. Now as you add components, scroll bars will appear as needed. You can also change the size of the scrollbar via the setSize() method. Here's a quick example

// Create a scroll pane object
ScrollPane myContainer = new ScrollPane();
// Add scroll pane to my current canvas (if I am an applet)
add(myContainer);

// Now I can add components to my container......


SOURCE : www.referjava.com

What does the ++ or -- signs after a variable mean?

These operators date back to the days of C programming. These operators increment or decrement a variable by one. They're quite handy for using in expressions, because they will increment or decrement the variable after the expression has been tested.

A common example of their use is in for loops. Consider the following loop, which counts from one to ten.

for (int i=1; i<=10; i++) {
System.out.println (i);
}
In this case, the variable is incremented by one each time, until the terminating condition of greater than ten has been reached. It could just have easily been a while loop, or other expression.


SOURCE : www.referjava.com

What's the difference between = & ==?

One of the most common programming mistakes that one can make is to confuse the equal sign (=) with a double equal signs (==). While experienced programmers can still make the same mistake, knowing the difference between the two is a good way to avoid it.

When we wish to assign a value to a variable or member, we use the equals sign (=). As an example, the following would assign the value of three to the variable a.

a = 1 + 2; // assignment operation
When we wish to make a comparison, such as in an if statement, we use the double equals sign (==). A simple example would be the following

if ( a == b ) then System.out.println ("Match found!");
Now consider what would have happened if we used an assignment operator instead. A would be assigned the value of B - destroying the current contents of A and giving us an incorrect comparison. Finding this type of error can be difficult, because the two operators look so similar. So why does Java use such confusing operators? Java draws its roots from C, which shares the same problem. Unfortunately, its something that all Java programmers must learn to live with.


SOURCE : www.referjava.com

How can I generate random numbers?

Generating random numbers is simple. Provided as part of the java.util package, the Random class makes it easy to generate numbers. Start by creating an instance of the Random class

// Create an instance of the random class
Random r = new Random();
Now, you must request a number from the generator. Supposing we wanted an integer number, we'd call the nextInt() method.

// Get an integer
int number = r.nextInt();
Often you'll want numbers to fall in a specific range (for example, from one to ten). We can use the modulus operator to limit the range of the numbers. This will give us the remainder of the number when divided by ten (giving us a range -9 to +9). To eliminate negative numbers, if the number is less than one we'll add ten to it. This gives us random numbers between one and ten!

// Accept only up to ten
int random_number = number % 10;
if (random_number < 1) random_number = random_number + 10;
Creating random numbers in an application or applet really isn't that difficult. Just remember to limit the range of your numbers, and to import the java.util.Random class.


SOURCE : www.referjava.com

What's the use of a StringBuffer? Why shouldn't I just use a String?

StringBuffer can improve the performance of your application or applet. Java has often been criticized for its slow execution - but often it can be sped up through efficient algorithms and application design. If your code uses strings that change in size, then converting to StringBuffers can be of benefit.

Consider the following example, where mystring grows in size :

String mystring = "";

for (int i = 0; i<=1000; i++)
{
mystring = mystring + 'Number ' + i + '\n';
}

System.out.print (mystring);
In every cycle of the loop, we are creating a brand new string object, and the Java Virtual Machine must allocate memory for each object. It must also deallocate the memory for previous mystring instances (through the garbage collector), or face a hefty memory penalty.

Now consider the next example :

StringBuffer mystringbuffer = new StringBuffer(5000);

for (int i = 0; i<=1000; i++)
{
mystringbuffer.append ( 'Number ' + i + '\n');
}
System.out.print (mystringbuffer);
Rather than creating one thousand strings, we create a single object (mystringbuffer), which can expand in length. We can also set a recommended starting size (in this case, 5000 bytes), which means that the buffer doesn't have to be continually requesting memory when a new string is appended to it.

While StringBuffer's won't improve efficiency in every situation, if your application uses strings that grow in length, it may be of benefit. Code can also be clearer with StringBuffers, because the append method saves you from having to use long assignment statements. StringBuffer has plenty of advantages - so consider using it in your next Java application/applet.


SOURCE : www.referjava.com

How can I create a modal dialog box?

Modal dialog boxes are extremely useful for display alert messages, and for capturing the user's attention. You can create a simple modal dialog box, and then it will remain visible and will maintain focus until it is hidden (usually when the user clicks on a button). Here's a simple example.

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

public class DialogExample {
private static Dialog d;

public static void main(String args[])
{
Frame window = new Frame();

// Create a modal dialog
d = new Dialog(window, "Alert", true);

// Use a flow layout
d.setLayout( new FlowLayout() );

// Create an OK button
Button ok = new Button ("OK");
ok.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
// Hide dialog
DialogExample.d.setVisible(false);
}
});

d.add( new Label ("Click OK to continue"));
d.add( ok );

// Show dialog
d.pack();
d.setVisible(true);
System.exit(0);
}
}

The most important part of the program is the line that initializes the dialog. Notice the parameters we pass to it. The first parameter is a parameter for a window, and the second the title for the dialog. The final parameter controls whether the dialog is modal or not (true modal, false non-modal).

d = new Dialog(window, "Alert", true);
Using dialogs is easy, and can communicate information to users effectively. For those wishing to use the example, remember that it requires JDK1.1 or higher.


SOURCE : www.referjava.com

What exactly are servlets?

Most programmers will be familiar with the concept of server-side programming. Content can be created at the client end, through JavaScript, Dynamic HTML, or applets - but it can also be created at the server end through CGI scripts, server side applications, and now servlets!

Servlets are pieces of Java code that work at the server end. Servlets have all the access to resources on the server that a CGI script do, and aren't normally limited by the restrictions on file and network access that Java applets have traditionally been held back by. Servlets also offer substantial performance advantages for developers and webmasters, because unlike CGI scripts, do not fork off additional processes each time a request is made from a browser.

Servlets may take a little while to approach the same amount of usage as CGI scripts, but they are growing in popularity. Aside from the obvious advantage of portability, the performance advantages are significant, and its likely that in the future the use of Java servlets will become widespread. Developers keen to adopt skills should certainly focus on this new trend in server side programming, as the number of developers with servlet experience is (currently), small.

Here is a sample servlet, to illustrate just how easy it is to write server-side code in Java. For this example, I've written a servlet that outputs the obligatory 'Hello World!' message.

import java.io.*;

// Import servlet packages (requires JDK1.2 or servlet toolkit)
import javax.servlet.*;
import javax.servlet.http.*;


public class MyFirstServlet extends HttpServlet
{
// We override the doGet method, from HttpServlet, to
// provide a custom GET method handler
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/plain");
ServletOutputStream out = res.getOutputStream();

out.println ("Hello World!");
out.flush();
}

public String getServletInfo() {
return "MyFirstServlet";
}
}


SOURCE : www.referjava.com

How do I use the Vector class, from the java.util package?

Using the Vector class, rather than creating your own linked-list structure is a good idea. Vectors are extremely easy to use, and implement the Enumeration interface which makes traversing the contents of a Vector extremely easy.

Creating a vector is easy. Simply define a variable of type Vector, and call the vector constructor.

// Create an instance of class Vector ....
Vector myVector = new Vector ();

// ... or suggest an initial vector size
myVector = new Vector(50);
Vector instances, like linked-lists, can grow dynamically. Once the vector reaches its maximum limit, it dynamically allocated resources and increases its maximum. However, if you know you're going to insert a large amount of data, you may want to specify an initial estimate.

Vector instances can store any type of object - you simply insert an object via the addElement method.

for (int i = 1; i <= 20; i++)
{
myVector.addElement( new String ("I am string " + i));
}
When you wish to access the elements of the vector, you can look at individual elements (via their offset within the vector which is in ascending order), or you can traverse the entire list.

// Peek at element 5
System.out.println ("Element : " + myVector.elementAt(5) );
Traversing the entire vector is a common opperation. Remember, however, that when you insert an object via the addElement, it is implicitly cast to an instance of Object. Object is the base class of all other Java classes, and you'll need to explicitly cast it to another object type.

// Traverse entire list, printing them all out
for (Enumeration e = myVector.elements(); e.hasMoreElements();)
{
String myString = (String) e.nextElement();
System.out.println(myString);
}
Traversing a list is made extremely simple through the use of the Enumeration interface. Enumerations are great, because they allow you to easily process all elements, without having to determine the length of the vector, and manually accessing each element. Instead, it returns all the elements through the nextElement method.

Vectors provide an easy interface, and have the advantage that they can grow dynamically, whereas arrays are of fixed length. Consider using them in your next Java project!


SOURCE : www.referjava.com

How can I find out the current screen resolution?

The current screen resolution is a useful piece of information to know - particularly if you want to place a frame window in the very center of the screen. The screen dimensions can be found through the aid of the getScreenSize() method of the default screen toolkit.

import java.awt.*;
public class GetScreenSize()
{
public static void main(String args[])
{
// Get the default toolkit
Toolkit toolkit = Toolkit.getDefaultToolkit();

// Get the current screen size
Dimension scrnsize = toolkit.getScreenSize();

// Print the screen size
System.out.println ("Screen size : " + scrnsize);

// Exit gracefully
System.exit(0);
}
}


SOURCE : www.referjava.com

How can I find out who is connected to my server?

If you write applications that supply TCP services via the StreamSocket class, its extremely easy to determine the IP address and port of the remote connection. The accept method returns a Socket (which is used to communicate with the remote client). The Socket class has a getInetAddress(), and a getPort() method - all instances of socket can provide you with a unique identifier at a given point in time.

As far as finding out exactly who (as opposed to what machine) is connected to your server, you might want to have some form of authentication phase so that as a client connects, you can uniquely identify the user. If you create a lookup table, at a later stage you can lookup the IP address and port to determine the user.


SOURCE : www.referjava.com

How can I tell the type of machine and OS my Java program is running on?

A set of system properties, accessible via the getSystemProperties() method of class System allows you to get all sorts of useful information.

class GetPropertyDemo
{
public static void main(String args[])
{
// Display value for machine type and OS
System.out.println ( System.getProperty("os.arch") +
" running " +
System.getProperty("os.name") );
}
}


SOURCE : www.referjava.com

I've heard that Java has automatic garbage collection. How does it know when I'm finished with data, and to free some memory space?

A low priority thread takes care of garbage collection automatically for the user. During idle time, the thread may be called upon, and it can begin to free memory previously allocated to an object in Java. But don't worry - it won't delete your objects on you!

When there are no references to an object, it becomes fair game for the garbage collector. Rather than calling some routine (like free in C++), you simply assign all references to the object to null, or assign a new class to the reference.

Example :

pubic static void main(String args[])
{
// Instantiate a large memory using class
MyLargeMemoryUsingClass myClass = new MyLargeMemoryUsingClass(8192);

// Do some work
for ( .............. )
{
// Do some processing on myClass
}

// Clear reference to myClass
myClass = null;

// Continue processing, safe in the knowledge
// that the garbage collector will reclaim myClass
}
If your code is about to request a large amount of memory, you may want to request the garbage collector begin reclaiming space, rather than allowing it to do so as a low-priority thread. To do this, add the following to your code

System.gc();
The garbage collector will attempt to reclaim free space, and your application can continue executing, with as much memory reclaimed as possible (memory fragmentation issues may apply on certain platforms).


SOURCE : www.referjava.com

How can I write primitive data-types to disk? In C/C++, the printf statement could write integers, floats, as well as other types.

Writing primitive data-types can be easily done, using the DataOutputStream class. DataOutputStream provides simple methods to write primitive data-types out to any output stream, whether it be the user console, a network connection, or a file.
Java also provides a corresponding DataInputStream, which will allow you to read data back. This means you can write a data structure out to a disk or network connection, and read it back at a later date.


SOURCE : www.referjava.com

What does the keyword 'static' mean?

The static keyword denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs.

In simple terms, it means that you can call a method, even if you've never created the object to which it belongs! Every time you run a stand-alone application (which requires a static main method), the virtual machine can call the main method without creating a new application object. Of course, unless the application's methods are all static, you will need to create an instance of it at some point.

With regard to member variables, it means that they can be read from, and written to, without creating an object. You may have noticed that many classes create constants that can be read, without creating an object.

static final int VERSION = 2;

Static member variables are shared by all instances of the class to which they belong. When writing classes, this can be a handy feature. Consider the following example, where a counter is used to track how many myObject instantiations have taken place.

public class myObject
{
static int objectCount = 0;

public myObject()
{
objectCount++;
}

public String toString()
{
return new String ("There are " + objectCount + " objects");
}
}
As each new myObject is created, the counter increments. If you were writing an Internet server application, you could track how many concurrent connections existed (remembering that you'd have to include in the destructor or at the end of the connection code a decrement to your count). When used correctly, static member variables and methods can be quite useful!


SOURCE : www.referjava.com

What is the difference between an applet and an application?

In simple terms, an applet runs under the control of a browser, whereas an application runs stand-alone, with the support of a virtual machine. As such, an applet is subjected to more stringent security restrictions in terms of file and network access, whereas an application can have free reign over these resources.

Applets are great for creating dynamic and interactive web applications, but the true power of Java lies in writing full blown applications. With the limitation of disk and network access, it would be difficult to write commercial applications (though through the user of server based file systems, not impossible). However, a Java application has full network and local file system access, and its potential is limited only by the creativity of its developers.


SOURCE : www.referjava.com

When I compile a Java application using the new JDK1.1 compiler from Sun, it says that it uses "a deprecated API". What does this mean?

Applications written for JDK1.0 used the existing Java API, but with JDK1.1 onwards, some methods have been marked as deprecated. The API has been restructured and modified, with new classes and methods that provide similar functionality. Whenever possible, you should modify your application to remove references to deprecated methods/classes, and use the new alternatives offered as part of the Java API.

For more details on exactly which parts of your code is using a deprecated API, use the '-deprecation' parameter with the javac compiler


SOURCE : www.referjava.com

How can I provide a directory listing, and allow the user to navigate directories and select a file?

The task of writing a platform independent file selection dialog would be extremely difficult, as you'd need to support Unix, Macintosh, and Windows platforms, as well as any future Java platforms. You'd also be re-inventing the wheel, as Java has its own FileDialog as part of the AWT package. Its simple to use, and provides you with an interface that looks good on any platform!

All you need to do is create a frame, create a file dialog that takes as a parameter the newly created frame, and call the dialog's show method. The dialog is modal, meaning that the application will wait for the user to select a file, or click cancel.The task of selecting files is made really simple, and you can create an open or a save dialog box by changing the parameters you give the dialog constructor.

A sample application that shows the use of the FileDialog class is given below.

import java.awt.*;

class DialogDemo
{
public static void main(String args[])
{
// Create a new frame
Frame f = new Frame();

// Create a file dialog
FileDialog fdialog = new FileDialog
( f , "Open file", FileDialog.LOAD);

// Show frame
fdialog.show();

// Print selection
System.out.println ("Selection : " + fdialog.getDirectory() + fdialog.getFile());

// Clean up and exit
fdialog.dispose();
f.dispose();

System.exit(0);
}

}


SOURCE : www.referjava.com

What is Pure Java? I've heard that its 100%, so if I only use Java code and no external applications, is my code 'pure'?

100% Pure Java code is code that conforms to the Java ideal of universal portability. Writing an application that doesn't exploit operating system/platform specific features is a great start, but you also have to write the code in a platform neutral way. This includes things such as not hardwiring the '/' symbol as a file separator on Unix systems, as this will fail on a Wintel system that use '\'. If you don't rely on the core Java API's, and instead use native methods, this can also disqualify an application from being 100%.


SOURCE : www.referjava.com

How can I create my own GUI components?

Custom graphical components can be created by producing a class that inherits from java.awt.Canvas. Your component should override the paint method, just like an applet does, to provide the graphical features of the component.


SOURCE : www.referjava.com

How can I read from, and write to, files in Java?

Stand-alone applications written in Java can access the local file-system, but applets executing under the control of a browser cannot. With this in mind, lets take a look at two simple applications that write a line of text to a file, and read it back.

import java.io.*;

public class MyFirstFileWritingApp
{
// Main method
public static void main (String args[])
{
// Stream to write file
FileOutputStream fout;

try
{
// Open an output stream
fout = new FileOutputStream ("myfile.txt");

// Print a line of text
new PrintStream(fout).println ("hello world!");

// Close our output stream
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
}
This simple application creates a FileOutputStream, and writes a line of text to the file. You'll notice that the file writing code is enclosed within a try { .... } catch block. If you're unfamiliar with exception handling in Java, this requires a little explanation.

Certain methods in Java have the potential to throw an error condition, known as an exception. We have to trap these error conditions, so we 'catch' any exceptions that may be thrown.

The task of reading from a file is also just as easy. We create a FileInputStream object, read the text, and display it to the user.

import java.io.*;

public class MyFirstFileReadingApp
{
// Main method
public static void main (String args[])
{
// Stream to read file
FileInputStream fin;

try
{
// Open an input stream
fin = new FileInputStream ("myfile.txt");

// Read a line of text
System.out.println( new DataInputStream(fin).readLine() );

// Close our input stream
fin.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to read from file");
System.exit(-1);
}
}
}


SOURCE : www.referjava.com

How can I load a particular HTML page from within an applet?

Applets are executed within a web browser, and there's an easy way to load show a specific URL.

Obtain a reference to the applet context
Call the showDocument method, which takes as a parameter a URL object.
The following code snippet shows you how this can be done.

import java.net.*;
import java.awt.*;
import java.applet.*;

public class MyApplet extends Applet
{
// Your applet code goes here

// Show me a page
public void showPage ( String mypage )
{
URL myurl = null;

// Create a URL object
try
{
myurl = new URL ( mypage );
}
catch (MalformedURLException e)
{
// Invalid URL
}

// Show URL
if (myurl != null)
{
getAppletContext().showDocument (myurl);
}

}

}


SOURCE : www.referjava.com