Sunday, February 11, 2007

How can I use a quote " character within a string?

When we use literal strings in Java, we use the quote (") character to indicate the beginning and ending of a string. For example, to declare a string called myString, we could this :-

String myString = "this is a string";
But what if we wanted to include a quote (") character WITHIN the string. We can use the \ character to indicate that we want to include a special character, and that the next character should be treated differently. \" indicates a quote character, not the termination of a string.

public static void main (String args[])
{
System.out.println ("If you need to 'quote' in Java");
System.out.println ("you can use single \' or double \" quote");
}


www.referjava.com

How do I compare two strings?

A common error that we all make from time to time is incorrect String comparison. Even once you learn how to compare strings correctly, it's extremely easy to make a mistake and use the == operator.

When we compare primitive data types, such as two ints, two chars, two doubles, etc. we can use the == operator. We can also use the == operator to compare two objects. However, when used with an object, the == operator will only check to see if they are the same objects, not if they hold the same contents.

This means that code like the following will not correctly compare to strings :

if ( string1 == string2 )
{
System.out.println ("Match found");
}
This code will only evaluate to true if string1 and string2 are the same object, not if they hold the same contents. This is an important distinction to make. Checking, for example, to see if
aString == "somevalue", will not evaluate to true even if aString holds the same contents.

To correctly compare two strings, we must use the .equals method(). This method is inherited from java.lang.Object, and can be used to compare any two strings. Here's an example of how to correctly check a String's contents :

if ( string1.equals("abcdef") )
{
System.out.println ("Match found");
}
This is a simple, and easy to remember tip that will safe you considerable time debugging applications. Remember - never use the == operator if you only want to compare the string's contents.


www.referjava.com

How do I convert from a char to an int?

If you want to get the ASCII value of a character, or just convert it into an int (say for writing to an OutputStream), you need to cast from a char to an int.

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 char_to_int
{
public static void main(String args[])
{
char myChar = 'a';
int i = (int) myChar; // cast from a char to an int

System.out.println ("ASCII value - " + i);
}
}
In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.


www.referjava.com

How do I connect a Reader to an InputStream?

This is a very common question - after all, there aren't any SocketReaders, or PipedReaders. You need something to bridge the gap between a Reader, and an InputStream. That's where InputStreamReader comes into play.

InputStreamReader is a reader that can be connected to any InputStream - even filtered input streams such as DataInputStream, or BufferedInputStream. Here's an example that shows InputStreamReader in action.

// Connect a BufferedReader, to an InputStreamReader which is connected to
// an InputStream called 'in'.
BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) );

You can do the same with an OutputStream to a Writer (see OutputStreamWriter for more information).


www.referjava.com

When should I use an InputStream, and when should I use a Reader?

This can be confusing, particularly if you're already familiar with InputStream, and keep getting deprecated API warning messages. Let me simplify it for you.

If you're reading data, such as bytes of information, you are best off to use InputStreams and DataInputStream in particular.
If you're reading in text, and want to be able to call a readLine() method, its best to use Readers, and BufferedReader in particular.
So what's the difference? Well, DataInputStream's readLine() method is deprecated, because of problems with this method. Readers offer an alternative - though placing a readLine() method in a BufferedReader still seems a little odd to me. Whether its buffered or not has little to do with the fact it can read lines of text - but its easy enough to live with.


www.referjava.com

My application/applet loads images, but they aren't drawn to the screen. What's going on?

I've encountered this problem a few times in my own applications. When you load an image (using java.awt.Toolkit.getImage), the function returns immediately, and the image is loaded asynchronously. This means that sometimes an image isn't ready to be drawn, because it hasn't yet loaded. Depending on when the image is loaded, and when it is drawn, the problem can be intermittent and hard to track down.

If your application or applet MUST display the image, you can have it wait until the image is fully loaded. An animation applet, for example, may not have any useful work to do until the image(s) are loaded. To wait for images, you need to use the java.awt.MediaTracker class.

MediaTracker allows you to register an image with the tracker, and have your application or applet wait until the image is ready. Note that this isn't limited just to applets loading images over a network - from my own experience an application it can happen loading a small (<100 bytes) image from a local filesystem.

To register an image, you assign it an image number, and call the addImage method. Then you can call the waitFor(int) or waitForAll() methods.

// Pass media tracker any component (such as a canvas or an applet)
MediaTracker tracker = new MediaTracker( this );

// Add images
tracker.addImage ( myImage1, 0);
tracker.addImage ( myImage1, 1);
// Wait for images
try {
tracker.waitForAll();
} catch (InterruptedException ie) {}
Once you start the wait, your application will block until the image has loaded. Then, you can call java.awt.Graphics.drawImage to display the image to your applet or application.


www.referjava.com

Why can't my applet read or write to files?

Applets execute under the control of a web browser. Netscape and Internet Explorer impose a security restriction, that prohibits access to the local filesystem by applets. While this may cause frustration for developers, this is an important security feature for the end-user. Without it, applets would be free to modify the contents of a user's hard-drive, or to read its contents and send this information back over a network.

Digitally signed applets can request permission to access the local filesystem, but the easiest way around the problem is to read and write to remote files located on a network drive. For example, in conjunction with a CGI script or servlet, you could send HTTP requests to store and retrieve data.


SOURCE : www.referjava.com

How can I convert my Java classes to an executable .EXE file for Windows?

This is a very common question asked in the comp.lang.java newsgroup. Its often useful to have an executable application when deploying your applications to a specific platform, but remember to make your .class files available for users running Unix/Macintosh/other platforms.

Microsoft used to provide a free system development kit (SDK), for Java, which includes the jexegen tool. This will convert class files into a .EXE form. The only disadvantage is that users need a Microsoft Java Virtual Machine (JVM) installed. Microsoft no longer supports this however, and you should transition to a new Win 32 Java system. See http://java.sun.com/ for the latest version of a Java interpreter for Winodws.


SOURCE : www.referjava.com

My version of JDK won't run classes, even when they're in the current directory. What should I set my classpath to?

Remember always to include the current directory in your classpath. For example, on Windows systems, you might need to try

jre -cp .\ MyJavaApplication , or

java -cp .\ MyJavaApplication


SOURCE : www.referjava.com

I'm confused about variables and their scope. What's the difference between a member variable, and a local variable?

Simple! A member variable is a variable that belongs to an object, whereas a local variable belongs to the current scope. Hmm... Still confused?

When we define a class, we can give that class member variables. These variables are members of that class. Take, for example, the following class declaration.

public class MyClass {
int a;
int b;
}

MyClass has two member variables, a & b. When we define an object instance of MyClass it will still have two member variables, a & b. We can reference these members using the '.' character.

// Create an instance of MyClass
MyClass obj = new MyClass();

// Assign new values to a & b
obj.a = 1;
obj.b = 65536;

These variables belong to MyClass, and are known as member variables. On the other hand, if we declare variables inside of a function, we call these local variables. These variables are local to a particular function, and not publicly accessible. For example, in the following function, we have no way of accessing the obj variable outside of the main(String[]) function.

public static void main (String args[])
{
MyClass obj = new MyClass();

System.out.println ("A" + obj.a);
}


SOURCE : www.referjava.com

How do I create a new instance of an object?

To create a new instance of an object, we use the "new" keyword. This keyword creates a new instance of an object, which we can then assign to a variable, or invoke methods. For example, to create a new StringBuffer object, we would use the new keyword in the following way.

StringBuffer myBuffer = new StringBuffer (50);

Notice how we can also assign parameters (in this case, we are allocating at least fifty characters for our buffer). If we don't wish to specify any parameters, we could use the new keyword this way.

StringBuffer myBuffer = new StringBuffer ();

The new keyword expects a class name, followed by the parameters that will be passed to a constructor. When we have no parameters, we simple use empty ()'s.


SOURCE : www.referjava.com

How do I detect if command line arguments are empty?

Whenever you write Java applications, its vital that you check your command line arguments before using them. Not all users will remember to put in the correct number of parameters, and your application will terminate with an ArrayIndexOutOfBoundsException. Fortunately, its extremely easy to check!

Here's an example program, that checks that at least one parameter exists :

public class argsdemo
{
public static void main(String args[])
{
if (args.length == 0)
{
System.err.println ("No arguments!");
System.exit(0);
}
}
}
Just add a if statement before using a parameter, and then perhaps exit with a message. You can check for a specific number of parameters, and terminate if they're missing.


SOURCE : www.referjava.com

How do I use stacks in Java?

A stack is a data structure that allows data to be inserted (a 'push' operation), and removed (a 'pop' operation). Many stacks also support a read ahead (a 'peek' operation), which reads data without removing it. A stack is a LIFO-queue, meaning that the last data to be inserted will be the first data to be removed.

When we insert data into a stack, it is placed at the head of a queue. This means that when we remove data, it will be in reverse order. Adding 1,2,3,4 will return 4,3,2,1. Stacks aren't the most frequently used data structure, but they are extremely useful for certain tasks.


SOURCE : www.referjava.com

How can I throw an exception without declaring it in a 'throws' clause?

Sometimes it is useful to throw exceptions, without explicitly declaring them in the throws clause of a method's signature. Any exceptions that extends java.lang.RuntimeException don't need to be declared. This means that it is safe to throw subclasses (like NullPointException), or to create your own.

SOURCE : www.referjava.com

Is there any way to access C++ objects, and use their methods?

Yes! The Common Object Request Broker Architecture (CORBA), allows developers to create interfaces to their objects that work with any other CORBA compatible language. This means that a C++ object can have its methods invoked from Java, and vice verca.


SOURCE : www.referjava.com

How do I use hashtables?

Hashtables are an extremely useful mechanism for storing data. Hashtables work by mapping a key to a value, which is stored in an in-memory data structure. Rather than searching through all elements of the hashtable for a matching key, a hashing function analyses a key, and returns an index number. This index matches a stored value, and the data is then accessed. This is an extremely efficient data structure, and one all programmers should remember.

Hashtables are supported by Java, in the form of the java.util.Hashtable class. Hashtables accept as keys and values any Java object. You can use a String, for example, as a key, or perhaps a number such as an Integer. However, you can't use a primitive data type, so you'll need to instead use Char, Integer, Long, etc.

// Use an Integer as a wrapper for an int
Integer integer = new Integer ( i );
hash.put( integer, data);
Data is placed into a hashtable through the put method, and can be accessed using the get method. It's important to know the key that maps to a value, otherwise its difficult to get the data back. If you want to process all the elements in a hashtable, you can always ask for an Enumeration of the hashtable's keys. The get method returns an object, which can then be cast back to the original object type.

// Get all values with an enumeration of the keys
for (Enumeration e = hash.keys(); e.hasMoreElements();)
{
String str = (String) hash.get( e.nextElement() );
System.out.println (str);
}
To demonstrate hashtables, I've written a little demo that adds one hundred strings to a hashtable. Each string is indexed by an Integer, which wraps the int primitive data type. Individual elements can be returned, or the entire list can be displayed. Note that hashtables don't store keys sequentially, so there is no ordering to the list.

import java.util.*;

public class hash {
public static void main (String args[]) throws Exception {
// Start with ten, expand by ten when limit reached
Hashtable hash = new Hashtable(10,10);

for (int i = 0; i <= 100; i++)
{
Integer integer = new Integer ( i );
hash.put( integer, "Number : " + i);
}

// Get value out again
System.out.println (hash.get(new Integer(5)));

// Get value out again
System.out.println (hash.get(new Integer(21)));

System.in.read();

// Get all values
for (Enumeration e = hash.keys(); e.hasMoreElements();)
{
System.out.println (hash.get(e.nextElement()));
}
}
}


SOURCE : www.referjava.com

How do I make my frames close in response to user requests?

You need to define an event handler for the "WindowClosing" event. Under JDK1.02, you can add the following code to your Frame subclasses.

// Response to close events
public void WindowClosing(WindowEvent evt)
{
// Close application
System.exit(0);
}
If you're using JDK1.1 AWT event handlers, you can use the WindowAdapter class for a similar purpose. Here's a simple application that demonstrates the use of WindowAdapter, as an anonymous inner class.

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

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

// Add a new button
f.add ( new Button("demo") );

// Resize/pack
f.pack();

// Add a window listener
f.addWindowListener ( new WindowAdapter () {
public void windowClosing ( WindowEvent evt )
{
System.exit(0);
}
});

// Show window
f.setVisible(true);
}
}


SOURCE : www.referjava.com

How can I change the cursor shape?

Any graphical component is capable of changing the mouse cursor. As the user moves the cursor over the component, the cursor will change. Setting a new cusor type is easy - every subclass of java.awt.Component has a setCursor method. Individual components, or even applets can specify their own cursor.

// Create an instance of java.awt.Cursor
Cursor c = new Cursor ( Cursor.WAIT_CURSOR );

// Create a frame to demonstrate use of setCursor method
Frame f = new Frame("Cursor demo");
f.setSize(100,100);

// Set cursor for the frame component
f.setCursor (c);

// Show frame
f.show();
There isn't a "global" cursor type, so this means that you can have different cursors for different components. But just remember - using cursors inappropriately will make it difficult for users, so don't put an hourglass wait component unless you actually want the user to wait! A full list of cursor types is available from the documentation for java.awt.Cursor.


SOURCE : www.referjava.com

How do I use really large numbers in Java?

There are many classes of applications that require support for large numbers. When primitive data types like long, and double just won't cut it, Java offers an answer in the form of the java.math package.

Whether its whole numbers or decimals you need, java.math has the solution. For whole numbers, use the BigInteger class, and for fractions use the BigDecimal class. Each allows a wide range of mathematical operations, from simple things like addition, subtraction, multiplication and division to more complex operations like logical AND, OR, NOT and powers.


SOURCE : www.referjava.com