Tuesday, February 27, 2007

Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following:
for(;;) ;


SOURCE : www.referjava.com

Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection


SOURCE : www.referjava.com

What is the difference between the >> and >>> operators?

The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.


SOURCE : www.referjava.com

How are Observer and Observable used?

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.


SOURCE : www.referjava.com

What is user defined exception ?

Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.


SOURCE : www.referjava.com

You can create a String object as String str = "abc"; Why cant a button object be created as Button bt = "abc";? Explain

The main reason you cannot create a button by Button bt1= "abc"; is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = "abc";


SOURCE : www.referjava.com

What is passed by ref and what by value ?

All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references


SOURCE : www.referjava.com

What is constructor chaining and how is it achieved in Java ?

A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.


SOURCE : www.referjava.com

Monday, February 26, 2007

What is a "stateless" protocol ?

Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination


SOURCE : www.referjava.com

Difference between a Class and an Object ?

A class is a definition or prototype whereas an object is an instance or living representation of the prototype


SOURCE : www.referjava.com

What gives java it's "write once and run anywhere" nature?

Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.


SOURCE : www.referjava.com

I made my class Cloneable but I still get 'Can't access protected method clone. Why?

Yeah, some of the Java books, in particular "The Java Programming Language", imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that's not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn't do anything special and just calls super.clone().


SOURCE : www.referjava.com

What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.


SOURCE : www.referjava.com

How is rounding performed under integer division?

The fractional part of the result is truncated. This is known as rounding toward zero.


SOURCE : www.referjava.com

Is the ternary operator written x : y ? z or x ? y : z ?

It is written x ? y : z.


SOURCE : www.referjava.com

Can an object be garbage collected while it is still reachable?

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected


SOURCE : www.referjava.com

When can an object reference be cast to an interface reference?

An object reference be cast to an interface reference when the object implements the referenced interface.


SOURCE : www.referjava.com

What is the % operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.


SOURCE : www.referjava.com

What is an object's lock and which object's have locks?

An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.


SOURCE : www.referjava.com

What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.


SOURCE : www.referjava.com

Sunday, February 25, 2007

Can a Byte object be cast to a double value?

No, an object cannot be cast to a primitive value.


SOURCE : www.referjava.com

What value does read() return when it has reached the end of a file?

The read() method returns -1 when it has reached the end of a file.


SOURCE : www.referjava.com

How are commas used in the intialization and iteration parts of a for statement?

Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

SOURCE : www.referjava.com

What is the advantage of the event-delegation model over the earlier event-inheritance model?

The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.


SOURCE : www.referjava.com

What must a class do to implement an interface?

It must provide all of the methods in the interface and identify the interface in its implements clause.


SOURCE : www.referjava.com

What is the difference between a break statement and a continue statement?

A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.


SOURCE : www.referjava.com

Can a double value be cast to a byte?

Yes, a double value can be cast to a byte.


SOURCE : www.referjava.com

Which Java operator is right associative?

The = operator is right associative.

SOURCE : www.referjava.com

What is the argument type of a program's main() method?

A program's main() method takes an argument of the String[] type.


SOURCE : www.referjava.com

How many times may an object's finalize() method be invoked by the garbage collector?

An object's finalize() method may only be invoked once by the garbage collector.


SOURCE : www.referjava.com

What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

SOURCE : www.referjava.com

What is the range of the char type?

The range of the char type is 0 to 2^16 - 1.


SOURCE : www.referjava.com

Thursday, February 22, 2007

What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause


SOURCE:www.referjava.com

What are order of precedence and associativity, and how are they used?

Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left


SOURCE:www.referjava.com

What restrictions are placed on the location of a package statement within a source code file?

A package statement must appear as the first line in a source code file (excluding blank lines and comments).


www.referjava.com

What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.


www.referjava.com

What are wrapped classes?

Wrapped classes are classes that allow primitive types to be accessed as objects.


SOURCE:www.referjava.com

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.


SOURCE:www.referjava.com

What modifiers may be used with an inner class that is a member of an outer class?

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.


SOURCE:www.referjava.com

Why do threads block on I/O?

Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.


www.referjava.com

How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com? (Networking)

String hostname = InetAddress.getByName("192.18.97.39").getHostName();


SOURCE:www.referjava.com

What does it mean that a method or field is "static"?

Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.

Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work. out is a static field in the java.lang.System class.


SOURCE:www.referjava.com

Why isn't there operator overloading?

Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn't even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().


SOURCE:www.referjava.com

What are some alternatives to inheritance?

Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).


SOURCE:www.referjava.com

Can an Interface have an inner class?

Yes public interface abc { static int i=0; void dd(); class a1 { a1() { int j; System.out.println("in interfia"); }; public static void main(String a1[]) { System.out.println("in interfia"); } } }


SOURCE:www.referjava.com

Can an Interface be final?

No


SOURCE:www.referjava.com

Why is not recommended to have instance variables in Interface?

By Default, All data members and methods in an Interface are public. Having public variables in a class that will be implementing it will be violation of the Encapsulation principal


SOURCE: www.referjava.com

Wednesday, February 21, 2007

Difference between JRE And JVM AND JDK ?

The "JDK" is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based software. The "JRE" is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs. Typically, each JDK contains one (or more) JRE's along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.


SOURCE: www.referjava.com

What is the diffrence between inner class and nested class?

When a class is defined within a scope od another class, then it becomes inner class.

If the access modifier of the inner class is static, then it becomes nested class.


SOURCE: www.referjava.com

What is the difference between an if statement and a switch statement?

The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.


SOURCE: www.referjava.com

What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.


SOURCE: www.referjava.com

How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.


SOURCE: www.referjava.com

What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.



SOURCE: www.referjava.com

What is a Java package and how is it used?

A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.


SOURCE: www.referjava.com

What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.


SOURCE: www.referjava.com

What is numeric promotion?

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required



SOURCE: www.referjava.com

Can an abstract class be final?

An abstract class may not be declared as final


SOURCE: www.referjava.com

Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException


www.referjava.com

What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.


www.referjava.com

How can a dead thread be restarted?

A dead thread cannot be restarted.


www.referjava.com

What restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return type.

The overriding method may not limit the access of the method it overrides.

The overriding method may not throw any exceptions that may not be thrown by the overridden method.


www.referjava.com

What is a compilation unit?

A compilation unit is a Java source code file.


www.referjava.com

Sunday, February 18, 2007

How can I use a variable that contains HTML?

If you have a variable like this:

example="This is a text ";

Use this in the output jsp:

bean:write property="example" filter="false"

www.referjava.com

Saturday, February 17, 2007

When converting older Java software written for JDK1.0 to run on a newer JVM, are there any issues I should be aware of?

While there have been significant improvements to the Java platform over the years in the terms of graphics, networking, performance, and other API enhancements, older software can't take advantage of these so many developers find themselves faced with the task of upgrading software. Or, as often happens, a machine running an earlier JVM for some critical application is upgraded, and a newer release is installed. How can you guarantee that there won't be any problems with your older software? Or is it safe to assume that all versions of Java are guaranteed to be backwards compatible?

It's never safe to make any assumption when it comes to JVMs. There are just too many vendors, and too many versions to keep track of. Beyond vendor incompatibilities though, there are some issues to be careful of when moving from JDK1.02 to JDK1.1, and from JDK1.1 to Java 2.

Firstly, and this is the most important, be mindful of deprecated methods. A method that has been marked as deprecated means that Sun no longer recommends using it and that an alternate mechanism should be used if at all possible. Please see an earlier FAQ on this topic located here. Remember also that if you want your new programs to run on older JDK1.0 machines, you must continue to use the deprecated methods and not newer ones that JDK1.0 is not aware of.

Secondly, there are many minor changes to the JDK tools, and JVMs, that will cause problems with older software. Generally this happens because of minor flaws in the original source code of the application, and as the JVM has improved it has become more strict. As a general rule, you shouldn't have much of a problem, but in the documentation that ships for JDK1.2 there are quite a few areas identified where problems can arise with older code
Sun documentation on compatibility problems
For JDK1.1, please see http://java.sun.com/products/jdk/1.1/compatible/index.html

For JDK 1.2, which identifies numerous problems which Java 2 has with older code, please see
http://java.sun.com/products/jdk/1.2/compatibility.html



www.referjava.com

How do I run the garbage collector to free memory and delete unused objects?

First, you should be aware that the garbage collector works automatically, whether you request it to or not. Secondly, you cannot force the garbage collector to run.

That said, you can request the garbage collector to perform work, by invoking the System.gc() method. Once working, you may experience a short pause while the garbage collector does its work. That means you should do it at an appropriate time, such as before a big task or when the GUI is idle and waiting for input.


www.referjava.com

What is a Sun Certified Java Architect? How can I become one?

Developers who have achieved a Sun Certified Java Programmer, or Sun Certified Java Developer title may want to consider becoming a certified architect. Software architecture encompasses a broad range of technologies and techniques such as :-

object oriented analysis and design (OOAD)
Unified Modeling Language (UML)
Enterprise JavaBeans (EJBs)
large scale system design
Java 2 Enterprise Edition technologies such as CORBA/RMI
internationalization and security

www.referjava.com

What does a void return value mean? Which class is being returned?

You've probably heard of this method :-

public static void main(String args[])
before. It's invoked by the JVM when starting a Java application. Have you ever wondered why it didn't have a return statement at the end of the method? After all, don't all methods return a value?

It's possible, and actually quite common, to not return a value. If you're not going to return a value, however, you must mark your method as void. This tells the compiler there's no need to enforce a return value.


www.referjava.com

How I can I return a null value from an object constructor?

The simple answer is : no, you can't.

The explanation why is simple. You don't return any value whatsoever from an object constructor. The object has already been created - in the constructor you're just initializing the object's state. So there isn't any way to return a null value.

However, if you want to throw a spanner in the works, and stop someone using your object (which is usually the intent of returning a null value, or to indicate an error), why not throw a NullPointerException ?

public MyClass()
{
// Something might go wrong, so throw a null pointer exception
throw new NullPointerException() ;
}


www.referjava.com

How I can find the class of an object?

That's easy. Suppose you've got some objects stored in a collection, like a Vector or a List of some sort. You might want to check to see if an individual object belongs to a particular class. The instanceof operator is used in this case.

For example:-

if (obj instanceof MyClass)
{
MyClass.doSomething();
}
else
{
// handle object differently .......
}


www.referjava.com

How can I append an existing file in Java?

Appending data to a file is a fairly common task. You'll be surprised to know that there was no support for file appending in JDK1.02, and developers supporting that platform are forced to re-write the entire file to a temporary file, and then overwrite the original. As most users support either JDK1.1 or the Java 2 platform, you'll probably be able to use the following FileOutputStream constructor to append data:

public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning
For example, to append the file 'autoexec.bat' to add a new path statement on a Wintel machine, you could do the following:

FileOutputStream appendedFile = new FileOutputStream
("c:\\autoexec.bat", true);


www.referjava.com

How do I kill a thread? The stop() method is deprecated in JDK1.2, so how do I shut it down?

The API documentation for JDK1.2 discusses an alternate mechanism for stopping threads, by having them continually poll a boolean flag to see if they should terminate of their own accord. This is an option, but if you have threads that become deadlocked or stall waiting for I/O, sometimes you'll have to kill them the hard way.

Why shouldn't you normally use the Thread.stop() method? Well, it is deprecated as of JDK1.2 because it can potentially leave the system in an unsafe state. If a thread
had a lock on an object (within a synchronized block), it might not release the object lock, causing problems at a later time. Note that this problem can affect older JVM implementations as well, JDK1.02 and JDK1.1 are not immune.

So while you shouldn't use Thread.stop() unless absolutely necessary, it is an acceptable way to kill a thread if it becomes stalled and you really need to shut it down fast.


www.referjava.com

What is an abstract class, and when should it be used?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Let's look at an example of an abstract class, and an abstract method.

Suppose we were modeling the behavior of animals, by creating a class hierachy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an abstract method for making a sound (such as a dog barking, a cow mooing, or a pig oinking).

public abstract Animal
{
public void eat(Food food)
{
// do something with food....
}

public void sleep(int hours)
{
try
{
// 1000 milliseconds * 60 seconds * 60 minutes * hours
Thread.sleep ( 1000 * 60 * 60 * hours);
}
catch (InterruptedException ie) { /* ignore */ }
}

public abstract void makeNoise();
}
Note that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class.

public Dog extends Animal
{
public void makeNoise() { System.out.println ("Bark! Bark!"); }
}

public Cow extends Animal
{
public void makeNoise() { System.out.println ("Moo! Moo!"); }
}
Now you may be wondering why not declare an abstract class as an interface, and have the Dog and Cow implement the interface. Sure you could - but you'd also need to implement the eat and sleep methods. By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.


www.referjava.com

What is a "magic number" in Java, and why does it sometimes go bad (referring to a bad magic number error when loading applets) ?

The class definition files (*.class) for Java applets are loaded over the network. Sometimes during the transmission of files, the connection may be aborted, or may be scrambled, causing class loading to fail. Sometimes when copying files over to a web server, they may become garbled or a disk error might occur. For this reason, special care is taken by the JVM and the class loader, to verify that classes are intact. One of the precautions is that every class definition contains at the beginning the magic number, a sequence of four bytes that identify a file as a Java class definition file.

For those curious to know what the magic number is, it is the hexadecimal number CAFEBABE, which is used by the class loader to see if a file is really a class definition file. Please don't ask me why it spells out cafebabe - my guess it was an attempt at humor.


www.referjava.com

I'm trying to compile a Java source file, and get the error message "bad command or filename". What did I do wrong?

This is a VERY frequently asked question. You need to add a path statement in your autoexec.bat file on windows to allow the javac.exe program to be found.

For example, if you installed java to the c:\java\ directory, you'd add the following to autoexec.bat

set path=%path%;c:\java\bin\

Hint: change the path to your installation dir (e.g. c:\jdk1.1.7\bin)
Remember to rerun the autoexec.bat file or reboot before trying to compile again, or the path setting will not be acted upon.


www.referjava.com

Thursday, February 15, 2007

How do I execute or run an XML file?

You can't and you don't. XML itself is not a programming language, so XML files don't ‘run’ or ‘execute’. XML is a markup specification language and XML files are just data: they sit there until you run a program which displays them (like a browser) or does some work with them (like a converter which writes the data in another format, or a database which reads the data), or modifies them (like an editor).

If you want to view or display an XML file, open it with an XML editor or an XML browser.

The water is muddied by XSL (both XSLT and XSL:FO) which use XML syntax to implement a declarative programming language. In these cases it is arguable that you can ‘execute’ XML code, by running a processing application like Saxon, which compiles the directives specified in XSLT files into Java bytecode to process XML.

www.referjava.com

Can I use JavaScript, ActiveX, etc in XML files?

This will depend on what facilities the browser makers implement. XML is about describing information; scripting languages and languages for embedded functionality are software which enables the information to be manipulated at the user's end, so these languages do not normally have any place in an XML file itself, but in stylesheets like XSL and CSS.

XML itself provides a way to define the markup needed to implement scripting languages: as a neutral standard it neither encourages not discourages their use, and does not favour one language over another, so it is possible to use XML markup to store the program code, from where it can be retrieved by (for example) XSLT and re-expressed in a HTML script element.

Server-side script embedding, like PHP or ASP, can be used with the relevant server to modify the XML code on the fly, as the document is served, just as they can with HTML. Authors should be aware, however, that embedding server-side scripting may mean the file as stored is not valid XML: it only becomes valid when processed and served, so care must be taken when using validating editors or other software to handle or manage such files. A better solution may be to use an XML serving solution like Cocoon, AxKit, or PropelX.

www.referjava.com

Can I do mathematics using XML?

Yes, if the document type you use provides for math, and your users' browsers are capable of rendering it. The mathematics-using community has developed the MathML Recommendation at the W3C, which is a native XML application suitable for embedding in other DTDs and Schemas.

It is also possible to make XML fragments from other DTDs, such as ISO 12083 Math, or OpenMath, or one of your own making. Browsers which display math embedded in SGML have existed for many years (eg DynaText, Panorama, Multidoc Pro), and mainstream browsers are now rendering MathML (eg Mozilla, Netscape). David Carlisle has produced a set of stylesheets for rendering MathML in browsers. It is also possible to use XSLT to convert XML math markup to for print (PDF) rendering, or to use XSL:FO.

www.referjava.com

How do I create my own document type?

Document types usually need a formal description, either a DTD or a Schema. Whilst it is possible to process well-formed XML documents without any such description, trying to create them without one is asking for trouble. A DTD or Schema is used with an XML editor or API interface to guide and control the construction of the document, making sure the right elements go in the right places.

Creating your own document type therefore begins with an analysis of the class of documents you want to describe: reports, invoices, letters, configuration files, credit-card verification requests, or whatever. Once you have the structure correct, you write code to express this formally, using DTD or Schema syntax.

www.referjava.com

Is there an XML version of HTML?

Yes, the W3C recommends using XHTML which is ‘a reformulation of HTML 4 in XML 1.0’. This specification defines HTML as an XML application, and provides three DTDs corresponding to the ones defined by HTML 4.* (Strict, Transitional, and Frameset).

The semantics of the elements and their attributes are as defined in the W3C Recommendation for HTML 4. These semantics provide the foundation for future extensibility of XHTML. Compatibility with existing HTML browsers is possible by following a small set of guidelines (see the W3C site).

www.referjava.com

If XML is just a subset of SGML, can I use XML files directly with existing SGML tools?

Yes, provided you use up-to-date SGML software which knows about the WebSGML Adaptations TC to ISO 8879 (the features needed to support XML, such as the variant form for EMPTY elements; some aspects of the SGML Declaration such as NAMECASE GENERAL NO; multiple attribute token list declarations, etc).

An alternative is to use an SGML DTD to let you create a fully-normalised SGML file, but one which does not use empty elements; and then remove the DocType Declaration so it becomes a well-formed DTDless XML file. Most SGML tools now handle XML files well, and provide an option switch between the two standards

www.referjava.com

Should I use XML instead of HTML?

Yes, if you need robustness, accuracy, and persistence. XML allows authors and providers to design their own document markup instead of being limited by HTML. Document types can be explicitly tailored to an application, so the cumbersome fudging and poodlefaking that has to take place with HTML becomes a thing of the past: your markup can always say what it means (trivial example: next Monday).

Information content can be richer and easier to use, because the descriptive and hypertext linking abilities of XML are much greater than those available in HTML.

XML can provide more and better facilities for browser presentation and performance, using XSLT and CSS stylesheets;

It removes many of the underlying complexities of SGML-format HTML (which led to them being ignored and broken) in favor of a more flexible model, so writing programs to handle XML is much easier than doing the same for all the old broken HTML.

Information becomes more accessible and reusable, because the more flexible markup of XML can be used by any XML software instead of being restricted to specific manufacturers as has become the case with HTML.

XML files can be used outside the Web as well, in existing document-handling environments (eg publishing).

If your information is transient, or completely static and unreferenced, or very short and simple, and unlikely to need updating, HTML may be all you need.

www.referjava.com

Who is responsible for XML?

XML is a project of the World Wide Web Consortium (W3C), and the development of the specification is supervised by an XML Working Group. A Special Interest Group of co-opted contributors and experts from various fields contributed comments and reviews by email.

XML is a public format: it is not a proprietary development of any company, although the membership of the WG and the SIG represented companies as well as industrial research and academic institutions. The v1.0 specification was accepted by the W3C as a Recommendation on Feb 10, 1998.

www.referjava.com

Why is XML such an important development?

It removes two constraints which were holding back Web developments:

dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for;

the complexity of full SGML, whose syntax allows many powerful but hard-to-program options.

XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.

www.referjava.com

Aren't XML, SGML, and HTML all the same thing?

Not quite; SGML is the mother tongue, and has been used for describing thousands of different document types in many fields of human activity, from transcriptions of ancient Irish manuscripts to the technical documentation for stealth bombers, and from patients' clinical records to musical notation. SGML is very large and complex, however, and probably overkill for most common office desktop applications.

XML is an abbreviated version of SGML, to make it easier to use over the Web, to make it easier for you to define your own document types, and to make it easier for programmers to write programs to handle them. It omits all the complex and less-used options of SGML in return for the benefits of being easier to write applications for, easier to understand, and more suited to delivery and interoperability over the Web. But it is still SGML, and XML files may still be processed in the same way as any other SGML file (see the question on XML software).

HTML is just one of many SGML or XML applications—the one most frequently used on the Web.

Technical readers may find it more useful to think of XML as being SGML−− rather than HTML++.


SOURCE : www.referjava.com

Tuesday, February 13, 2007

How can I read the status code of a HTTP request?

If you use the URL.openStream() method, there's no way to determine whether a request was successful or not. The only alternative is to use the URL.openConnection() method, which returns a URLConnection instance. The URLConnection is an abstract class, meaning that it provides a template of methods which other classes will implement. Even though the URL.openConnection() method returns a URLConnection instance, it is actually returning a concrete implementation of that class.

When a request is made for a resource using the Hypertext Transfer Protocol, the implementation of URLConnection that is returned is a java.net.HttpURLConnection. This class defines additional methods, one of which allow you to access the response status code. To find out the status of a request, you need to cast the URLConnection to a HttpURLConnection, and invoke the int HttpUrlConnection.getResponseCode() method.

URL url = new URL ( some_url );
URLConnection connection = url.openConnection();

connection.connect();

// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
{
HttpURLConnection httpConnection = (HttpURLConnection) connection;

int code = httpConnection.getResponseCode();

// do something with code .....
}
else
{
System.err.println ("error - not a http request!");
}


SOURCE : www.referjava.com

How can I create an event handling mechanism in Java? I'm used to ActiveX controls, which fire asynchronous events (i.e. when a control is finished a

The most common mechanism for this is the callback, where one class calls the method of another to notify it of an action or event. The class to be notified defines methods that will respond to specific events, such as when a mouse is clicked, dragged, or released. The AWT makes heavy use of this, with Listener interfaces. A class implements the event handling methods of a listener, and can then be registered with a component that generates these types of events. Classes that are event sources provide methods which register a listener, and at a later time when the event is generated, will invoke listener methods. The Abstract Windowing Toolkit (AWT) and Swing APIs would be a good place to start, to see if this suits your needs.


SOURCE : www.referjava.com

How can I poll a remote server, to see if it is still available? I'd like to check to see if the server has crashed, and if so, record the time.

If your application is a TCP server, the easiest way to do this is for a client to connect to it, using the java.net.Socket class. When the Socket is connected, if the server is down an IOException will be thrown, indicating that the server is not accepting connections.

However, this may not be a sufficient test for mission critical applications. What if the server has stalled, and will accept connections but not respond to them? In this situation, you'll need to write a valid request to the server (using the appropriate network protocol, such as HTTP or FTP). It doesn't matter what type of request is made, or what data is really returned (unless it is an error message). The only purpose of the request is to see if the server will response, and is still available for use.


SOURCE : www.referjava.com

Who created Java?

Java is still a relatively new language, so it is quite amusing to some to think that Java has a "history" behind it. One of the most frequent questions I've been getting lately though is about the origins of Java.

Java was created by engineers working at Sun Microsystems. The figure that stands out most of all is James Gosling, widely regarded as the "father" of Java. James and his team were working on a language whose original name was Oak. Oak was designed for embedded devices, such as mobile phones. The first publicly available version of Java, however, was as Java applets, in the original HotJava browser. From there, Java grew to what it is today.


SOURCE : www.referjava.com

How do I pass a primitive data type by reference? For example, how do I make an int passed to a function modifiable.

Java passes all primitive data types by value. This means that a copy is made, so that it cannot be modified. When passing Java objects, you're passing an object reference, which makes it possible to modify the object's member variables. If you want to pass a primitive data type by reference, you need to wrap it in an object.

The easiest of all is to pass it as an array (or even a Vector). Your array only needs to contain a single element, but wrapping it in an array means it can be changed by a function. Here's a simple example of it in action.

public static void increment(int[] array, int amount)
{
array[0] = array[0] + amount;
}

public static void main(String args[])
{
int[] myInt = { 1 };

increment (myInt, 5);

System.out.println ("Array contents : " + myInt[0]);
}
Of course, if you're modifying the contents of parameters passed to a method, you really should try to avoid this behavior. It increases the complexity of code, and really should be avoided. The preferred way is to return a value from a method, rather than modifying parameter values directly.


www.referjava.com

How do I debug my Java applets to see what's going wrong?

Often, when an applet behaves strangely or fails to work, the problem is hard to diagnose. Many applets behave fine under Netscape Navigator, only to fail under Internet Explorer (or vice versa). Sometimes a different Java Virtual Machine (JVM) will have less tolerance for a bug, and other times the fault lies in the actual JVM implementation.

The lack of information provided by the browser can be frustrating. However, there is a way to display a debugging console, which will provide developers with additional information. For example, an uncaught exception will generate an exception trace, telling you which method and which exception were involved. Both the later versions of Netscape Communicator and Internet Explorer support these debugging consoles.

To view the Java Console in Netscape Communicator
Load any page with an applet, and then select the following menu option
Communicator -> Tools -> Java Console


www.referjava.com

How do I get parameters from a HTML form when using servlets?

When extending javax.servlet.http.HttpServlet, you should override either of the following two methods: -

public void doGet(HttpServletRequest req,
HttpServletResponse res)
public void doPost(HttpServletRequest req,
HttpServletResponse res)
Both of these methods accept as a parameter a HttpServletRequest instance. This allows the servlet to obtain information about the browser request, including the parameters passed to the servlet. By using the String getParameter(String) method, you can request any parameter you need. If the parameter is not present, a null value will be returned.


www.referjava.com

How do I gray out components, and prevent users from using them?

Every AWT & Swing component inherits methods that will enable and disable it, from java.awt.Component. The setEnabled(boolean) method allows a component to be disabled, and later enabled. Previously, AWT components could be enabled and disabled by calling their enable() and disable() methods. However, these methods have been deprecated, and should no longer been used.

// Disable button (b)
b.setEnabled ( false );
// Enable button (b)
b.setEnabled ( true );


www.referjava.com

How do I make cookies expire after a set time period? For example, in five minutes time for security reasons

Depending on how you use the data stored in a cookie, it is often a good idea to make the cookie expire. Since anyone using the browser will have the cookie sent on their behalf, it may appear to be a legitimate user when in actual fact it is not. This often happens in places like Internet cafes, school or university computing labs, or libraries. If your cookie sends a user identifier that facilitates access to sensitive data, or allows changes to be made (for example, a web-based email service), then you should expire cookies after a small time period. If the user keeps using your servlet, you always have the option of resending the cookie with a longer duration.

To specify an expiration time, you can use the setMaxTime(int) method of javax.servlet.http.Cookie. It takes as a parameter the number of seconds before the cookie will expire. For example, for a five minute expiration, we would do the following :-

// Create a new cookie for userID from a fictitious
// method called getUserID
Cookie cookie = new Cookie ("userID", getUserID());

// Expire the cookie in five minutes (5 * 60)
cookie.setMaxTime( 300 );
When the cookie is sent back to the browser, using HttpServletResponse.addCookie(Cookie), it will only be returned by the browser until the expiration date occurs. If you'd prefer, you can also specify a negative value for setMaxTime(int), and the cookie will expire as soon as the browser exits. Note however that not everyone will shutdown their browser, and it might be available for minutes, hours even days. Finally, specifying a value of zero will expire the cookie instantly.


www.referjava.com

How do I read browser cookies from a servlet?

Reading cookies from a servlet is quite easy. You can gain access to any cookies sent by the browser from the javax.servlet.http.HttpServletRequest passed to the servlet's doGet, doPost, etc methods. HttpServletResponse offers a method, Cookies[] getCookies() which returns an array of Cookie objects. However, if no cookies are available, this value may be null, so be sure to check before accessing any array elements.

// Check for cookies
Cookie[] cookie_jar = request.getCookies();

// Check to see if any cookies exists
if (cookie_jar != null)
{
for (int i =0; i< cookies.length; i++)
{
Cookie aCookie = cookie_jar[i];
pout.println ("Name : " + aCookie.getName());
pout.println ("Value: " + aCookie.getValue());
}
}


www.referjava.com

How do I send cookies from a servlet?

HTTP is a stateless protocol, which makes tracking user actions difficult. One solution is to use a cookie, which is a small piece of data sent by a web browser every time it requests a page from a particular site. Servlets, and CGI scripts, can send cookies when a HTTP request is made - though as always, there is no guarantee the browser will accept it.

Cookies are represented by the javax.servlet.http.Cookie class. Cookie has a single constructor, which takes two strings (a key and a value).

// Create a new cookie
Cookie cookie = new Cookie ("counter", "1");
Adding a cookie to a browser is easy. Cookies are sent as part of a HTTPServletResponse, using the addCookie( Cookie ) method. You can call this method multiple times, but remember that most browsers impose a limit of ten cookies, and 4096 bytes of data per hostname.

public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.addCookie(new Cookie("cookie_name", "cookie_value"));
}


www.referjava.com

How do I get the length of a string?

Working with strings under Java is far easier than with other languages. Most languages represent a string as a data type, or as an array of characters. Java however treats strings as an actual object, and provides methods that make string manipulation far easier.

Strings under Java are represented by the java.lang.String class. Since the java.lang package is imported by every Java application or applet, we can refer to it just as String. To determine the length of a String, simply call the String.length() method, which returns an int value.

String aString = "this is a string. what is my length?";
int length = aString.length();

System.out.println (aString);
System.out.println (length);
TIP - Remember that the String class is zero-indexed. Even though the String is of length n, you can only access characters in the range 0..n-1


www.referjava.com

How do I minimize and restore frames and JFrames?

This question stumped me when I first took a look at it. There is no minimize or restore method in JFrame, or java.awt.Frame for that matter. However, I knew there had to be a way - as JFrames frequently need to be restored programmatically. I suspected that the problem was a difference in terminology, and after a little searching, found the answer.

JFrame inherits the setState method from java.awt.Frame. This method allows you to change the state of a window from "iconified", back to "normal". This is, in actual fact, minimize and restore - but the documentation uses different terms. To minimize or restore a window, we simply call the setState method, and pass it a state parameter to indicate whether we want to minimize or restore the window..

For example, to minimize a Frame (or subclass, such as JFrame), we pass the 'iconified' parameter

myFrame.setState ( Frame.ICONIFIED );
To restore the frame to its normal state, we call the setState method with the 'normal' parameter

myFrame.setState ( Frame.NORMAL );
To demonstrate this effect, I've written a small demonstration, which you can compile and run. In the following example, a new frame is created, and then minimized. After a short delay, it is restored again.

import java.awt.*;

public class FrameTest
{
public static void main (String args[]) throws Exception
{
// Create a test frame
Frame frame = new Frame("Hello");
frame.add ( new Label("Minimize demo") );
frame.pack();

// Show the frame
frame.setVisible (true);

// Sleep for 5 seconds, then minimize
Thread.sleep (5000);
frame.setState ( Frame.ICONIFIED );

// Sleep for 5 seconds, then restore
Thread.sleep (5000);
frame.setState ( Frame.NORMAL );

// Sleep for 5 seconds, then kill window
Thread.sleep (5000);
frame.setVisible (false);
frame.dispose();

// Terminate test
System.exit(0);
}
}


www.referjava.com

Is Java Y2K compliant? Where can I find more information?

I'd like to give a big unconditional yes, but its not quite that simple. Java is more than a language - its a platform. There are many different virtual machines, by many different vendors, running on many different hardware and software architectures. Does that present a Y2K threat? Yes.

However, work is being done to prevent problems. Sun takes its commitments very seriously - for a comprehensive list of products and their Y2K status visit

http://www.sun.com/y2000/cpl.html

The problem is - will all Java Virtual Machines be ready in time. Remember that some are third party ports, or completely re-engineered versions. So there is still the potential for problems if you use non-Sun virtual machines. If you use third party class libraries, or code, you're also running some risk. Of course, a quick test to reassure you, might be to turn your computer's clock forward till after Jan 1 2000.


www.referjava.com

What are exceptions, and when should I use them?

Exception handling is an important feature of C++ and Java. Exceptions indicate unusual error conditions that occur during the execution of an application or applet. When you call an object method, and an "exceptional" event occurs (such as being unable to access a file or network resource), the method can stop execution, and "throw" an exception. This means that it passes an object (the exception), back to the calling code. That code can then handle the event, and deal with unusual conditions.

That's the theory of exception handling. Let's look at a practical example. Suppose my application had to read some data from a file. Most times, it will be able to read the data, and continue on without any problems - but what would happen if the file didn't exist? Our program might crash, without reporting any meaningful error message. Let's see how exception handling can help.

The following code snippet shows our code for reading a line of text from a data file. Note the use the try / catch keywords. This indicates that code within this block can throw an exception, and how we will deal it.

String line;

try
{
// This line throws an IOException if file not present
FileInputStream fin = new FileInputStream ("config.ini");

// Create a data input stream for reading a line of text
DataInputStream din = new DataInputStream( fin );

// Read line of text
line = din.readLine();
}
catch (IOException ioe)
{
// Exit gracefully with an error message
System.err.println
("An error occurred while reading config file");
System.exit(0);
}
Exception handling also has other benefits. In the past, programmers would check the return value for a null object, or a special numerical code that indicated failure. But, programmers being human, this value wouldn't always be checked. This lead to strange errors at run-time, and no meaningful error messages. When an exception is specified in the throws clause of an object method, it must be caught, or the compiler will generate an error message. This forces programmers to always provide some form of catch statement (though many choose to leave their catch statement blank).

Finally, exception handling can also make code more legible. Its easy to see where error conditions are being handled, and which error conditions are explicitly being looked at. This also separates programming code for "normal" situations from that of handler code for unusual events. In small applications, the advantages of this are not noticeable, but when debugging large and complex systems, it helps to reduce complexity and track down problems.


www.referjava.com

How can I change the gray background of an applet?

Applets use a default background of gray, which isn't very visually appealing, and very infrequently matches the background of the web page on which it is loaded. So unless you repaint the background yourself in the paint() method of your applet, you'll want to change its background as soon as the applet loads.

The best place to do it will be in your init() method. This means the applet will change color once it has finished loading. To change background color, you need to invoke the setBackground(Color) method. It accepts as a parameter any valid Color.

public void init()
{
setBackground ( Color.black );
}


www.referjava.com

What does certification involve?

Passing the Sun Certified Java Programmer exam involves answering a series of multiple choice questions. Sound easy enough? There's a little more to it though - you must select ALL the right answers, without missing any or adding extra ones. Often the difference between one answer and another is subtle, and it requires a good understanding of the language and the base Java APIs. There's no reference material allowed, and to make it even tougher, a score of 70% or over is required to pass.

The second level of certification involves an additional programming task. You'll be given specifications, and have to implement the system (involving actual coding). This involves a more extensive coverage of the Java APIs, but there's often more than one way to solve a problem.


www.referjava.com

What are the Java Certification exams?

Industry certification helps to distinguish skilled software developers from the pack, and to give employers an idea of the skill level of candidates. There's a certain amount of prestige associated with certification (ask anyone who has studied for, and passed a certification exam), and its usually a good measure of skills. Like other vendors (such as Microsoft), Sun Microsystems offers certification for for its flagship - the Java language. This certification is suited to commercial Java programmers and developers.

There are two levels of Java certification available currently, and there are plans to expand into three levels in the future (in conjunction with Netscape and other vendors). Currently, Sun offers the following :-

Sun Certified Java Programmer for JDK1.05, JDK1.5 & Java 5
Sun Certified Java Developer for JDK1.04, JDK1.4 & Java 4


www.referjava.com

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

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